xref: /src/contrib/llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
171d5a254SDimitry Andric //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
26fe5c7aaSRoman Divacky //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66fe5c7aaSRoman Divacky //
76fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
86fe5c7aaSRoman Divacky //
96fe5c7aaSRoman Divacky // This file implements classes used to handle lowerings specific to common
106fe5c7aaSRoman Divacky // object file formats.
116fe5c7aaSRoman Divacky //
126fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
136fe5c7aaSRoman Divacky 
147ab83427SDimitry Andric #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
154a16efa3SDimitry Andric #include "llvm/ADT/SmallString.h"
1671d5a254SDimitry Andric #include "llvm/ADT/SmallVector.h"
174a16efa3SDimitry Andric #include "llvm/ADT/StringExtras.h"
1871d5a254SDimitry Andric #include "llvm/ADT/StringRef.h"
197ab83427SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
207ab83427SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
217ab83427SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
227ab83427SDimitry Andric #include "llvm/BinaryFormat/MachO.h"
23344a3780SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
24b60736ecSDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
25cfca06d7SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
26cfca06d7SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
2771d5a254SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
286fe5c7aaSRoman Divacky #include "llvm/CodeGen/MachineModuleInfoImpls.h"
2971d5a254SDimitry Andric #include "llvm/IR/Comdat.h"
304a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
314a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
324a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
33cfca06d7SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
34cfca06d7SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
354a16efa3SDimitry Andric #include "llvm/IR/Function.h"
3671d5a254SDimitry Andric #include "llvm/IR/GlobalAlias.h"
3771d5a254SDimitry Andric #include "llvm/IR/GlobalObject.h"
3871d5a254SDimitry Andric #include "llvm/IR/GlobalValue.h"
394a16efa3SDimitry Andric #include "llvm/IR/GlobalVariable.h"
405ca98fd9SDimitry Andric #include "llvm/IR/Mangler.h"
4171d5a254SDimitry Andric #include "llvm/IR/Metadata.h"
424a16efa3SDimitry Andric #include "llvm/IR/Module.h"
43b60736ecSDimitry Andric #include "llvm/IR/PseudoProbe.h"
4471d5a254SDimitry Andric #include "llvm/IR/Type.h"
45dd58ef01SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
46ac9a064cSDimitry Andric #include "llvm/MC/MCAsmInfoDarwin.h"
476fe5c7aaSRoman Divacky #include "llvm/MC/MCContext.h"
486fe5c7aaSRoman Divacky #include "llvm/MC/MCExpr.h"
49abdf259dSRoman Divacky #include "llvm/MC/MCSectionCOFF.h"
504a16efa3SDimitry Andric #include "llvm/MC/MCSectionELF.h"
51344a3780SDimitry Andric #include "llvm/MC/MCSectionGOFF.h"
524a16efa3SDimitry Andric #include "llvm/MC/MCSectionMachO.h"
5371d5a254SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
541d5ae102SDimitry Andric #include "llvm/MC/MCSectionXCOFF.h"
556b943ff3SDimitry Andric #include "llvm/MC/MCStreamer.h"
5671d5a254SDimitry Andric #include "llvm/MC/MCSymbol.h"
5785d8b2bbSDimitry Andric #include "llvm/MC/MCSymbolELF.h"
585a5ac124SDimitry Andric #include "llvm/MC/MCValue.h"
5971d5a254SDimitry Andric #include "llvm/MC/SectionKind.h"
6001095a5dSDimitry Andric #include "llvm/ProfileData/InstrProf.h"
61e3b55780SDimitry Andric #include "llvm/Support/Base64.h"
6271d5a254SDimitry Andric #include "llvm/Support/Casting.h"
6371d5a254SDimitry Andric #include "llvm/Support/CodeGen.h"
646fe5c7aaSRoman Divacky #include "llvm/Support/ErrorHandling.h"
65cfca06d7SDimitry Andric #include "llvm/Support/Format.h"
666fe5c7aaSRoman Divacky #include "llvm/Support/raw_ostream.h"
674a16efa3SDimitry Andric #include "llvm/Target/TargetMachine.h"
687fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
6971d5a254SDimitry Andric #include <cassert>
7071d5a254SDimitry Andric #include <string>
7171d5a254SDimitry Andric 
726fe5c7aaSRoman Divacky using namespace llvm;
7367a71b31SRoman Divacky using namespace dwarf;
746fe5c7aaSRoman Divacky 
757fa27ce4SDimitry Andric static cl::opt<bool> JumpTableInFunctionSection(
767fa27ce4SDimitry Andric     "jumptable-in-function-section", cl::Hidden, cl::init(false),
777fa27ce4SDimitry Andric     cl::desc("Putting Jump Table in function section"));
787fa27ce4SDimitry Andric 
GetObjCImageInfo(Module & M,unsigned & Version,unsigned & Flags,StringRef & Section)797c7aba6eSDimitry Andric static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
807ab83427SDimitry Andric                              StringRef &Section) {
817c7aba6eSDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
827c7aba6eSDimitry Andric   M.getModuleFlagsMetadata(ModuleFlags);
837c7aba6eSDimitry Andric 
847ab83427SDimitry Andric   for (const auto &MFE: ModuleFlags) {
857ab83427SDimitry Andric     // Ignore flags with 'Require' behaviour.
867ab83427SDimitry Andric     if (MFE.Behavior == Module::Require)
877ab83427SDimitry Andric       continue;
887ab83427SDimitry Andric 
897ab83427SDimitry Andric     StringRef Key = MFE.Key->getString();
907ab83427SDimitry Andric     if (Key == "Objective-C Image Info Version") {
917ab83427SDimitry Andric       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
927ab83427SDimitry Andric     } else if (Key == "Objective-C Garbage Collection" ||
937ab83427SDimitry Andric                Key == "Objective-C GC Only" ||
947ab83427SDimitry Andric                Key == "Objective-C Is Simulated" ||
957ab83427SDimitry Andric                Key == "Objective-C Class Properties" ||
967ab83427SDimitry Andric                Key == "Objective-C Image Swift Version") {
977ab83427SDimitry Andric       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
987ab83427SDimitry Andric     } else if (Key == "Objective-C Image Info Section") {
997ab83427SDimitry Andric       Section = cast<MDString>(MFE.Val)->getString();
1007ab83427SDimitry Andric     }
101cfca06d7SDimitry Andric     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
102cfca06d7SDimitry Andric     // "Objective-C Garbage Collection".
103cfca06d7SDimitry Andric     else if (Key == "Swift ABI Version") {
104cfca06d7SDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
105cfca06d7SDimitry Andric     } else if (Key == "Swift Major Version") {
106cfca06d7SDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
107cfca06d7SDimitry Andric     } else if (Key == "Swift Minor Version") {
108cfca06d7SDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
109cfca06d7SDimitry Andric     }
1107ab83427SDimitry Andric   }
1117ab83427SDimitry Andric }
1127ab83427SDimitry Andric 
1136fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
1146fe5c7aaSRoman Divacky //                                  ELF
1156fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
1166fe5c7aaSRoman Divacky 
TargetLoweringObjectFileELF()1176f8fc217SDimitry Andric TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
118b60736ecSDimitry Andric   SupportDSOLocalEquivalentLowering = true;
119b60736ecSDimitry Andric }
120b60736ecSDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TgtM)121eb11fae6SDimitry Andric void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
122eb11fae6SDimitry Andric                                              const TargetMachine &TgtM) {
123eb11fae6SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
124d8e91e46SDimitry Andric 
125d8e91e46SDimitry Andric   CodeModel::Model CM = TgtM.getCodeModel();
126cfca06d7SDimitry Andric   InitializeELF(TgtM.Options.UseInitArray);
127d8e91e46SDimitry Andric 
128d8e91e46SDimitry Andric   switch (TgtM.getTargetTriple().getArch()) {
129d8e91e46SDimitry Andric   case Triple::arm:
130d8e91e46SDimitry Andric   case Triple::armeb:
131d8e91e46SDimitry Andric   case Triple::thumb:
132d8e91e46SDimitry Andric   case Triple::thumbeb:
133d8e91e46SDimitry Andric     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
134d8e91e46SDimitry Andric       break;
135d8e91e46SDimitry Andric     // Fallthrough if not using EHABI
136e3b55780SDimitry Andric     [[fallthrough]];
137d8e91e46SDimitry Andric   case Triple::ppc:
138b60736ecSDimitry Andric   case Triple::ppcle:
139d8e91e46SDimitry Andric   case Triple::x86:
140d8e91e46SDimitry Andric     PersonalityEncoding = isPositionIndependent()
141d8e91e46SDimitry Andric                               ? dwarf::DW_EH_PE_indirect |
142d8e91e46SDimitry Andric                                     dwarf::DW_EH_PE_pcrel |
143d8e91e46SDimitry Andric                                     dwarf::DW_EH_PE_sdata4
144d8e91e46SDimitry Andric                               : dwarf::DW_EH_PE_absptr;
145d8e91e46SDimitry Andric     LSDAEncoding = isPositionIndependent()
146d8e91e46SDimitry Andric                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
147d8e91e46SDimitry Andric                        : dwarf::DW_EH_PE_absptr;
148d8e91e46SDimitry Andric     TTypeEncoding = isPositionIndependent()
149d8e91e46SDimitry Andric                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
150d8e91e46SDimitry Andric                               dwarf::DW_EH_PE_sdata4
151d8e91e46SDimitry Andric                         : dwarf::DW_EH_PE_absptr;
152d8e91e46SDimitry Andric     break;
153d8e91e46SDimitry Andric   case Triple::x86_64:
154d8e91e46SDimitry Andric     if (isPositionIndependent()) {
155d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
156d8e91e46SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
157d8e91e46SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
158d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
159d8e91e46SDimitry Andric         (CM == CodeModel::Small
160d8e91e46SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
161d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
162d8e91e46SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
163344a3780SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
164d8e91e46SDimitry Andric     } else {
165d8e91e46SDimitry Andric       PersonalityEncoding =
166d8e91e46SDimitry Andric         (CM == CodeModel::Small || CM == CodeModel::Medium)
167d8e91e46SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
168d8e91e46SDimitry Andric       LSDAEncoding = (CM == CodeModel::Small)
169d8e91e46SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
170d8e91e46SDimitry Andric       TTypeEncoding = (CM == CodeModel::Small)
171d8e91e46SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
172d8e91e46SDimitry Andric     }
173d8e91e46SDimitry Andric     break;
174d8e91e46SDimitry Andric   case Triple::hexagon:
175d8e91e46SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
176d8e91e46SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
177d8e91e46SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
178d8e91e46SDimitry Andric     if (isPositionIndependent()) {
179d8e91e46SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
180d8e91e46SDimitry Andric       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
181d8e91e46SDimitry Andric       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
182d8e91e46SDimitry Andric     }
183d8e91e46SDimitry Andric     break;
184d8e91e46SDimitry Andric   case Triple::aarch64:
185d8e91e46SDimitry Andric   case Triple::aarch64_be:
1861d5ae102SDimitry Andric   case Triple::aarch64_32:
187d8e91e46SDimitry Andric     // The small model guarantees static code/data size < 4GB, but not where it
188d8e91e46SDimitry Andric     // will be in memory. Most of these could end up >2GB away so even a signed
189d8e91e46SDimitry Andric     // pc-relative 32-bit address is insufficient, theoretically.
1907fa27ce4SDimitry Andric     //
1917fa27ce4SDimitry Andric     // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
1927fa27ce4SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel |
1937fa27ce4SDimitry Andric                    (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32
1947fa27ce4SDimitry Andric                         ? dwarf::DW_EH_PE_sdata4
1957fa27ce4SDimitry Andric                         : dwarf::DW_EH_PE_sdata8);
1967fa27ce4SDimitry Andric     PersonalityEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect;
1977fa27ce4SDimitry Andric     TTypeEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect;
198d8e91e46SDimitry Andric     break;
199d8e91e46SDimitry Andric   case Triple::lanai:
200d8e91e46SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
201d8e91e46SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
202d8e91e46SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
203d8e91e46SDimitry Andric     break;
204d8e91e46SDimitry Andric   case Triple::mips:
205d8e91e46SDimitry Andric   case Triple::mipsel:
206d8e91e46SDimitry Andric   case Triple::mips64:
207d8e91e46SDimitry Andric   case Triple::mips64el:
208d8e91e46SDimitry Andric     // MIPS uses indirect pointer to refer personality functions and types, so
209d8e91e46SDimitry Andric     // that the eh_frame section can be read-only. DW.ref.personality will be
210d8e91e46SDimitry Andric     // generated for relocation.
211d8e91e46SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
212d8e91e46SDimitry Andric     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
213d8e91e46SDimitry Andric     //        identify N64 from just a triple.
214d8e91e46SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
215d8e91e46SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
216d8e91e46SDimitry Andric 
217d8e91e46SDimitry Andric     // FreeBSD must be explicit about the data size and using pcrel since it's
218d8e91e46SDimitry Andric     // assembler/linker won't do the automatic conversion that the Linux tools
219d8e91e46SDimitry Andric     // do.
220ac9a064cSDimitry Andric     if (isPositionIndependent() || TgtM.getTargetTriple().isOSFreeBSD()) {
221d8e91e46SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
222d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
223d8e91e46SDimitry Andric     }
224d8e91e46SDimitry Andric     break;
225d8e91e46SDimitry Andric   case Triple::ppc64:
226d8e91e46SDimitry Andric   case Triple::ppc64le:
227d8e91e46SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
228d8e91e46SDimitry Andric       dwarf::DW_EH_PE_udata8;
229d8e91e46SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
230d8e91e46SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
231d8e91e46SDimitry Andric       dwarf::DW_EH_PE_udata8;
232d8e91e46SDimitry Andric     break;
233d8e91e46SDimitry Andric   case Triple::sparcel:
234d8e91e46SDimitry Andric   case Triple::sparc:
235d8e91e46SDimitry Andric     if (isPositionIndependent()) {
236d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
237d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
238d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
239d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
240d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
241d8e91e46SDimitry Andric     } else {
242d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
243d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
244d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
245d8e91e46SDimitry Andric     }
246e6d15924SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
247e6d15924SDimitry Andric     break;
248e6d15924SDimitry Andric   case Triple::riscv32:
249e6d15924SDimitry Andric   case Triple::riscv64:
250e6d15924SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
251e6d15924SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
252e6d15924SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
253e6d15924SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
254e6d15924SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
255e6d15924SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
256d8e91e46SDimitry Andric     break;
257d8e91e46SDimitry Andric   case Triple::sparcv9:
258d8e91e46SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
259d8e91e46SDimitry Andric     if (isPositionIndependent()) {
260d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
261d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
262d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
263d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
264d8e91e46SDimitry Andric     } else {
265d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
266d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
267d8e91e46SDimitry Andric     }
268d8e91e46SDimitry Andric     break;
269d8e91e46SDimitry Andric   case Triple::systemz:
270d8e91e46SDimitry Andric     // All currently-defined code models guarantee that 4-byte PC-relative
271d8e91e46SDimitry Andric     // values will be in range.
272d8e91e46SDimitry Andric     if (isPositionIndependent()) {
273d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
274d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
275d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
276d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
277d8e91e46SDimitry Andric         dwarf::DW_EH_PE_sdata4;
278d8e91e46SDimitry Andric     } else {
279d8e91e46SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
280d8e91e46SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
281d8e91e46SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
282d8e91e46SDimitry Andric     }
283d8e91e46SDimitry Andric     break;
284e3b55780SDimitry Andric   case Triple::loongarch32:
285e3b55780SDimitry Andric   case Triple::loongarch64:
286e3b55780SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
287e3b55780SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
288e3b55780SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
289e3b55780SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
290e3b55780SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
291e3b55780SDimitry Andric     break;
292d8e91e46SDimitry Andric   default:
293d8e91e46SDimitry Andric     break;
294d8e91e46SDimitry Andric   }
295eb11fae6SDimitry Andric }
296eb11fae6SDimitry Andric 
getModuleMetadata(Module & M)297344a3780SDimitry Andric void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
298344a3780SDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
299344a3780SDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
300344a3780SDimitry Andric   for (GlobalValue *GV : Vec)
301344a3780SDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
302344a3780SDimitry Andric       Used.insert(GO);
303344a3780SDimitry Andric }
304344a3780SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const305eb11fae6SDimitry Andric void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
306eb11fae6SDimitry Andric                                                      Module &M) const {
307eb11fae6SDimitry Andric   auto &C = getContext();
308eb11fae6SDimitry Andric 
309eb11fae6SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
310eb11fae6SDimitry Andric     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
311eb11fae6SDimitry Andric                               ELF::SHF_EXCLUDE);
312eb11fae6SDimitry Andric 
313145449b1SDimitry Andric     Streamer.switchSection(S);
314eb11fae6SDimitry Andric 
315706b4fc4SDimitry Andric     for (const auto *Operand : LinkerOptions->operands()) {
316eb11fae6SDimitry Andric       if (cast<MDNode>(Operand)->getNumOperands() != 2)
317eb11fae6SDimitry Andric         report_fatal_error("invalid llvm.linker.options");
318eb11fae6SDimitry Andric       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
319cfca06d7SDimitry Andric         Streamer.emitBytes(cast<MDString>(Option)->getString());
320cfca06d7SDimitry Andric         Streamer.emitInt8(0);
321eb11fae6SDimitry Andric       }
322eb11fae6SDimitry Andric     }
323eb11fae6SDimitry Andric   }
324eb11fae6SDimitry Andric 
325e6d15924SDimitry Andric   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
326e6d15924SDimitry Andric     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
327344a3780SDimitry Andric                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
328e6d15924SDimitry Andric 
329145449b1SDimitry Andric     Streamer.switchSection(S);
330e6d15924SDimitry Andric 
331706b4fc4SDimitry Andric     for (const auto *Operand : DependentLibraries->operands()) {
332cfca06d7SDimitry Andric       Streamer.emitBytes(
333e6d15924SDimitry Andric           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
334cfca06d7SDimitry Andric       Streamer.emitInt8(0);
335e6d15924SDimitry Andric     }
336e6d15924SDimitry Andric   }
337e6d15924SDimitry Andric 
338b60736ecSDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
339b60736ecSDimitry Andric     // Emit a descriptor for every function including functions that have an
340b60736ecSDimitry Andric     // available external linkage. We may not want this for imported functions
341b60736ecSDimitry Andric     // that has code in another thinLTO module but we don't have a good way to
342b60736ecSDimitry Andric     // tell them apart from inline functions defined in header files. Therefore
343b60736ecSDimitry Andric     // we put each descriptor in a separate comdat section and rely on the
344b60736ecSDimitry Andric     // linker to deduplicate.
345b60736ecSDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
346b60736ecSDimitry Andric       const auto *MD = cast<MDNode>(Operand);
347b60736ecSDimitry Andric       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
348b60736ecSDimitry Andric       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
349b60736ecSDimitry Andric       auto *Name = cast<MDString>(MD->getOperand(2));
350b60736ecSDimitry Andric       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
351b60736ecSDimitry Andric           TM->getFunctionSections() ? Name->getString() : StringRef());
352b60736ecSDimitry Andric 
353145449b1SDimitry Andric       Streamer.switchSection(S);
354b60736ecSDimitry Andric       Streamer.emitInt64(GUID->getZExtValue());
355b60736ecSDimitry Andric       Streamer.emitInt64(Hash->getZExtValue());
356b60736ecSDimitry Andric       Streamer.emitULEB128IntValue(Name->getString().size());
357b60736ecSDimitry Andric       Streamer.emitBytes(Name->getString());
358b60736ecSDimitry Andric     }
359b60736ecSDimitry Andric   }
360b60736ecSDimitry Andric 
361e3b55780SDimitry Andric   if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
362e3b55780SDimitry Andric     // Emit the metadata for llvm statistics into .llvm_stats section, which is
363e3b55780SDimitry Andric     // formatted as a list of key/value pair, the value is base64 encoded.
364e3b55780SDimitry Andric     auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
365e3b55780SDimitry Andric     Streamer.switchSection(S);
366e3b55780SDimitry Andric     for (const auto *Operand : LLVMStats->operands()) {
367e3b55780SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
368e3b55780SDimitry Andric       assert(MD->getNumOperands() % 2 == 0 &&
369e3b55780SDimitry Andric              ("Operand num should be even for a list of key/value pair"));
370e3b55780SDimitry Andric       for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
371e3b55780SDimitry Andric         // Encode the key string size.
372e3b55780SDimitry Andric         auto *Key = cast<MDString>(MD->getOperand(I));
373e3b55780SDimitry Andric         Streamer.emitULEB128IntValue(Key->getString().size());
374e3b55780SDimitry Andric         Streamer.emitBytes(Key->getString());
375e3b55780SDimitry Andric         // Encode the value into a Base64 string.
376e3b55780SDimitry Andric         std::string Value = encodeBase64(
377e3b55780SDimitry Andric             Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
378e3b55780SDimitry Andric                       ->getZExtValue())
379e3b55780SDimitry Andric                 .str());
380e3b55780SDimitry Andric         Streamer.emitULEB128IntValue(Value.size());
381e3b55780SDimitry Andric         Streamer.emitBytes(Value);
382e3b55780SDimitry Andric       }
383e3b55780SDimitry Andric     }
384e3b55780SDimitry Andric   }
385e3b55780SDimitry Andric 
3867ab83427SDimitry Andric   unsigned Version = 0;
3877ab83427SDimitry Andric   unsigned Flags = 0;
3887ab83427SDimitry Andric   StringRef Section;
3897ab83427SDimitry Andric 
3907c7aba6eSDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
391eb11fae6SDimitry Andric   if (!Section.empty()) {
3927ab83427SDimitry Andric     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
393145449b1SDimitry Andric     Streamer.switchSection(S);
394cfca06d7SDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
395cfca06d7SDimitry Andric     Streamer.emitInt32(Version);
396cfca06d7SDimitry Andric     Streamer.emitInt32(Flags);
397145449b1SDimitry Andric     Streamer.addBlankLine();
3987ab83427SDimitry Andric   }
3997ab83427SDimitry Andric 
400b60736ecSDimitry Andric   emitCGProfileMetadata(Streamer, M);
401eb11fae6SDimitry Andric }
402eb11fae6SDimitry Andric 
getCFIPersonalitySymbol(const GlobalValue * GV,const TargetMachine & TM,MachineModuleInfo * MMI) const4035ca98fd9SDimitry Andric MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
404b915e9e0SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
4056b943ff3SDimitry Andric     MachineModuleInfo *MMI) const {
4066b943ff3SDimitry Andric   unsigned Encoding = getPersonalityEncoding();
40771d5a254SDimitry Andric   if ((Encoding & 0x80) == DW_EH_PE_indirect)
4085a5ac124SDimitry Andric     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
409b915e9e0SDimitry Andric                                           TM.getSymbol(GV)->getName());
41071d5a254SDimitry Andric   if ((Encoding & 0x70) == DW_EH_PE_absptr)
411b915e9e0SDimitry Andric     return TM.getSymbol(GV);
4125ca98fd9SDimitry Andric   report_fatal_error("We do not support this DWARF encoding yet!");
4136b943ff3SDimitry Andric }
4146b943ff3SDimitry Andric 
emitPersonalityValue(MCStreamer & Streamer,const DataLayout & DL,const MCSymbol * Sym) const415dd58ef01SDimitry Andric void TargetLoweringObjectFileELF::emitPersonalityValue(
416dd58ef01SDimitry Andric     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
417411bd29eSDimitry Andric   SmallString<64> NameData("DW.ref.");
418411bd29eSDimitry Andric   NameData += Sym->getName();
41985d8b2bbSDimitry Andric   MCSymbolELF *Label =
42085d8b2bbSDimitry Andric       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
421cfca06d7SDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
422cfca06d7SDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
4236b943ff3SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
42401095a5dSDimitry Andric   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
42501095a5dSDimitry Andric                                                    ELF::SHT_PROGBITS, Flags, 0);
426dd58ef01SDimitry Andric   unsigned Size = DL.getPointerSize();
427145449b1SDimitry Andric   Streamer.switchSection(Sec);
428e3b55780SDimitry Andric   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
429cfca06d7SDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
43085d8b2bbSDimitry Andric   const MCExpr *E = MCConstantExpr::create(Size, getContext());
43185d8b2bbSDimitry Andric   Streamer.emitELFSize(Label, E);
432cfca06d7SDimitry Andric   Streamer.emitLabel(Label);
4336b943ff3SDimitry Andric 
434cfca06d7SDimitry Andric   Streamer.emitSymbolValue(Sym, Size);
4356b943ff3SDimitry Andric }
4366b943ff3SDimitry Andric 
getTTypeGlobalReference(const GlobalValue * GV,unsigned Encoding,const TargetMachine & TM,MachineModuleInfo * MMI,MCStreamer & Streamer) const4375ca98fd9SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
438b915e9e0SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
439b915e9e0SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
44071d5a254SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
4414a16efa3SDimitry Andric     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
4424a16efa3SDimitry Andric 
443b915e9e0SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
4444a16efa3SDimitry Andric 
4454a16efa3SDimitry Andric     // Add information about the stub reference to ELFMMI so that the stub
4464a16efa3SDimitry Andric     // gets emitted by the asmprinter.
4474a16efa3SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
4485ca98fd9SDimitry Andric     if (!StubSym.getPointer()) {
449b915e9e0SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
4504a16efa3SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
4514a16efa3SDimitry Andric     }
4524a16efa3SDimitry Andric 
4534a16efa3SDimitry Andric     return TargetLoweringObjectFile::
45485d8b2bbSDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
45571d5a254SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
4564a16efa3SDimitry Andric   }
4574a16efa3SDimitry Andric 
458b915e9e0SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
459b915e9e0SDimitry Andric                                                            MMI, Streamer);
4604a16efa3SDimitry Andric }
4614a16efa3SDimitry Andric 
getELFKindForNamedSection(StringRef Name,SectionKind K)462044eb2f6SDimitry Andric static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
463eb11fae6SDimitry Andric   // N.B.: The defaults used in here are not the same ones used in MC.
46456fe8f14SDimitry Andric   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
46556fe8f14SDimitry Andric   // both gas and MC will produce a section with no flags. Given
46658b69754SDimitry Andric   // section(".eh_frame") gcc will produce:
46758b69754SDimitry Andric   //
46856fe8f14SDimitry Andric   //   .section   .eh_frame,"a",@progbits
46901095a5dSDimitry Andric 
47071d5a254SDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
471cfca06d7SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
472cfca06d7SDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
473b60736ecSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
474312c0ed1SDimitry Andric       Name == getInstrProfSectionName(IPSK_covdata, Triple::ELF,
475312c0ed1SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
476312c0ed1SDimitry Andric       Name == getInstrProfSectionName(IPSK_covname, Triple::ELF,
477312c0ed1SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
478b60736ecSDimitry Andric       Name == ".llvmbc" || Name == ".llvmcmd")
47901095a5dSDimitry Andric     return SectionKind::getMetadata();
48001095a5dSDimitry Andric 
481ac9a064cSDimitry Andric   if (!Name.starts_with(".")) return K;
4826fe5c7aaSRoman Divacky 
483eb11fae6SDimitry Andric   // Default implementation based on some magic section names.
484312c0ed1SDimitry Andric   if (Name == ".bss" || Name.starts_with(".bss.") ||
485312c0ed1SDimitry Andric       Name.starts_with(".gnu.linkonce.b.") ||
486312c0ed1SDimitry Andric       Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
487312c0ed1SDimitry Andric       Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
488312c0ed1SDimitry Andric       Name.starts_with(".llvm.linkonce.sb."))
4896fe5c7aaSRoman Divacky     return SectionKind::getBSS();
4906fe5c7aaSRoman Divacky 
491312c0ed1SDimitry Andric   if (Name == ".tdata" || Name.starts_with(".tdata.") ||
492312c0ed1SDimitry Andric       Name.starts_with(".gnu.linkonce.td.") ||
493312c0ed1SDimitry Andric       Name.starts_with(".llvm.linkonce.td."))
4946fe5c7aaSRoman Divacky     return SectionKind::getThreadData();
4956fe5c7aaSRoman Divacky 
496312c0ed1SDimitry Andric   if (Name == ".tbss" || Name.starts_with(".tbss.") ||
497312c0ed1SDimitry Andric       Name.starts_with(".gnu.linkonce.tb.") ||
498312c0ed1SDimitry Andric       Name.starts_with(".llvm.linkonce.tb."))
4996fe5c7aaSRoman Divacky     return SectionKind::getThreadBSS();
5006fe5c7aaSRoman Divacky 
5016fe5c7aaSRoman Divacky   return K;
5026fe5c7aaSRoman Divacky }
5036fe5c7aaSRoman Divacky 
hasPrefix(StringRef SectionName,StringRef Prefix)5046f8fc217SDimitry Andric static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
5056f8fc217SDimitry Andric   return SectionName.consume_front(Prefix) &&
5066f8fc217SDimitry Andric          (SectionName.empty() || SectionName[0] == '.');
5076f8fc217SDimitry Andric }
5086f8fc217SDimitry Andric 
getELFSectionType(StringRef Name,SectionKind K)5096fe5c7aaSRoman Divacky static unsigned getELFSectionType(StringRef Name, SectionKind K) {
510b915e9e0SDimitry Andric   // Use SHT_NOTE for section whose name starts with ".note" to allow
511b915e9e0SDimitry Andric   // emitting ELF notes from C variable declaration.
512b915e9e0SDimitry Andric   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
513312c0ed1SDimitry Andric   if (Name.starts_with(".note"))
514b915e9e0SDimitry Andric     return ELF::SHT_NOTE;
5156fe5c7aaSRoman Divacky 
5166f8fc217SDimitry Andric   if (hasPrefix(Name, ".init_array"))
517cf099d11SDimitry Andric     return ELF::SHT_INIT_ARRAY;
5186fe5c7aaSRoman Divacky 
5196f8fc217SDimitry Andric   if (hasPrefix(Name, ".fini_array"))
520cf099d11SDimitry Andric     return ELF::SHT_FINI_ARRAY;
5216fe5c7aaSRoman Divacky 
5226f8fc217SDimitry Andric   if (hasPrefix(Name, ".preinit_array"))
523cf099d11SDimitry Andric     return ELF::SHT_PREINIT_ARRAY;
5246fe5c7aaSRoman Divacky 
5251f917f69SDimitry Andric   if (hasPrefix(Name, ".llvm.offloading"))
5261f917f69SDimitry Andric     return ELF::SHT_LLVM_OFFLOADING;
527ac9a064cSDimitry Andric   if (Name == ".llvm.lto")
528ac9a064cSDimitry Andric     return ELF::SHT_LLVM_LTO;
5291f917f69SDimitry Andric 
5306fe5c7aaSRoman Divacky   if (K.isBSS() || K.isThreadBSS())
531cf099d11SDimitry Andric     return ELF::SHT_NOBITS;
5326fe5c7aaSRoman Divacky 
533cf099d11SDimitry Andric   return ELF::SHT_PROGBITS;
5346fe5c7aaSRoman Divacky }
5356fe5c7aaSRoman Divacky 
getELFSectionFlags(SectionKind K)5365a5ac124SDimitry Andric static unsigned getELFSectionFlags(SectionKind K) {
5376fe5c7aaSRoman Divacky   unsigned Flags = 0;
5386fe5c7aaSRoman Divacky 
539145449b1SDimitry Andric   if (!K.isMetadata() && !K.isExclude())
540cf099d11SDimitry Andric     Flags |= ELF::SHF_ALLOC;
5416fe5c7aaSRoman Divacky 
542145449b1SDimitry Andric   if (K.isExclude())
543145449b1SDimitry Andric     Flags |= ELF::SHF_EXCLUDE;
544145449b1SDimitry Andric 
5456fe5c7aaSRoman Divacky   if (K.isText())
546cf099d11SDimitry Andric     Flags |= ELF::SHF_EXECINSTR;
5476fe5c7aaSRoman Divacky 
548b915e9e0SDimitry Andric   if (K.isExecuteOnly())
549b915e9e0SDimitry Andric     Flags |= ELF::SHF_ARM_PURECODE;
550b915e9e0SDimitry Andric 
5516fe5c7aaSRoman Divacky   if (K.isWriteable())
552cf099d11SDimitry Andric     Flags |= ELF::SHF_WRITE;
5536fe5c7aaSRoman Divacky 
5546fe5c7aaSRoman Divacky   if (K.isThreadLocal())
555cf099d11SDimitry Andric     Flags |= ELF::SHF_TLS;
5566fe5c7aaSRoman Divacky 
5575a5ac124SDimitry Andric   if (K.isMergeableCString() || K.isMergeableConst())
558cf099d11SDimitry Andric     Flags |= ELF::SHF_MERGE;
5596fe5c7aaSRoman Divacky 
5606fe5c7aaSRoman Divacky   if (K.isMergeableCString())
561cf099d11SDimitry Andric     Flags |= ELF::SHF_STRINGS;
5626fe5c7aaSRoman Divacky 
5636fe5c7aaSRoman Divacky   return Flags;
5646fe5c7aaSRoman Divacky }
5656fe5c7aaSRoman Divacky 
getELFComdat(const GlobalValue * GV)5665ca98fd9SDimitry Andric static const Comdat *getELFComdat(const GlobalValue *GV) {
5675ca98fd9SDimitry Andric   const Comdat *C = GV->getComdat();
5685ca98fd9SDimitry Andric   if (!C)
5695ca98fd9SDimitry Andric     return nullptr;
5706fe5c7aaSRoman Divacky 
571344a3780SDimitry Andric   if (C->getSelectionKind() != Comdat::Any &&
572344a3780SDimitry Andric       C->getSelectionKind() != Comdat::NoDeduplicate)
573344a3780SDimitry Andric     report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
574344a3780SDimitry Andric                        "SelectionKind::NoDeduplicate, '" +
5755ca98fd9SDimitry Andric                        C->getName() + "' cannot be lowered.");
5765ca98fd9SDimitry Andric 
5775ca98fd9SDimitry Andric   return C;
5785ca98fd9SDimitry Andric }
5795ca98fd9SDimitry Andric 
getLinkedToSymbol(const GlobalObject * GO,const TargetMachine & TM)580cfca06d7SDimitry Andric static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
58171d5a254SDimitry Andric                                             const TargetMachine &TM) {
58271d5a254SDimitry Andric   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
58371d5a254SDimitry Andric   if (!MD)
58471d5a254SDimitry Andric     return nullptr;
58571d5a254SDimitry Andric 
5867fa27ce4SDimitry Andric   auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
5871d5ae102SDimitry Andric   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
5881d5ae102SDimitry Andric   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
58971d5a254SDimitry Andric }
59071d5a254SDimitry Andric 
getEntrySizeForKind(SectionKind Kind)591d8e91e46SDimitry Andric static unsigned getEntrySizeForKind(SectionKind Kind) {
592d8e91e46SDimitry Andric   if (Kind.isMergeable1ByteCString())
593d8e91e46SDimitry Andric     return 1;
594d8e91e46SDimitry Andric   else if (Kind.isMergeable2ByteCString())
595d8e91e46SDimitry Andric     return 2;
596d8e91e46SDimitry Andric   else if (Kind.isMergeable4ByteCString())
597d8e91e46SDimitry Andric     return 4;
598d8e91e46SDimitry Andric   else if (Kind.isMergeableConst4())
599d8e91e46SDimitry Andric     return 4;
600d8e91e46SDimitry Andric   else if (Kind.isMergeableConst8())
601d8e91e46SDimitry Andric     return 8;
602d8e91e46SDimitry Andric   else if (Kind.isMergeableConst16())
603d8e91e46SDimitry Andric     return 16;
604d8e91e46SDimitry Andric   else if (Kind.isMergeableConst32())
605d8e91e46SDimitry Andric     return 32;
606d8e91e46SDimitry Andric   else {
607d8e91e46SDimitry Andric     // We shouldn't have mergeable C strings or mergeable constants that we
608d8e91e46SDimitry Andric     // didn't handle above.
609d8e91e46SDimitry Andric     assert(!Kind.isMergeableCString() && "unknown string width");
610d8e91e46SDimitry Andric     assert(!Kind.isMergeableConst() && "unknown data width");
611d8e91e46SDimitry Andric     return 0;
612d8e91e46SDimitry Andric   }
613d8e91e46SDimitry Andric }
614d8e91e46SDimitry Andric 
615cfca06d7SDimitry Andric /// Return the section prefix name used by options FunctionsSections and
616cfca06d7SDimitry Andric /// DataSections.
getSectionPrefixForGlobal(SectionKind Kind,bool IsLarge)6177fa27ce4SDimitry Andric static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge) {
618cfca06d7SDimitry Andric   if (Kind.isText())
619b1c73532SDimitry Andric     return IsLarge ? ".ltext" : ".text";
620cfca06d7SDimitry Andric   if (Kind.isReadOnly())
6217fa27ce4SDimitry Andric     return IsLarge ? ".lrodata" : ".rodata";
622cfca06d7SDimitry Andric   if (Kind.isBSS())
6237fa27ce4SDimitry Andric     return IsLarge ? ".lbss" : ".bss";
624cfca06d7SDimitry Andric   if (Kind.isThreadData())
625cfca06d7SDimitry Andric     return ".tdata";
626cfca06d7SDimitry Andric   if (Kind.isThreadBSS())
627cfca06d7SDimitry Andric     return ".tbss";
628cfca06d7SDimitry Andric   if (Kind.isData())
6297fa27ce4SDimitry Andric     return IsLarge ? ".ldata" : ".data";
630cfca06d7SDimitry Andric   if (Kind.isReadOnlyWithRel())
6317fa27ce4SDimitry Andric     return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
632cfca06d7SDimitry Andric   llvm_unreachable("Unknown section kind");
633cfca06d7SDimitry Andric }
634cfca06d7SDimitry Andric 
635cfca06d7SDimitry Andric static SmallString<128>
getELFSectionNameForGlobal(const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,unsigned EntrySize,bool UniqueSectionName)636cfca06d7SDimitry Andric getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
637cfca06d7SDimitry Andric                            Mangler &Mang, const TargetMachine &TM,
638cfca06d7SDimitry Andric                            unsigned EntrySize, bool UniqueSectionName) {
639ac9a064cSDimitry Andric   SmallString<128> Name =
640ac9a064cSDimitry Andric       getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO));
641cfca06d7SDimitry Andric   if (Kind.isMergeableCString()) {
642cfca06d7SDimitry Andric     // We also need alignment here.
643cfca06d7SDimitry Andric     // FIXME: this is getting the alignment of the character, not the
644cfca06d7SDimitry Andric     // alignment of the global!
645ac9a064cSDimitry Andric     Align Alignment = GO->getDataLayout().getPreferredAlign(
646cfca06d7SDimitry Andric         cast<GlobalVariable>(GO));
647cfca06d7SDimitry Andric 
648ac9a064cSDimitry Andric     Name += ".str";
649cfca06d7SDimitry Andric     Name += utostr(EntrySize);
650ac9a064cSDimitry Andric     Name += ".";
651ac9a064cSDimitry Andric     Name += utostr(Alignment.value());
652ac9a064cSDimitry Andric   } else if (Kind.isMergeableConst()) {
653ac9a064cSDimitry Andric     Name += ".cst";
654ac9a064cSDimitry Andric     Name += utostr(EntrySize);
655cfca06d7SDimitry Andric   }
656cfca06d7SDimitry Andric 
657cfca06d7SDimitry Andric   bool HasPrefix = false;
658cfca06d7SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
659e3b55780SDimitry Andric     if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
660b60736ecSDimitry Andric       raw_svector_ostream(Name) << '.' << *Prefix;
661cfca06d7SDimitry Andric       HasPrefix = true;
662cfca06d7SDimitry Andric     }
663cfca06d7SDimitry Andric   }
664cfca06d7SDimitry Andric 
665cfca06d7SDimitry Andric   if (UniqueSectionName) {
666cfca06d7SDimitry Andric     Name.push_back('.');
667cfca06d7SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
668cfca06d7SDimitry Andric   } else if (HasPrefix)
669344a3780SDimitry Andric     // For distinguishing between .text.${text-section-prefix}. (with trailing
670344a3780SDimitry Andric     // dot) and .text.${function-name}
671cfca06d7SDimitry Andric     Name.push_back('.');
672cfca06d7SDimitry Andric   return Name;
673cfca06d7SDimitry Andric }
674cfca06d7SDimitry Andric 
675cfca06d7SDimitry Andric namespace {
676cfca06d7SDimitry Andric class LoweringDiagnosticInfo : public DiagnosticInfo {
677cfca06d7SDimitry Andric   const Twine &Msg;
678cfca06d7SDimitry Andric 
679cfca06d7SDimitry Andric public:
LoweringDiagnosticInfo(const Twine & DiagMsg,DiagnosticSeverity Severity=DS_Error)680cfca06d7SDimitry Andric   LoweringDiagnosticInfo(const Twine &DiagMsg,
681cfca06d7SDimitry Andric                          DiagnosticSeverity Severity = DS_Error)
682cfca06d7SDimitry Andric       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
print(DiagnosticPrinter & DP) const683cfca06d7SDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
684cfca06d7SDimitry Andric };
685cfca06d7SDimitry Andric }
686cfca06d7SDimitry Andric 
687344a3780SDimitry Andric /// Calculate an appropriate unique ID for a section, and update Flags,
688344a3780SDimitry Andric /// EntrySize and NextUniqueID where appropriate.
689344a3780SDimitry Andric static unsigned
calcUniqueIDUpdateFlagsAndSize(const GlobalObject * GO,StringRef SectionName,SectionKind Kind,const TargetMachine & TM,MCContext & Ctx,Mangler & Mang,unsigned & Flags,unsigned & EntrySize,unsigned & NextUniqueID,const bool Retain,const bool ForceUnique)690344a3780SDimitry Andric calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
691344a3780SDimitry Andric                                SectionKind Kind, const TargetMachine &TM,
692344a3780SDimitry Andric                                MCContext &Ctx, Mangler &Mang, unsigned &Flags,
693344a3780SDimitry Andric                                unsigned &EntrySize, unsigned &NextUniqueID,
694344a3780SDimitry Andric                                const bool Retain, const bool ForceUnique) {
695344a3780SDimitry Andric   // Increment uniqueID if we are forced to emit a unique section.
696344a3780SDimitry Andric   // This works perfectly fine with section attribute or pragma section as the
697344a3780SDimitry Andric   // sections with the same name are grouped together by the assembler.
698344a3780SDimitry Andric   if (ForceUnique)
699344a3780SDimitry Andric     return NextUniqueID++;
700344a3780SDimitry Andric 
701344a3780SDimitry Andric   // A section can have at most one associated section. Put each global with
702344a3780SDimitry Andric   // MD_associated in a unique section.
703344a3780SDimitry Andric   const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
704344a3780SDimitry Andric   if (Associated) {
705344a3780SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
706344a3780SDimitry Andric     return NextUniqueID++;
707344a3780SDimitry Andric   }
708344a3780SDimitry Andric 
709344a3780SDimitry Andric   if (Retain) {
710145449b1SDimitry Andric     if (TM.getTargetTriple().isOSSolaris())
711145449b1SDimitry Andric       Flags |= ELF::SHF_SUNW_NODISCARD;
712145449b1SDimitry Andric     else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
713145449b1SDimitry Andric              Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
714344a3780SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
715344a3780SDimitry Andric     return NextUniqueID++;
716344a3780SDimitry Andric   }
717344a3780SDimitry Andric 
718344a3780SDimitry Andric   // If two symbols with differing sizes end up in the same mergeable section
719344a3780SDimitry Andric   // that section can be assigned an incorrect entry size. To avoid this we
720344a3780SDimitry Andric   // usually put symbols of the same size into distinct mergeable sections with
721344a3780SDimitry Andric   // the same name. Doing so relies on the ",unique ," assembly feature. This
722344a3780SDimitry Andric   // feature is not avalible until bintuils version 2.35
723344a3780SDimitry Andric   // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
724344a3780SDimitry Andric   const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
725344a3780SDimitry Andric                               Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
726344a3780SDimitry Andric   if (!SupportsUnique) {
727344a3780SDimitry Andric     Flags &= ~ELF::SHF_MERGE;
728344a3780SDimitry Andric     EntrySize = 0;
729344a3780SDimitry Andric     return MCContext::GenericSectionID;
730344a3780SDimitry Andric   }
731344a3780SDimitry Andric 
732344a3780SDimitry Andric   const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
733344a3780SDimitry Andric   const bool SeenSectionNameBefore =
734344a3780SDimitry Andric       Ctx.isELFGenericMergeableSection(SectionName);
735344a3780SDimitry Andric   // If this is the first ocurrence of this section name, treat it as the
736344a3780SDimitry Andric   // generic section
737ac9a064cSDimitry Andric   if (!SymbolMergeable && !SeenSectionNameBefore) {
738ac9a064cSDimitry Andric     if (TM.getSeparateNamedSections())
739ac9a064cSDimitry Andric       return NextUniqueID++;
740ac9a064cSDimitry Andric     else
741344a3780SDimitry Andric       return MCContext::GenericSectionID;
742ac9a064cSDimitry Andric   }
743344a3780SDimitry Andric 
744344a3780SDimitry Andric   // Symbols must be placed into sections with compatible entry sizes. Generate
745344a3780SDimitry Andric   // unique sections for symbols that have not been assigned to compatible
746344a3780SDimitry Andric   // sections.
747344a3780SDimitry Andric   const auto PreviousID =
748344a3780SDimitry Andric       Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
749ac9a064cSDimitry Andric   if (PreviousID && (!TM.getSeparateNamedSections() ||
750ac9a064cSDimitry Andric                      *PreviousID == MCContext::GenericSectionID))
751344a3780SDimitry Andric     return *PreviousID;
752344a3780SDimitry Andric 
753344a3780SDimitry Andric   // If the user has specified the same section name as would be created
754344a3780SDimitry Andric   // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
755344a3780SDimitry Andric   // to unique the section as the entry size for this symbol will be
756344a3780SDimitry Andric   // compatible with implicitly created sections.
757344a3780SDimitry Andric   SmallString<128> ImplicitSectionNameStem =
758344a3780SDimitry Andric       getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
759344a3780SDimitry Andric   if (SymbolMergeable &&
760344a3780SDimitry Andric       Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
761312c0ed1SDimitry Andric       SectionName.starts_with(ImplicitSectionNameStem))
762344a3780SDimitry Andric     return MCContext::GenericSectionID;
763344a3780SDimitry Andric 
764344a3780SDimitry Andric   // We have seen this section name before, but with different flags or entity
765344a3780SDimitry Andric   // size. Create a new unique ID.
766344a3780SDimitry Andric   return NextUniqueID++;
767344a3780SDimitry Andric }
768344a3780SDimitry Andric 
769b1c73532SDimitry Andric static std::tuple<StringRef, bool, unsigned>
getGlobalObjectInfo(const GlobalObject * GO,const TargetMachine & TM)770b1c73532SDimitry Andric getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM) {
771b1c73532SDimitry Andric   StringRef Group = "";
772b1c73532SDimitry Andric   bool IsComdat = false;
773b1c73532SDimitry Andric   unsigned Flags = 0;
774b1c73532SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
775b1c73532SDimitry Andric     Flags |= ELF::SHF_GROUP;
776b1c73532SDimitry Andric     Group = C->getName();
777b1c73532SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
778b1c73532SDimitry Andric   }
779312c0ed1SDimitry Andric   if (TM.isLargeGlobalValue(GO))
780b1c73532SDimitry Andric     Flags |= ELF::SHF_X86_64_LARGE;
781b1c73532SDimitry Andric   return {Group, IsComdat, Flags};
782b1c73532SDimitry Andric }
783b1c73532SDimitry Andric 
selectExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM,MCContext & Ctx,Mangler & Mang,unsigned & NextUniqueID,bool Retain,bool ForceUnique)784344a3780SDimitry Andric static MCSection *selectExplicitSectionGlobal(
785344a3780SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
786344a3780SDimitry Andric     MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
787344a3780SDimitry Andric     bool Retain, bool ForceUnique) {
788b915e9e0SDimitry Andric   StringRef SectionName = GO->getSection();
7896fe5c7aaSRoman Divacky 
7907ab83427SDimitry Andric   // Check if '#pragma clang section' name is applicable.
7917ab83427SDimitry Andric   // Note that pragma directive overrides -ffunction-section, -fdata-section
7927ab83427SDimitry Andric   // and so section name is exactly as user specified and not uniqued.
7937ab83427SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
7947ab83427SDimitry Andric   if (GV && GV->hasImplicitSection()) {
7957ab83427SDimitry Andric     auto Attrs = GV->getAttributes();
7967ab83427SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
7977ab83427SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
7987ab83427SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
7997ab83427SDimitry Andric       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
8001d5ae102SDimitry Andric     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
8011d5ae102SDimitry Andric       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
8027ab83427SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
8037ab83427SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
8047ab83427SDimitry Andric     }
8057ab83427SDimitry Andric   }
8067ab83427SDimitry Andric 
8076fe5c7aaSRoman Divacky   // Infer section flags from the section name if we can.
8086fe5c7aaSRoman Divacky   Kind = getELFKindForNamedSection(SectionName, Kind);
8096fe5c7aaSRoman Divacky 
8105ca98fd9SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
811b1c73532SDimitry Andric   auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
812b1c73532SDimitry Andric   Flags |= ExtraFlags;
81371d5a254SDimitry Andric 
814cfca06d7SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
815344a3780SDimitry Andric   const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
816344a3780SDimitry Andric       GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
817344a3780SDimitry Andric       Retain, ForceUnique);
818cfca06d7SDimitry Andric 
819cfca06d7SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
820344a3780SDimitry Andric   MCSectionELF *Section = Ctx.getELFSection(
821344a3780SDimitry Andric       SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
822344a3780SDimitry Andric       Group, IsComdat, UniqueID, LinkedToSym);
82371d5a254SDimitry Andric   // Make sure that we did not get some other section with incompatible sh_link.
82471d5a254SDimitry Andric   // This should not be possible due to UniqueID code above.
825cfca06d7SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym &&
826eb11fae6SDimitry Andric          "Associated symbol mismatch between sections");
827cfca06d7SDimitry Andric 
828344a3780SDimitry Andric   if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
829344a3780SDimitry Andric         Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
830b60736ecSDimitry Andric     // If we are using GNU as before 2.35, then this symbol might have
831cfca06d7SDimitry Andric     // been placed in an incompatible mergeable section. Emit an error if this
832cfca06d7SDimitry Andric     // is the case to avoid creating broken output.
833cfca06d7SDimitry Andric     if ((Section->getFlags() & ELF::SHF_MERGE) &&
834cfca06d7SDimitry Andric         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
835cfca06d7SDimitry Andric       GO->getContext().diagnose(LoweringDiagnosticInfo(
836cfca06d7SDimitry Andric           "Symbol '" + GO->getName() + "' from module '" +
837cfca06d7SDimitry Andric           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
838cfca06d7SDimitry Andric           "' required a section with entry-size=" +
839cfca06d7SDimitry Andric           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
840cfca06d7SDimitry Andric           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
841cfca06d7SDimitry Andric           ": Explicit assignment by pragma or attribute of an incompatible "
842cfca06d7SDimitry Andric           "symbol to this section?"));
8436fe5c7aaSRoman Divacky   }
8446fe5c7aaSRoman Divacky 
845cfca06d7SDimitry Andric   return Section;
846d7f7719eSRoman Divacky }
847d7f7719eSRoman Divacky 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const848344a3780SDimitry Andric MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
849344a3780SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
850344a3780SDimitry Andric   return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
851344a3780SDimitry Andric                                      NextUniqueID, Used.count(GO),
852344a3780SDimitry Andric                                      /* ForceUnique = */false);
853344a3780SDimitry Andric }
854344a3780SDimitry Andric 
selectELFSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool EmitUniqueSection,unsigned Flags,unsigned * NextUniqueID,const MCSymbolELF * AssociatedSymbol)85571d5a254SDimitry Andric static MCSectionELF *selectELFSectionForGlobal(
85671d5a254SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
85771d5a254SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
85871d5a254SDimitry Andric     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
8595ca98fd9SDimitry Andric 
860b1c73532SDimitry Andric   auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
861b1c73532SDimitry Andric   Flags |= ExtraFlags;
862cf099d11SDimitry Andric 
863b7eb8e35SDimitry Andric   // Get the section entry size based on the kind.
864b7eb8e35SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
865b7eb8e35SDimitry Andric 
866cfca06d7SDimitry Andric   bool UniqueSectionName = false;
86701095a5dSDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
868b7eb8e35SDimitry Andric   if (EmitUniqueSection) {
869b7eb8e35SDimitry Andric     if (TM.getUniqueSectionNames()) {
870cfca06d7SDimitry Andric       UniqueSectionName = true;
871b7eb8e35SDimitry Andric     } else {
8725a5ac124SDimitry Andric       UniqueID = *NextUniqueID;
8735a5ac124SDimitry Andric       (*NextUniqueID)++;
8745a5ac124SDimitry Andric     }
875b7eb8e35SDimitry Andric   }
876cfca06d7SDimitry Andric   SmallString<128> Name = getELFSectionNameForGlobal(
877cfca06d7SDimitry Andric       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
878cfca06d7SDimitry Andric 
879b7eb8e35SDimitry Andric   // Use 0 as the unique ID for execute-only text.
880b915e9e0SDimitry Andric   if (Kind.isExecuteOnly())
881b915e9e0SDimitry Andric     UniqueID = 0;
8825a5ac124SDimitry Andric   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
883344a3780SDimitry Andric                            EntrySize, Group, IsComdat, UniqueID,
884344a3780SDimitry Andric                            AssociatedSymbol);
885344a3780SDimitry Andric }
886344a3780SDimitry Andric 
selectELFSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool Retain,bool EmitUniqueSection,unsigned Flags,unsigned * NextUniqueID)887344a3780SDimitry Andric static MCSection *selectELFSectionForGlobal(
888344a3780SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
889344a3780SDimitry Andric     const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
890344a3780SDimitry Andric     unsigned Flags, unsigned *NextUniqueID) {
891344a3780SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
892344a3780SDimitry Andric   if (LinkedToSym) {
893344a3780SDimitry Andric     EmitUniqueSection = true;
894344a3780SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
895344a3780SDimitry Andric   }
896145449b1SDimitry Andric   if (Retain) {
897145449b1SDimitry Andric     if (TM.getTargetTriple().isOSSolaris()) {
898145449b1SDimitry Andric       EmitUniqueSection = true;
899145449b1SDimitry Andric       Flags |= ELF::SHF_SUNW_NODISCARD;
900145449b1SDimitry Andric     } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
901145449b1SDimitry Andric                Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
902344a3780SDimitry Andric       EmitUniqueSection = true;
903344a3780SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
904344a3780SDimitry Andric     }
905145449b1SDimitry Andric   }
906344a3780SDimitry Andric 
907344a3780SDimitry Andric   MCSectionELF *Section = selectELFSectionForGlobal(
908344a3780SDimitry Andric       Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
909344a3780SDimitry Andric       NextUniqueID, LinkedToSym);
910344a3780SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym);
911344a3780SDimitry Andric   return Section;
9125a5ac124SDimitry Andric }
9135a5ac124SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const9145a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
915b915e9e0SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
9165a5ac124SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
9175a5ac124SDimitry Andric 
9185a5ac124SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
9195a5ac124SDimitry Andric   // global value to a uniqued section specifically for it.
9205a5ac124SDimitry Andric   bool EmitUniqueSection = false;
9215a5ac124SDimitry Andric   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
9225a5ac124SDimitry Andric     if (Kind.isText())
9235a5ac124SDimitry Andric       EmitUniqueSection = TM.getFunctionSections();
9246fe5c7aaSRoman Divacky     else
9255a5ac124SDimitry Andric       EmitUniqueSection = TM.getDataSections();
9265a5ac124SDimitry Andric   }
927b915e9e0SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
928344a3780SDimitry Andric   return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
929344a3780SDimitry Andric                                    Used.count(GO), EmitUniqueSection, Flags,
930344a3780SDimitry Andric                                    &NextUniqueID);
93171d5a254SDimitry Andric }
93271d5a254SDimitry Andric 
getUniqueSectionForFunction(const Function & F,const TargetMachine & TM) const933344a3780SDimitry Andric MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
934344a3780SDimitry Andric     const Function &F, const TargetMachine &TM) const {
935344a3780SDimitry Andric   SectionKind Kind = SectionKind::getText();
936344a3780SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
937344a3780SDimitry Andric   // If the function's section names is pre-determined via pragma or a
938344a3780SDimitry Andric   // section attribute, call selectExplicitSectionGlobal.
939ac9a064cSDimitry Andric   if (F.hasSection())
940344a3780SDimitry Andric     return selectExplicitSectionGlobal(
941344a3780SDimitry Andric         &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
942344a3780SDimitry Andric         Used.count(&F), /* ForceUnique = */true);
943344a3780SDimitry Andric   else
944344a3780SDimitry Andric     return selectELFSectionForGlobal(
945344a3780SDimitry Andric         getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
946344a3780SDimitry Andric         /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
9476fe5c7aaSRoman Divacky }
9486fe5c7aaSRoman Divacky 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const9495a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
950b915e9e0SDimitry Andric     const Function &F, const TargetMachine &TM) const {
9515a5ac124SDimitry Andric   // If the function can be removed, produce a unique section so that
9525a5ac124SDimitry Andric   // the table doesn't prevent the removal.
9535a5ac124SDimitry Andric   const Comdat *C = F.getComdat();
9545a5ac124SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
9555a5ac124SDimitry Andric   if (!EmitUniqueSection)
9565a5ac124SDimitry Andric     return ReadOnlySection;
9575a5ac124SDimitry Andric 
9585a5ac124SDimitry Andric   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
95971d5a254SDimitry Andric                                    getMangler(), TM, EmitUniqueSection,
96071d5a254SDimitry Andric                                    ELF::SHF_ALLOC, &NextUniqueID,
96171d5a254SDimitry Andric                                    /* AssociatedSymbol */ nullptr);
9626fe5c7aaSRoman Divacky }
9636fe5c7aaSRoman Divacky 
getSectionForLSDA(const Function & F,const MCSymbol & FnSym,const TargetMachine & TM) const964344a3780SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
965344a3780SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
966b60736ecSDimitry Andric   // If neither COMDAT nor function sections, use the monolithic LSDA section.
967b60736ecSDimitry Andric   // Re-use this path if LSDASection is null as in the Arm EHABI.
968b60736ecSDimitry Andric   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
969b60736ecSDimitry Andric     return LSDASection;
970b60736ecSDimitry Andric 
971b60736ecSDimitry Andric   const auto *LSDA = cast<MCSectionELF>(LSDASection);
972b60736ecSDimitry Andric   unsigned Flags = LSDA->getFlags();
973344a3780SDimitry Andric   const MCSymbolELF *LinkedToSym = nullptr;
974b60736ecSDimitry Andric   StringRef Group;
975344a3780SDimitry Andric   bool IsComdat = false;
976344a3780SDimitry Andric   if (const Comdat *C = getELFComdat(&F)) {
977b60736ecSDimitry Andric     Flags |= ELF::SHF_GROUP;
978344a3780SDimitry Andric     Group = C->getName();
979344a3780SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
980344a3780SDimitry Andric   }
981344a3780SDimitry Andric   // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
982344a3780SDimitry Andric   // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
983344a3780SDimitry Andric   if (TM.getFunctionSections() &&
984344a3780SDimitry Andric       (getContext().getAsmInfo()->useIntegratedAssembler() &&
985344a3780SDimitry Andric        getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
986344a3780SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
987344a3780SDimitry Andric     LinkedToSym = cast<MCSymbolELF>(&FnSym);
988b60736ecSDimitry Andric   }
989b60736ecSDimitry Andric 
990b60736ecSDimitry Andric   // Append the function name as the suffix like GCC, assuming
991b60736ecSDimitry Andric   // -funique-section-names applies to .gcc_except_table sections.
992344a3780SDimitry Andric   return getContext().getELFSection(
993344a3780SDimitry Andric       (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
994344a3780SDimitry Andric                                   : LSDA->getName()),
995344a3780SDimitry Andric       LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
996344a3780SDimitry Andric       LinkedToSym);
997b60736ecSDimitry Andric }
998b60736ecSDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const9995a5ac124SDimitry Andric bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
10005a5ac124SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
10015a5ac124SDimitry Andric   // We can always create relative relocations, so use another section
10025a5ac124SDimitry Andric   // that can be marked non-executable.
10035a5ac124SDimitry Andric   return false;
10046fe5c7aaSRoman Divacky }
10056fe5c7aaSRoman Divacky 
10065a5ac124SDimitry Andric /// Given a mergeable constant with the specified size and relocation
10075a5ac124SDimitry Andric /// information, return a section that it should be placed in.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const1008dd58ef01SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
100901095a5dSDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
1010cfca06d7SDimitry Andric     Align &Alignment) const {
10116fe5c7aaSRoman Divacky   if (Kind.isMergeableConst4() && MergeableConst4Section)
10126fe5c7aaSRoman Divacky     return MergeableConst4Section;
10136fe5c7aaSRoman Divacky   if (Kind.isMergeableConst8() && MergeableConst8Section)
10146fe5c7aaSRoman Divacky     return MergeableConst8Section;
10156fe5c7aaSRoman Divacky   if (Kind.isMergeableConst16() && MergeableConst16Section)
10166fe5c7aaSRoman Divacky     return MergeableConst16Section;
101701095a5dSDimitry Andric   if (Kind.isMergeableConst32() && MergeableConst32Section)
101801095a5dSDimitry Andric     return MergeableConst32Section;
10196fe5c7aaSRoman Divacky   if (Kind.isReadOnly())
10206fe5c7aaSRoman Divacky     return ReadOnlySection;
10216fe5c7aaSRoman Divacky 
10226fe5c7aaSRoman Divacky   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
10236fe5c7aaSRoman Divacky   return DataRelROSection;
10246fe5c7aaSRoman Divacky }
10256fe5c7aaSRoman Divacky 
1026cfca06d7SDimitry Andric /// Returns a unique section for the given machine basic block.
getSectionForMachineBasicBlock(const Function & F,const MachineBasicBlock & MBB,const TargetMachine & TM) const1027cfca06d7SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
1028cfca06d7SDimitry Andric     const Function &F, const MachineBasicBlock &MBB,
1029cfca06d7SDimitry Andric     const TargetMachine &TM) const {
1030cfca06d7SDimitry Andric   assert(MBB.isBeginSection() && "Basic block does not start a section!");
1031cfca06d7SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
1032cfca06d7SDimitry Andric 
1033b60736ecSDimitry Andric   // For cold sections use the .text.split. prefix along with the parent
1034cfca06d7SDimitry Andric   // function name. All cold blocks for the same function go to the same
1035cfca06d7SDimitry Andric   // section. Similarly all exception blocks are grouped by symbol name
1036cfca06d7SDimitry Andric   // under the .text.eh prefix. For regular sections, we either use a unique
1037cfca06d7SDimitry Andric   // name, or a unique ID for the section.
1038cfca06d7SDimitry Andric   SmallString<128> Name;
1039b1c73532SDimitry Andric   StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1040ac9a064cSDimitry Andric   if (FunctionSectionName == ".text" ||
1041312c0ed1SDimitry Andric       FunctionSectionName.starts_with(".text.")) {
1042b1c73532SDimitry Andric     // Function is in a regular .text section.
1043b1c73532SDimitry Andric     StringRef FunctionName = MBB.getParent()->getName();
1044cfca06d7SDimitry Andric     if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1045b60736ecSDimitry Andric       Name += BBSectionsColdTextPrefix;
1046b1c73532SDimitry Andric       Name += FunctionName;
1047cfca06d7SDimitry Andric     } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
1048cfca06d7SDimitry Andric       Name += ".text.eh.";
1049b1c73532SDimitry Andric       Name += FunctionName;
1050cfca06d7SDimitry Andric     } else {
1051b1c73532SDimitry Andric       Name += FunctionSectionName;
1052cfca06d7SDimitry Andric       if (TM.getUniqueBasicBlockSectionNames()) {
1053312c0ed1SDimitry Andric         if (!Name.ends_with("."))
1054cfca06d7SDimitry Andric           Name += ".";
1055cfca06d7SDimitry Andric         Name += MBB.getSymbol()->getName();
1056cfca06d7SDimitry Andric       } else {
1057cfca06d7SDimitry Andric         UniqueID = NextUniqueID++;
1058cfca06d7SDimitry Andric       }
1059cfca06d7SDimitry Andric     }
1060b1c73532SDimitry Andric   } else {
1061b1c73532SDimitry Andric     // If the original function has a custom non-dot-text section, then emit
1062b1c73532SDimitry Andric     // all basic block sections into that section too, each with a unique id.
1063b1c73532SDimitry Andric     Name = FunctionSectionName;
1064b1c73532SDimitry Andric     UniqueID = NextUniqueID++;
1065b1c73532SDimitry Andric   }
1066cfca06d7SDimitry Andric 
1067cfca06d7SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1068b60736ecSDimitry Andric   std::string GroupName;
1069cfca06d7SDimitry Andric   if (F.hasComdat()) {
1070cfca06d7SDimitry Andric     Flags |= ELF::SHF_GROUP;
1071cfca06d7SDimitry Andric     GroupName = F.getComdat()->getName().str();
1072cfca06d7SDimitry Andric   }
1073cfca06d7SDimitry Andric   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1074344a3780SDimitry Andric                                     0 /* Entry Size */, GroupName,
1075344a3780SDimitry Andric                                     F.hasComdat(), UniqueID, nullptr);
1076cfca06d7SDimitry Andric }
1077cfca06d7SDimitry Andric 
getStaticStructorSection(MCContext & Ctx,bool UseInitArray,bool IsCtor,unsigned Priority,const MCSymbol * KeySym)10785a5ac124SDimitry Andric static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
10795a5ac124SDimitry Andric                                               bool IsCtor, unsigned Priority,
108067c32a98SDimitry Andric                                               const MCSymbol *KeySym) {
108167c32a98SDimitry Andric   std::string Name;
108267c32a98SDimitry Andric   unsigned Type;
108367c32a98SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1084344a3780SDimitry Andric   StringRef Comdat = KeySym ? KeySym->getName() : "";
108567c32a98SDimitry Andric 
108667c32a98SDimitry Andric   if (KeySym)
108767c32a98SDimitry Andric     Flags |= ELF::SHF_GROUP;
108863faed5bSDimitry Andric 
108958b69754SDimitry Andric   if (UseInitArray) {
109067c32a98SDimitry Andric     if (IsCtor) {
109167c32a98SDimitry Andric       Type = ELF::SHT_INIT_ARRAY;
109267c32a98SDimitry Andric       Name = ".init_array";
109358b69754SDimitry Andric     } else {
109467c32a98SDimitry Andric       Type = ELF::SHT_FINI_ARRAY;
109567c32a98SDimitry Andric       Name = ".fini_array";
109663faed5bSDimitry Andric     }
109767c32a98SDimitry Andric     if (Priority != 65535) {
109867c32a98SDimitry Andric       Name += '.';
109967c32a98SDimitry Andric       Name += utostr(Priority);
110067c32a98SDimitry Andric     }
110167c32a98SDimitry Andric   } else {
110267c32a98SDimitry Andric     // The default scheme is .ctor / .dtor, so we have to invert the priority
110367c32a98SDimitry Andric     // numbering.
110467c32a98SDimitry Andric     if (IsCtor)
110567c32a98SDimitry Andric       Name = ".ctors";
110667c32a98SDimitry Andric     else
110767c32a98SDimitry Andric       Name = ".dtors";
1108044eb2f6SDimitry Andric     if (Priority != 65535)
1109044eb2f6SDimitry Andric       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
111067c32a98SDimitry Andric     Type = ELF::SHT_PROGBITS;
111167c32a98SDimitry Andric   }
111267c32a98SDimitry Andric 
1113344a3780SDimitry Andric   return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
111467c32a98SDimitry Andric }
111567c32a98SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const11165a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
111767c32a98SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
111867c32a98SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
111967c32a98SDimitry Andric                                   KeySym);
112058b69754SDimitry Andric }
112163faed5bSDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const11225a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
11235ca98fd9SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
112467c32a98SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
112567c32a98SDimitry Andric                                   KeySym);
112658b69754SDimitry Andric }
112758b69754SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const112801095a5dSDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
1129b915e9e0SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
113001095a5dSDimitry Andric     const TargetMachine &TM) const {
113101095a5dSDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
113201095a5dSDimitry Andric   // functions.
113301095a5dSDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
113401095a5dSDimitry Andric     return nullptr;
113501095a5dSDimitry Andric 
1136f65dcba8SDimitry Andric   // Basic correctness checks.
113701095a5dSDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
113801095a5dSDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
113901095a5dSDimitry Andric       RHS->isThreadLocal())
114001095a5dSDimitry Andric     return nullptr;
114101095a5dSDimitry Andric 
114201095a5dSDimitry Andric   return MCBinaryExpr::createSub(
1143b915e9e0SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
114401095a5dSDimitry Andric                               getContext()),
1145b915e9e0SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
114601095a5dSDimitry Andric }
114701095a5dSDimitry Andric 
lowerDSOLocalEquivalent(const DSOLocalEquivalent * Equiv,const TargetMachine & TM) const1148b60736ecSDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1149b60736ecSDimitry Andric     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1150b60736ecSDimitry Andric   assert(supportDSOLocalEquivalentLowering());
1151b60736ecSDimitry Andric 
1152b60736ecSDimitry Andric   const auto *GV = Equiv->getGlobalValue();
1153b60736ecSDimitry Andric 
1154b60736ecSDimitry Andric   // A PLT entry is not needed for dso_local globals.
1155b60736ecSDimitry Andric   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1156b60736ecSDimitry Andric     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1157b60736ecSDimitry Andric 
1158b60736ecSDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1159b60736ecSDimitry Andric                                  getContext());
1160b60736ecSDimitry Andric }
1161b60736ecSDimitry Andric 
getSectionForCommandLines() const1162d8e91e46SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1163d8e91e46SDimitry Andric   // Use ".GCC.command.line" since this feature is to support clang's
1164d8e91e46SDimitry Andric   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1165d8e91e46SDimitry Andric   // same name.
1166d8e91e46SDimitry Andric   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1167344a3780SDimitry Andric                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
1168d8e91e46SDimitry Andric }
1169d8e91e46SDimitry Andric 
117058b69754SDimitry Andric void
InitializeELF(bool UseInitArray_)117158b69754SDimitry Andric TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
117258b69754SDimitry Andric   UseInitArray = UseInitArray_;
1173b915e9e0SDimitry Andric   MCContext &Ctx = getContext();
1174b915e9e0SDimitry Andric   if (!UseInitArray) {
1175b915e9e0SDimitry Andric     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1176b915e9e0SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
117758b69754SDimitry Andric 
1178b915e9e0SDimitry Andric     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1179b915e9e0SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1180b915e9e0SDimitry Andric     return;
1181b915e9e0SDimitry Andric   }
1182b915e9e0SDimitry Andric 
1183b915e9e0SDimitry Andric   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1184b915e9e0SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1185b915e9e0SDimitry Andric   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1186b915e9e0SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
118758b69754SDimitry Andric }
118863faed5bSDimitry Andric 
11896fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
11906fe5c7aaSRoman Divacky //                                 MachO
11916fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
11926fe5c7aaSRoman Divacky 
TargetLoweringObjectFileMachO()11936f8fc217SDimitry Andric TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() {
11945a5ac124SDimitry Andric   SupportIndirectSymViaGOTPCRel = true;
11955a5ac124SDimitry Andric }
11965a5ac124SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TM)1197b915e9e0SDimitry Andric void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1198b915e9e0SDimitry Andric                                                const TargetMachine &TM) {
1199b915e9e0SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1200b915e9e0SDimitry Andric   if (TM.getRelocationModel() == Reloc::Static) {
1201b915e9e0SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1202b915e9e0SDimitry Andric                                             SectionKind::getData());
1203b915e9e0SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1204b915e9e0SDimitry Andric                                             SectionKind::getData());
1205b915e9e0SDimitry Andric   } else {
1206b915e9e0SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1207b915e9e0SDimitry Andric                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1208b915e9e0SDimitry Andric                                             SectionKind::getData());
1209b915e9e0SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1210b915e9e0SDimitry Andric                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1211b915e9e0SDimitry Andric                                             SectionKind::getData());
1212b915e9e0SDimitry Andric   }
1213d8e91e46SDimitry Andric 
1214d8e91e46SDimitry Andric   PersonalityEncoding =
1215d8e91e46SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1216d8e91e46SDimitry Andric   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1217d8e91e46SDimitry Andric   TTypeEncoding =
1218d8e91e46SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1219b915e9e0SDimitry Andric }
1220b915e9e0SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const1221145449b1SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getStaticDtorSection(
1222145449b1SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1223145449b1SDimitry Andric   return StaticDtorSection;
12247fa27ce4SDimitry Andric   // In userspace, we lower global destructors via atexit(), but kernel/kext
12257fa27ce4SDimitry Andric   // environments do not provide this function so we still need to support the
12267fa27ce4SDimitry Andric   // legacy way here.
12277fa27ce4SDimitry Andric   // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
12287fa27ce4SDimitry Andric   // context.
1229145449b1SDimitry Andric }
1230145449b1SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const1231eb11fae6SDimitry Andric void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1232eb11fae6SDimitry Andric                                                        Module &M) const {
12334a16efa3SDimitry Andric   // Emit the linker options if present.
12347c7aba6eSDimitry Andric   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1235706b4fc4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
12364a16efa3SDimitry Andric       SmallVector<std::string, 4> StrOptions;
123701095a5dSDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands())
1238cfca06d7SDimitry Andric         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1239cfca06d7SDimitry Andric       Streamer.emitLinkerOptions(StrOptions);
12404a16efa3SDimitry Andric     }
124163faed5bSDimitry Andric   }
124263faed5bSDimitry Andric 
12437ab83427SDimitry Andric   unsigned VersionVal = 0;
12447ab83427SDimitry Andric   unsigned ImageInfoFlags = 0;
12457ab83427SDimitry Andric   StringRef SectionVal;
12467c7aba6eSDimitry Andric 
12477c7aba6eSDimitry Andric   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
12486f8fc217SDimitry Andric   emitCGProfileMetadata(Streamer, M);
12497ab83427SDimitry Andric 
125063faed5bSDimitry Andric   // The section is mandatory. If we don't have it, then we don't have GC info.
12517ab83427SDimitry Andric   if (SectionVal.empty())
12527ab83427SDimitry Andric     return;
125363faed5bSDimitry Andric 
125463faed5bSDimitry Andric   StringRef Segment, Section;
125563faed5bSDimitry Andric   unsigned TAA = 0, StubSize = 0;
125663faed5bSDimitry Andric   bool TAAParsed;
1257344a3780SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1258344a3780SDimitry Andric           SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
125963faed5bSDimitry Andric     // If invalid, report the error with report_fatal_error.
1260344a3780SDimitry Andric     report_fatal_error("Invalid section specifier '" + Section +
1261344a3780SDimitry Andric                        "': " + toString(std::move(E)) + ".");
1262344a3780SDimitry Andric   }
126363faed5bSDimitry Andric 
126463faed5bSDimitry Andric   // Get the section.
12655a5ac124SDimitry Andric   MCSectionMachO *S = getContext().getMachOSection(
1266dd58ef01SDimitry Andric       Segment, Section, TAA, StubSize, SectionKind::getData());
1267145449b1SDimitry Andric   Streamer.switchSection(S);
1268cfca06d7SDimitry Andric   Streamer.emitLabel(getContext().
12695a5ac124SDimitry Andric                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1270cfca06d7SDimitry Andric   Streamer.emitInt32(VersionVal);
1271cfca06d7SDimitry Andric   Streamer.emitInt32(ImageInfoFlags);
1272145449b1SDimitry Andric   Streamer.addBlankLine();
127363faed5bSDimitry Andric }
127463faed5bSDimitry Andric 
checkMachOComdat(const GlobalValue * GV)12755ca98fd9SDimitry Andric static void checkMachOComdat(const GlobalValue *GV) {
12765ca98fd9SDimitry Andric   const Comdat *C = GV->getComdat();
12775ca98fd9SDimitry Andric   if (!C)
12785ca98fd9SDimitry Andric     return;
12795ca98fd9SDimitry Andric 
12805ca98fd9SDimitry Andric   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
12815ca98fd9SDimitry Andric                      "' cannot be lowered.");
12825ca98fd9SDimitry Andric }
12835ca98fd9SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const12845a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1285b915e9e0SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1286344a3780SDimitry Andric 
1287344a3780SDimitry Andric   StringRef SectionName = GO->getSection();
1288344a3780SDimitry Andric 
12897fa27ce4SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
12907fa27ce4SDimitry Andric   if (GV && GV->hasImplicitSection()) {
12917fa27ce4SDimitry Andric     auto Attrs = GV->getAttributes();
12927fa27ce4SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
12937fa27ce4SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
12947fa27ce4SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
12957fa27ce4SDimitry Andric       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
12967fa27ce4SDimitry Andric     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
12977fa27ce4SDimitry Andric       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
12987fa27ce4SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
12997fa27ce4SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
13007fa27ce4SDimitry Andric     }
13017fa27ce4SDimitry Andric   }
13027fa27ce4SDimitry Andric 
13036fe5c7aaSRoman Divacky   // Parse the section specifier and create it if valid.
13046fe5c7aaSRoman Divacky   StringRef Segment, Section;
13056b943ff3SDimitry Andric   unsigned TAA = 0, StubSize = 0;
13066b943ff3SDimitry Andric   bool TAAParsed;
13075ca98fd9SDimitry Andric 
1308b915e9e0SDimitry Andric   checkMachOComdat(GO);
13095ca98fd9SDimitry Andric 
1310344a3780SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1311344a3780SDimitry Andric           SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1312d7f7719eSRoman Divacky     // If invalid, report the error with report_fatal_error.
1313b915e9e0SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
131463faed5bSDimitry Andric                        "' has an invalid section specifier '" +
1315344a3780SDimitry Andric                        GO->getSection() + "': " + toString(std::move(E)) + ".");
13166fe5c7aaSRoman Divacky   }
13176fe5c7aaSRoman Divacky 
13186fe5c7aaSRoman Divacky   // Get the section.
13195a5ac124SDimitry Andric   MCSectionMachO *S =
1320d7f7719eSRoman Divacky       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
13216fe5c7aaSRoman Divacky 
1322d0e4e96dSDimitry Andric   // If TAA wasn't set by ParseSectionSpecifier() above,
1323d0e4e96dSDimitry Andric   // use the value returned by getMachOSection() as a default.
13246b943ff3SDimitry Andric   if (!TAAParsed)
1325d0e4e96dSDimitry Andric     TAA = S->getTypeAndAttributes();
1326d0e4e96dSDimitry Andric 
13276fe5c7aaSRoman Divacky   // Okay, now that we got the section, verify that the TAA & StubSize agree.
13286fe5c7aaSRoman Divacky   // If the user declared multiple globals with different section flags, we need
13296fe5c7aaSRoman Divacky   // to reject it here.
13306fe5c7aaSRoman Divacky   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1331d7f7719eSRoman Divacky     // If invalid, report the error with report_fatal_error.
1332b915e9e0SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
13336fe5c7aaSRoman Divacky                        "' section type or attributes does not match previous"
13346fe5c7aaSRoman Divacky                        " section specifier");
13356fe5c7aaSRoman Divacky   }
13366fe5c7aaSRoman Divacky 
13376fe5c7aaSRoman Divacky   return S;
13386fe5c7aaSRoman Divacky }
13396fe5c7aaSRoman Divacky 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const13405a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1341b915e9e0SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1342b915e9e0SDimitry Andric   checkMachOComdat(GO);
1343f8af5cf6SDimitry Andric 
1344f8af5cf6SDimitry Andric   // Handle thread local data.
1345f8af5cf6SDimitry Andric   if (Kind.isThreadBSS()) return TLSBSSSection;
1346f8af5cf6SDimitry Andric   if (Kind.isThreadData()) return TLSDataSection;
1347f8af5cf6SDimitry Andric 
13486fe5c7aaSRoman Divacky   if (Kind.isText())
1349b915e9e0SDimitry Andric     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
13506fe5c7aaSRoman Divacky 
13516fe5c7aaSRoman Divacky   // If this is weak/linkonce, put this in a coalescable section, either in text
13526fe5c7aaSRoman Divacky   // or data depending on if it is writable.
1353b915e9e0SDimitry Andric   if (GO->isWeakForLinker()) {
13546fe5c7aaSRoman Divacky     if (Kind.isReadOnly())
13556fe5c7aaSRoman Divacky       return ConstTextCoalSection;
1356eb11fae6SDimitry Andric     if (Kind.isReadOnlyWithRel())
1357eb11fae6SDimitry Andric       return ConstDataCoalSection;
13586fe5c7aaSRoman Divacky     return DataCoalSection;
13596fe5c7aaSRoman Divacky   }
13606fe5c7aaSRoman Divacky 
13616fe5c7aaSRoman Divacky   // FIXME: Alignment check should be handled by section classifier.
1362ea5b2dd1SRoman Divacky   if (Kind.isMergeable1ByteCString() &&
1363ac9a064cSDimitry Andric       GO->getDataLayout().getPreferredAlign(
1364cfca06d7SDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
13656fe5c7aaSRoman Divacky     return CStringSection;
1366ea5b2dd1SRoman Divacky 
1367ea5b2dd1SRoman Divacky   // Do not put 16-bit arrays in the UString section if they have an
1368ea5b2dd1SRoman Divacky   // externally visible label, this runs into issues with certain linker
1369ea5b2dd1SRoman Divacky   // versions.
1370b915e9e0SDimitry Andric   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1371ac9a064cSDimitry Andric       GO->getDataLayout().getPreferredAlign(
1372cfca06d7SDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
13736fe5c7aaSRoman Divacky     return UStringSection;
13746fe5c7aaSRoman Divacky 
137567c32a98SDimitry Andric   // With MachO only variables whose corresponding symbol starts with 'l' or
137667c32a98SDimitry Andric   // 'L' can be merged, so we only try merging GVs with private linkage.
1377b915e9e0SDimitry Andric   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
13786fe5c7aaSRoman Divacky     if (Kind.isMergeableConst4())
13796fe5c7aaSRoman Divacky       return FourByteConstantSection;
13806fe5c7aaSRoman Divacky     if (Kind.isMergeableConst8())
13816fe5c7aaSRoman Divacky       return EightByteConstantSection;
13825ca98fd9SDimitry Andric     if (Kind.isMergeableConst16())
13836fe5c7aaSRoman Divacky       return SixteenByteConstantSection;
13846fe5c7aaSRoman Divacky   }
13856fe5c7aaSRoman Divacky 
13866fe5c7aaSRoman Divacky   // Otherwise, if it is readonly, but not something we can specially optimize,
13876fe5c7aaSRoman Divacky   // just drop it in .const.
13886fe5c7aaSRoman Divacky   if (Kind.isReadOnly())
13896fe5c7aaSRoman Divacky     return ReadOnlySection;
13906fe5c7aaSRoman Divacky 
13916fe5c7aaSRoman Divacky   // If this is marked const, put it into a const section.  But if the dynamic
13926fe5c7aaSRoman Divacky   // linker needs to write to it, put it in the data segment.
13936fe5c7aaSRoman Divacky   if (Kind.isReadOnlyWithRel())
13946fe5c7aaSRoman Divacky     return ConstDataSection;
13956fe5c7aaSRoman Divacky 
13966fe5c7aaSRoman Divacky   // Put zero initialized globals with strong external linkage in the
13976fe5c7aaSRoman Divacky   // DATA, __common section with the .zerofill directive.
13986fe5c7aaSRoman Divacky   if (Kind.isBSSExtern())
13996fe5c7aaSRoman Divacky     return DataCommonSection;
14006fe5c7aaSRoman Divacky 
14016fe5c7aaSRoman Divacky   // Put zero initialized globals with local linkage in __DATA,__bss directive
14026fe5c7aaSRoman Divacky   // with the .zerofill directive (aka .lcomm).
14036fe5c7aaSRoman Divacky   if (Kind.isBSSLocal())
14046fe5c7aaSRoman Divacky     return DataBSSSection;
14056fe5c7aaSRoman Divacky 
14066fe5c7aaSRoman Divacky   // Otherwise, just drop the variable in the normal data section.
14076fe5c7aaSRoman Divacky   return DataSection;
14086fe5c7aaSRoman Divacky }
14096fe5c7aaSRoman Divacky 
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const1410dd58ef01SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
141101095a5dSDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
1412cfca06d7SDimitry Andric     Align &Alignment) const {
14136fe5c7aaSRoman Divacky   // If this constant requires a relocation, we have to put it in the data
14146fe5c7aaSRoman Divacky   // segment, not in the text segment.
1415dd58ef01SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel())
14166fe5c7aaSRoman Divacky     return ConstDataSection;
14176fe5c7aaSRoman Divacky 
14186fe5c7aaSRoman Divacky   if (Kind.isMergeableConst4())
14196fe5c7aaSRoman Divacky     return FourByteConstantSection;
14206fe5c7aaSRoman Divacky   if (Kind.isMergeableConst8())
14216fe5c7aaSRoman Divacky     return EightByteConstantSection;
14225ca98fd9SDimitry Andric   if (Kind.isMergeableConst16())
14236fe5c7aaSRoman Divacky     return SixteenByteConstantSection;
14246fe5c7aaSRoman Divacky   return ReadOnlySection;  // .const
14256fe5c7aaSRoman Divacky }
14266fe5c7aaSRoman Divacky 
getSectionForCommandLines() const14277fa27ce4SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForCommandLines() const {
14287fa27ce4SDimitry Andric   return getContext().getMachOSection("__TEXT", "__command_line", 0,
14297fa27ce4SDimitry Andric                                       SectionKind::getReadOnly());
14307fa27ce4SDimitry Andric }
14317fa27ce4SDimitry Andric 
getTTypeGlobalReference(const GlobalValue * GV,unsigned Encoding,const TargetMachine & TM,MachineModuleInfo * MMI,MCStreamer & Streamer) const14325ca98fd9SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1433b915e9e0SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1434b915e9e0SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
14356fe5c7aaSRoman Divacky   // The mach-o version of this method defaults to returning a stub reference.
14366fe5c7aaSRoman Divacky 
143767a71b31SRoman Divacky   if (Encoding & DW_EH_PE_indirect) {
143867a71b31SRoman Divacky     MachineModuleInfoMachO &MachOMMI =
143967a71b31SRoman Divacky       MMI->getObjFileInfo<MachineModuleInfoMachO>();
144067a71b31SRoman Divacky 
1441b915e9e0SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
144267a71b31SRoman Divacky 
144367a71b31SRoman Divacky     // Add information about the stub reference to MachOMMI so that the stub
144467a71b31SRoman Divacky     // gets emitted by the asmprinter.
144501095a5dSDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
14465ca98fd9SDimitry Andric     if (!StubSym.getPointer()) {
1447b915e9e0SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
1448c6910277SRoman Divacky       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
144967a71b31SRoman Divacky     }
14506fe5c7aaSRoman Divacky 
14516fe5c7aaSRoman Divacky     return TargetLoweringObjectFile::
145285d8b2bbSDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
145371d5a254SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
14546fe5c7aaSRoman Divacky   }
14556fe5c7aaSRoman Divacky 
1456b915e9e0SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1457b915e9e0SDimitry Andric                                                            MMI, Streamer);
14586fe5c7aaSRoman Divacky }
14596fe5c7aaSRoman Divacky 
getCFIPersonalitySymbol(const GlobalValue * GV,const TargetMachine & TM,MachineModuleInfo * MMI) const14605ca98fd9SDimitry Andric MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1461b915e9e0SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
14626b943ff3SDimitry Andric     MachineModuleInfo *MMI) const {
14636b943ff3SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
14646b943ff3SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
14656b943ff3SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
14666b943ff3SDimitry Andric 
1467b915e9e0SDimitry Andric   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
14686b943ff3SDimitry Andric 
14696b943ff3SDimitry Andric   // Add information about the stub reference to MachOMMI so that the stub
14706b943ff3SDimitry Andric   // gets emitted by the asmprinter.
147163faed5bSDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
14725ca98fd9SDimitry Andric   if (!StubSym.getPointer()) {
1473b915e9e0SDimitry Andric     MCSymbol *Sym = TM.getSymbol(GV);
14746b943ff3SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
14756b943ff3SDimitry Andric   }
14766b943ff3SDimitry Andric 
14776b943ff3SDimitry Andric   return SSym;
14786b943ff3SDimitry Andric }
14796b943ff3SDimitry Andric 
getIndirectSymViaGOTPCRel(const GlobalValue * GV,const MCSymbol * Sym,const MCValue & MV,int64_t Offset,MachineModuleInfo * MMI,MCStreamer & Streamer) const14805a5ac124SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
14811d5ae102SDimitry Andric     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
14821d5ae102SDimitry Andric     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1483dd58ef01SDimitry Andric   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
14845a5ac124SDimitry Andric   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
14855a5ac124SDimitry Andric   // through a non_lazy_ptr stub instead. One advantage is that it allows the
14865a5ac124SDimitry Andric   // computation of deltas to final external symbols. Example:
14875a5ac124SDimitry Andric   //
14885a5ac124SDimitry Andric   //    _extgotequiv:
14895a5ac124SDimitry Andric   //       .long   _extfoo
14905a5ac124SDimitry Andric   //
14915a5ac124SDimitry Andric   //    _delta:
14925a5ac124SDimitry Andric   //       .long   _extgotequiv-_delta
14935a5ac124SDimitry Andric   //
14945a5ac124SDimitry Andric   // is transformed to:
14955a5ac124SDimitry Andric   //
14965a5ac124SDimitry Andric   //    _delta:
14975a5ac124SDimitry Andric   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
14985a5ac124SDimitry Andric   //
14995a5ac124SDimitry Andric   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
15005a5ac124SDimitry Andric   //    L_extfoo$non_lazy_ptr:
15015a5ac124SDimitry Andric   //       .indirect_symbol        _extfoo
15025a5ac124SDimitry Andric   //       .long   0
15035a5ac124SDimitry Andric   //
1504d8e91e46SDimitry Andric   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1505d8e91e46SDimitry Andric   // may point to both local (same translation unit) and global (other
1506d8e91e46SDimitry Andric   // translation units) symbols. Example:
1507d8e91e46SDimitry Andric   //
1508d8e91e46SDimitry Andric   // .section __DATA,__pointers,non_lazy_symbol_pointers
1509d8e91e46SDimitry Andric   // L1:
1510d8e91e46SDimitry Andric   //    .indirect_symbol _myGlobal
1511d8e91e46SDimitry Andric   //    .long 0
1512d8e91e46SDimitry Andric   // L2:
1513d8e91e46SDimitry Andric   //    .indirect_symbol _myLocal
1514d8e91e46SDimitry Andric   //    .long _myLocal
1515d8e91e46SDimitry Andric   //
1516d8e91e46SDimitry Andric   // If the symbol is local, instead of the symbol's index, the assembler
1517d8e91e46SDimitry Andric   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1518d8e91e46SDimitry Andric   // Then the linker will notice the constant in the table and will look at the
1519d8e91e46SDimitry Andric   // content of the symbol.
15205a5ac124SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
15215a5ac124SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
15225a5ac124SDimitry Andric   MCContext &Ctx = getContext();
15235a5ac124SDimitry Andric 
15245a5ac124SDimitry Andric   // The offset must consider the original displacement from the base symbol
15255a5ac124SDimitry Andric   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
15265a5ac124SDimitry Andric   Offset = -MV.getConstant();
15275a5ac124SDimitry Andric   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
15285a5ac124SDimitry Andric 
15295a5ac124SDimitry Andric   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
15305a5ac124SDimitry Andric   // non_lazy_ptr stubs.
15315a5ac124SDimitry Andric   SmallString<128> Name;
15325a5ac124SDimitry Andric   StringRef Suffix = "$non_lazy_ptr";
1533dd58ef01SDimitry Andric   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
15345a5ac124SDimitry Andric   Name += Sym->getName();
15355a5ac124SDimitry Andric   Name += Suffix;
15365a5ac124SDimitry Andric   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
15375a5ac124SDimitry Andric 
15385a5ac124SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
15391d5ae102SDimitry Andric 
15401d5ae102SDimitry Andric   if (!StubSym.getPointer())
1541d8e91e46SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
15421d5ae102SDimitry Andric                                                  !GV->hasLocalLinkage());
15435a5ac124SDimitry Andric 
15445a5ac124SDimitry Andric   const MCExpr *BSymExpr =
154585d8b2bbSDimitry Andric     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
15465a5ac124SDimitry Andric   const MCExpr *LHS =
154785d8b2bbSDimitry Andric     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
15485a5ac124SDimitry Andric 
15495a5ac124SDimitry Andric   if (!Offset)
155085d8b2bbSDimitry Andric     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
15515a5ac124SDimitry Andric 
15525a5ac124SDimitry Andric   const MCExpr *RHS =
155385d8b2bbSDimitry Andric     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
155485d8b2bbSDimitry Andric   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
15555a5ac124SDimitry Andric }
15565a5ac124SDimitry Andric 
canUsePrivateLabel(const MCAsmInfo & AsmInfo,const MCSection & Section)1557dd58ef01SDimitry Andric static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1558dd58ef01SDimitry Andric                                const MCSection &Section) {
1559ac9a064cSDimitry Andric   if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols(Section))
1560dd58ef01SDimitry Andric     return true;
1561dd58ef01SDimitry Andric 
1562344a3780SDimitry Andric   // FIXME: we should be able to use private labels for sections that can't be
1563344a3780SDimitry Andric   // dead-stripped (there's no issue with blocking atomization there), but `ld
1564344a3780SDimitry Andric   // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1565344a3780SDimitry Andric   // we don't allow it.
1566dd58ef01SDimitry Andric   return false;
1567dd58ef01SDimitry Andric }
1568dd58ef01SDimitry Andric 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,const TargetMachine & TM) const1569dd58ef01SDimitry Andric void TargetLoweringObjectFileMachO::getNameWithPrefix(
1570b915e9e0SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1571dd58ef01SDimitry Andric     const TargetMachine &TM) const {
1572b915e9e0SDimitry Andric   bool CannotUsePrivateLabel = true;
1573c0981da4SDimitry Andric   if (auto *GO = GV->getAliaseeObject()) {
1574b915e9e0SDimitry Andric     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1575b915e9e0SDimitry Andric     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1576b915e9e0SDimitry Andric     CannotUsePrivateLabel =
1577dd58ef01SDimitry Andric         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1578b915e9e0SDimitry Andric   }
1579b915e9e0SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1580dd58ef01SDimitry Andric }
1581dd58ef01SDimitry Andric 
15826fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
15836fe5c7aaSRoman Divacky //                                  COFF
15846fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
15856fe5c7aaSRoman Divacky 
1586abdf259dSRoman Divacky static unsigned
getCOFFSectionFlags(SectionKind K,const TargetMachine & TM)158701095a5dSDimitry Andric getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1588abdf259dSRoman Divacky   unsigned Flags = 0;
158901095a5dSDimitry Andric   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1590abdf259dSRoman Divacky 
159166e41e3cSRoman Divacky   if (K.isMetadata())
1592abdf259dSRoman Divacky     Flags |=
159366e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1594145449b1SDimitry Andric   else if (K.isExclude())
1595145449b1SDimitry Andric     Flags |=
1596145449b1SDimitry Andric       COFF::IMAGE_SCN_LNK_REMOVE | COFF::IMAGE_SCN_MEM_DISCARDABLE;
1597abdf259dSRoman Divacky   else if (K.isText())
1598abdf259dSRoman Divacky     Flags |=
159966e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_EXECUTE |
1600cf099d11SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
160101095a5dSDimitry Andric       COFF::IMAGE_SCN_CNT_CODE |
160201095a5dSDimitry Andric       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1603abdf259dSRoman Divacky   else if (K.isBSS())
1604abdf259dSRoman Divacky     Flags |=
160566e41e3cSRoman Divacky       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
160666e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_READ |
160766e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_WRITE;
160863faed5bSDimitry Andric   else if (K.isThreadLocal())
160963faed5bSDimitry Andric     Flags |=
161063faed5bSDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
161163faed5bSDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
161263faed5bSDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
161367c32a98SDimitry Andric   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1614abdf259dSRoman Divacky     Flags |=
161566e41e3cSRoman Divacky       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
161666e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_READ;
1617abdf259dSRoman Divacky   else if (K.isWriteable())
1618abdf259dSRoman Divacky     Flags |=
161966e41e3cSRoman Divacky       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
162066e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_READ |
162166e41e3cSRoman Divacky       COFF::IMAGE_SCN_MEM_WRITE;
1622abdf259dSRoman Divacky 
1623abdf259dSRoman Divacky   return Flags;
16246fe5c7aaSRoman Divacky }
16256fe5c7aaSRoman Divacky 
getComdatGVForCOFF(const GlobalValue * GV)16265ca98fd9SDimitry Andric static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
16275ca98fd9SDimitry Andric   const Comdat *C = GV->getComdat();
16285ca98fd9SDimitry Andric   assert(C && "expected GV to have a Comdat!");
16295ca98fd9SDimitry Andric 
16305ca98fd9SDimitry Andric   StringRef ComdatGVName = C->getName();
16315ca98fd9SDimitry Andric   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
16325ca98fd9SDimitry Andric   if (!ComdatGV)
16335ca98fd9SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
16345ca98fd9SDimitry Andric                        "' does not exist.");
16355ca98fd9SDimitry Andric 
16365ca98fd9SDimitry Andric   if (ComdatGV->getComdat() != C)
16375ca98fd9SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
163867c32a98SDimitry Andric                        "' is not a key for its COMDAT.");
16395ca98fd9SDimitry Andric 
16405ca98fd9SDimitry Andric   return ComdatGV;
16415ca98fd9SDimitry Andric }
16425ca98fd9SDimitry Andric 
getSelectionForCOFF(const GlobalValue * GV)16435ca98fd9SDimitry Andric static int getSelectionForCOFF(const GlobalValue *GV) {
16445ca98fd9SDimitry Andric   if (const Comdat *C = GV->getComdat()) {
16455ca98fd9SDimitry Andric     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
16465ca98fd9SDimitry Andric     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1647c0981da4SDimitry Andric       ComdatKey = GA->getAliaseeObject();
16485ca98fd9SDimitry Andric     if (ComdatKey == GV) {
16495ca98fd9SDimitry Andric       switch (C->getSelectionKind()) {
16505ca98fd9SDimitry Andric       case Comdat::Any:
16515ca98fd9SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_ANY;
16525ca98fd9SDimitry Andric       case Comdat::ExactMatch:
16535ca98fd9SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
16545ca98fd9SDimitry Andric       case Comdat::Largest:
16555ca98fd9SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1656344a3780SDimitry Andric       case Comdat::NoDeduplicate:
16575ca98fd9SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
16585ca98fd9SDimitry Andric       case Comdat::SameSize:
16595ca98fd9SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
16605ca98fd9SDimitry Andric       }
16615ca98fd9SDimitry Andric     } else {
16625ca98fd9SDimitry Andric       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
16635ca98fd9SDimitry Andric     }
16645ca98fd9SDimitry Andric   }
16655ca98fd9SDimitry Andric   return 0;
16665ca98fd9SDimitry Andric }
16675ca98fd9SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const16685a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1669b915e9e0SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1670950076cdSDimitry Andric   StringRef Name = GO->getSection();
1671950076cdSDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1672950076cdSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
1673950076cdSDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::COFF,
1674950076cdSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
1675950076cdSDimitry Andric       Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1676950076cdSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
1677950076cdSDimitry Andric       Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1678950076cdSDimitry Andric                                       /*AddSegmentInfo=*/false))
1679950076cdSDimitry Andric     Kind = SectionKind::getMetadata();
16804a16efa3SDimitry Andric   int Selection = 0;
168101095a5dSDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
16825ca98fd9SDimitry Andric   StringRef COMDATSymName = "";
1683b915e9e0SDimitry Andric   if (GO->hasComdat()) {
1684b915e9e0SDimitry Andric     Selection = getSelectionForCOFF(GO);
16855ca98fd9SDimitry Andric     const GlobalValue *ComdatGV;
16865ca98fd9SDimitry Andric     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1687b915e9e0SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
16885ca98fd9SDimitry Andric     else
1689b915e9e0SDimitry Andric       ComdatGV = GO;
16905ca98fd9SDimitry Andric 
16915ca98fd9SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1692b915e9e0SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
16935ca98fd9SDimitry Andric       COMDATSymName = Sym->getName();
16944a16efa3SDimitry Andric       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
16955ca98fd9SDimitry Andric     } else {
16965ca98fd9SDimitry Andric       Selection = 0;
16975ca98fd9SDimitry Andric     }
16984a16efa3SDimitry Andric   }
169901095a5dSDimitry Andric 
1700ac9a064cSDimitry Andric   return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1701f8af5cf6SDimitry Andric                                      Selection);
17026fe5c7aaSRoman Divacky }
17036fe5c7aaSRoman Divacky 
getCOFFSectionNameForUniqueGlobal(SectionKind Kind)1704eb11fae6SDimitry Andric static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
17056fe5c7aaSRoman Divacky   if (Kind.isText())
17065ca98fd9SDimitry Andric     return ".text";
1707abdf259dSRoman Divacky   if (Kind.isBSS())
17085ca98fd9SDimitry Andric     return ".bss";
17095ca98fd9SDimitry Andric   if (Kind.isThreadLocal())
17105ca98fd9SDimitry Andric     return ".tls$";
171167c32a98SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
17125ca98fd9SDimitry Andric     return ".rdata";
171367c32a98SDimitry Andric   return ".data";
17146fe5c7aaSRoman Divacky }
17156fe5c7aaSRoman Divacky 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const17165a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1717b915e9e0SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
17185ca98fd9SDimitry Andric   // If we have -ffunction-sections then we should emit the global value to a
17195ca98fd9SDimitry Andric   // uniqued section specifically for it.
17205ca98fd9SDimitry Andric   bool EmitUniquedSection;
17215ca98fd9SDimitry Andric   if (Kind.isText())
17225ca98fd9SDimitry Andric     EmitUniquedSection = TM.getFunctionSections();
17235ca98fd9SDimitry Andric   else
17245ca98fd9SDimitry Andric     EmitUniquedSection = TM.getDataSections();
17256fe5c7aaSRoman Divacky 
1726b915e9e0SDimitry Andric   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1727eb11fae6SDimitry Andric     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1728eb11fae6SDimitry Andric 
172901095a5dSDimitry Andric     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1730abdf259dSRoman Divacky 
173166e41e3cSRoman Divacky     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1732b915e9e0SDimitry Andric     int Selection = getSelectionForCOFF(GO);
17335ca98fd9SDimitry Andric     if (!Selection)
17345ca98fd9SDimitry Andric       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
17355ca98fd9SDimitry Andric     const GlobalValue *ComdatGV;
1736b915e9e0SDimitry Andric     if (GO->hasComdat())
1737b915e9e0SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
17385ca98fd9SDimitry Andric     else
1739b915e9e0SDimitry Andric       ComdatGV = GO;
1740abdf259dSRoman Divacky 
174101095a5dSDimitry Andric     unsigned UniqueID = MCContext::GenericSectionID;
174201095a5dSDimitry Andric     if (EmitUniquedSection)
174301095a5dSDimitry Andric       UniqueID = NextUniqueID++;
174401095a5dSDimitry Andric 
17455ca98fd9SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1746b915e9e0SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
17475ca98fd9SDimitry Andric       StringRef COMDATSymName = Sym->getName();
1748eb11fae6SDimitry Andric 
1749b60736ecSDimitry Andric       if (const auto *F = dyn_cast<Function>(GO))
1750e3b55780SDimitry Andric         if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1751b60736ecSDimitry Andric           raw_svector_ostream(Name) << '$' << *Prefix;
1752b60736ecSDimitry Andric 
1753d8e91e46SDimitry Andric       // Append "$symbol" to the section name *before* IR-level mangling is
1754d8e91e46SDimitry Andric       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1755eb11fae6SDimitry Andric       // COFF linker will not properly handle comdats otherwise.
1756344a3780SDimitry Andric       if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1757d8e91e46SDimitry Andric         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1758eb11fae6SDimitry Andric 
1759ac9a064cSDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1760ac9a064cSDimitry Andric                                          Selection, UniqueID);
17615a5ac124SDimitry Andric     } else {
17625a5ac124SDimitry Andric       SmallString<256> TmpData;
1763b915e9e0SDimitry Andric       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1764ac9a064cSDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, TmpData,
176501095a5dSDimitry Andric                                          Selection, UniqueID);
17665ca98fd9SDimitry Andric     }
17676fe5c7aaSRoman Divacky   }
17686fe5c7aaSRoman Divacky 
17696fe5c7aaSRoman Divacky   if (Kind.isText())
1770f8af5cf6SDimitry Andric     return TextSection;
17716fe5c7aaSRoman Divacky 
177263faed5bSDimitry Andric   if (Kind.isThreadLocal())
1773f8af5cf6SDimitry Andric     return TLSDataSection;
177463faed5bSDimitry Andric 
177567c32a98SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1776f8af5cf6SDimitry Andric     return ReadOnlySection;
1777f8af5cf6SDimitry Andric 
17785ca98fd9SDimitry Andric   // Note: we claim that common symbols are put in BSSSection, but they are
17795ca98fd9SDimitry Andric   // really emitted with the magic .comm directive, which creates a symbol table
17805ca98fd9SDimitry Andric   // entry but not a section.
17815ca98fd9SDimitry Andric   if (Kind.isBSS() || Kind.isCommon())
1782f8af5cf6SDimitry Andric     return BSSSection;
1783f8af5cf6SDimitry Andric 
1784f8af5cf6SDimitry Andric   return DataSection;
17856fe5c7aaSRoman Divacky }
17866fe5c7aaSRoman Divacky 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,const TargetMachine & TM) const17875a5ac124SDimitry Andric void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1788b915e9e0SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1789dd58ef01SDimitry Andric     const TargetMachine &TM) const {
1790dd58ef01SDimitry Andric   bool CannotUsePrivateLabel = false;
17915a5ac124SDimitry Andric   if (GV->hasPrivateLinkage() &&
17925a5ac124SDimitry Andric       ((isa<Function>(GV) && TM.getFunctionSections()) ||
17935a5ac124SDimitry Andric        (isa<GlobalVariable>(GV) && TM.getDataSections())))
17945a5ac124SDimitry Andric     CannotUsePrivateLabel = true;
17955a5ac124SDimitry Andric 
1796b915e9e0SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
17975a5ac124SDimitry Andric }
17985a5ac124SDimitry Andric 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const17995a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1800b915e9e0SDimitry Andric     const Function &F, const TargetMachine &TM) const {
18015a5ac124SDimitry Andric   // If the function can be removed, produce a unique section so that
18025a5ac124SDimitry Andric   // the table doesn't prevent the removal.
18035a5ac124SDimitry Andric   const Comdat *C = F.getComdat();
18045a5ac124SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
18055a5ac124SDimitry Andric   if (!EmitUniqueSection)
18065a5ac124SDimitry Andric     return ReadOnlySection;
18075a5ac124SDimitry Andric 
18085a5ac124SDimitry Andric   // FIXME: we should produce a symbol for F instead.
18095a5ac124SDimitry Andric   if (F.hasPrivateLinkage())
18105a5ac124SDimitry Andric     return ReadOnlySection;
18115a5ac124SDimitry Andric 
1812b915e9e0SDimitry Andric   MCSymbol *Sym = TM.getSymbol(&F);
18135a5ac124SDimitry Andric   StringRef COMDATSymName = Sym->getName();
18145a5ac124SDimitry Andric 
18155a5ac124SDimitry Andric   SectionKind Kind = SectionKind::getReadOnly();
1816eb11fae6SDimitry Andric   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
181701095a5dSDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
18185a5ac124SDimitry Andric   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
181901095a5dSDimitry Andric   unsigned UniqueID = NextUniqueID++;
18205a5ac124SDimitry Andric 
1821ac9a064cSDimitry Andric   return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName,
1822ac9a064cSDimitry Andric                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE,
1823ac9a064cSDimitry Andric                                      UniqueID);
18245a5ac124SDimitry Andric }
18255a5ac124SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const18267fa27ce4SDimitry Andric bool TargetLoweringObjectFileCOFF::shouldPutJumpTableInFunctionSection(
18277fa27ce4SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
18287fa27ce4SDimitry Andric   if (TM->getTargetTriple().getArch() == Triple::x86_64) {
18297fa27ce4SDimitry Andric     if (!JumpTableInFunctionSection) {
18307fa27ce4SDimitry Andric       // We can always create relative relocations, so use another section
18317fa27ce4SDimitry Andric       // that can be marked non-executable.
18327fa27ce4SDimitry Andric       return false;
18337fa27ce4SDimitry Andric     }
18347fa27ce4SDimitry Andric   }
18357fa27ce4SDimitry Andric   return TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
18367fa27ce4SDimitry Andric     UsesLabelDifference, F);
18377fa27ce4SDimitry Andric }
18387fa27ce4SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const1839eb11fae6SDimitry Andric void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1840eb11fae6SDimitry Andric                                                       Module &M) const {
1841b60736ecSDimitry Andric   emitLinkerDirectives(Streamer, M);
1842b60736ecSDimitry Andric 
1843b60736ecSDimitry Andric   unsigned Version = 0;
1844b60736ecSDimitry Andric   unsigned Flags = 0;
1845b60736ecSDimitry Andric   StringRef Section;
1846b60736ecSDimitry Andric 
1847b60736ecSDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
1848b60736ecSDimitry Andric   if (!Section.empty()) {
1849b60736ecSDimitry Andric     auto &C = getContext();
1850ac9a064cSDimitry Andric     auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1851ac9a064cSDimitry Andric                                             COFF::IMAGE_SCN_MEM_READ);
1852145449b1SDimitry Andric     Streamer.switchSection(S);
1853b60736ecSDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1854b60736ecSDimitry Andric     Streamer.emitInt32(Version);
1855b60736ecSDimitry Andric     Streamer.emitInt32(Flags);
1856145449b1SDimitry Andric     Streamer.addBlankLine();
1857b60736ecSDimitry Andric   }
1858b60736ecSDimitry Andric 
1859b60736ecSDimitry Andric   emitCGProfileMetadata(Streamer, M);
1860b60736ecSDimitry Andric }
1861b60736ecSDimitry Andric 
emitLinkerDirectives(MCStreamer & Streamer,Module & M) const1862b60736ecSDimitry Andric void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1863b60736ecSDimitry Andric     MCStreamer &Streamer, Module &M) const {
18647c7aba6eSDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
186559d6cff9SDimitry Andric     // Emit the linker options to the linker .drectve section.  According to the
186601095a5dSDimitry Andric     // spec, this section is a space-separated string containing flags for
186701095a5dSDimitry Andric     // linker.
18685a5ac124SDimitry Andric     MCSection *Sec = getDrectveSection();
1869145449b1SDimitry Andric     Streamer.switchSection(Sec);
1870706b4fc4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
187101095a5dSDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
187259d6cff9SDimitry Andric         // Lead with a space for consistency with our dllexport implementation.
18735a5ac124SDimitry Andric         std::string Directive(" ");
1874cfca06d7SDimitry Andric         Directive.append(std::string(cast<MDString>(Piece)->getString()));
1875cfca06d7SDimitry Andric         Streamer.emitBytes(Directive);
187659d6cff9SDimitry Andric       }
187759d6cff9SDimitry Andric     }
187859d6cff9SDimitry Andric   }
18797ab83427SDimitry Andric 
1880b60736ecSDimitry Andric   // Emit /EXPORT: flags for each exported global as necessary.
1881b60736ecSDimitry Andric   std::string Flags;
1882b60736ecSDimitry Andric   for (const GlobalValue &GV : M.global_values()) {
1883b60736ecSDimitry Andric     raw_string_ostream OS(Flags);
1884344a3780SDimitry Andric     emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1885344a3780SDimitry Andric                                  getMangler());
1886b60736ecSDimitry Andric     OS.flush();
1887b60736ecSDimitry Andric     if (!Flags.empty()) {
1888145449b1SDimitry Andric       Streamer.switchSection(getDrectveSection());
1889b60736ecSDimitry Andric       Streamer.emitBytes(Flags);
1890b60736ecSDimitry Andric     }
1891b60736ecSDimitry Andric     Flags.clear();
1892b60736ecSDimitry Andric   }
18937ab83427SDimitry Andric 
1894b60736ecSDimitry Andric   // Emit /INCLUDE: flags for each used global as necessary.
1895b60736ecSDimitry Andric   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1896b60736ecSDimitry Andric     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1897b60736ecSDimitry Andric     assert(isa<ArrayType>(LU->getValueType()) &&
1898b60736ecSDimitry Andric            "expected llvm.used to be an array type");
1899b60736ecSDimitry Andric     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1900b60736ecSDimitry Andric       for (const Value *Op : A->operands()) {
1901b60736ecSDimitry Andric         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1902b60736ecSDimitry Andric         // Global symbols with internal or private linkage are not visible to
1903b60736ecSDimitry Andric         // the linker, and thus would cause an error when the linker tried to
1904b60736ecSDimitry Andric         // preserve the symbol due to the `/include:` directive.
1905b60736ecSDimitry Andric         if (GV->hasLocalLinkage())
1906b60736ecSDimitry Andric           continue;
19077ab83427SDimitry Andric 
1908b60736ecSDimitry Andric         raw_string_ostream OS(Flags);
1909344a3780SDimitry Andric         emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1910344a3780SDimitry Andric                                    getMangler());
1911b60736ecSDimitry Andric         OS.flush();
1912b60736ecSDimitry Andric 
1913b60736ecSDimitry Andric         if (!Flags.empty()) {
1914145449b1SDimitry Andric           Streamer.switchSection(getDrectveSection());
1915b60736ecSDimitry Andric           Streamer.emitBytes(Flags);
1916b60736ecSDimitry Andric         }
1917b60736ecSDimitry Andric         Flags.clear();
1918b60736ecSDimitry Andric       }
1919b60736ecSDimitry Andric     }
1920b60736ecSDimitry Andric   }
192101095a5dSDimitry Andric }
19225ca98fd9SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TM)1923b915e9e0SDimitry Andric void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1924b915e9e0SDimitry Andric                                               const TargetMachine &TM) {
1925b915e9e0SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1926b60736ecSDimitry Andric   this->TM = &TM;
1927b915e9e0SDimitry Andric   const Triple &T = TM.getTargetTriple();
1928e6d15924SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1929b915e9e0SDimitry Andric     StaticCtorSection =
1930b915e9e0SDimitry Andric         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1931ac9a064cSDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ);
1932b915e9e0SDimitry Andric     StaticDtorSection =
1933b915e9e0SDimitry Andric         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1934ac9a064cSDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ);
1935b915e9e0SDimitry Andric   } else {
1936b915e9e0SDimitry Andric     StaticCtorSection = Ctx.getCOFFSection(
1937b915e9e0SDimitry Andric         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1938ac9a064cSDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE);
1939b915e9e0SDimitry Andric     StaticDtorSection = Ctx.getCOFFSection(
1940b915e9e0SDimitry Andric         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1941ac9a064cSDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE);
1942b915e9e0SDimitry Andric   }
1943b915e9e0SDimitry Andric }
1944b915e9e0SDimitry Andric 
getCOFFStaticStructorSection(MCContext & Ctx,const Triple & T,bool IsCtor,unsigned Priority,const MCSymbol * KeySym,MCSectionCOFF * Default)1945044eb2f6SDimitry Andric static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1946044eb2f6SDimitry Andric                                                    const Triple &T, bool IsCtor,
1947044eb2f6SDimitry Andric                                                    unsigned Priority,
1948044eb2f6SDimitry Andric                                                    const MCSymbol *KeySym,
1949044eb2f6SDimitry Andric                                                    MCSectionCOFF *Default) {
1950e6d15924SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1951d8e91e46SDimitry Andric     // If the priority is the default, use .CRT$XCU, possibly associative.
1952d8e91e46SDimitry Andric     if (Priority == 65535)
1953044eb2f6SDimitry Andric       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1954044eb2f6SDimitry Andric 
1955d8e91e46SDimitry Andric     // Otherwise, we need to compute a new section name. Low priorities should
1956d8e91e46SDimitry Andric     // run earlier. The linker will sort sections ASCII-betically, and we need a
1957d8e91e46SDimitry Andric     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1958d8e91e46SDimitry Andric     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1959d8e91e46SDimitry Andric     // low priorities need to sort before 'L', since the CRT uses that
1960e3b55780SDimitry Andric     // internally, so we use ".CRT$XCA00001" for them. We have a contract with
1961e3b55780SDimitry Andric     // the frontend that "init_seg(compiler)" corresponds to priority 200 and
1962e3b55780SDimitry Andric     // "init_seg(lib)" corresponds to priority 400, and those respectively use
1963e3b55780SDimitry Andric     // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
1964e3b55780SDimitry Andric     // use 'C' with the priority as a suffix.
1965d8e91e46SDimitry Andric     SmallString<24> Name;
1966e3b55780SDimitry Andric     char LastLetter = 'T';
1967e3b55780SDimitry Andric     bool AddPrioritySuffix = Priority != 200 && Priority != 400;
1968e3b55780SDimitry Andric     if (Priority < 200)
1969e3b55780SDimitry Andric       LastLetter = 'A';
1970e3b55780SDimitry Andric     else if (Priority < 400)
1971e3b55780SDimitry Andric       LastLetter = 'C';
1972e3b55780SDimitry Andric     else if (Priority == 400)
1973e3b55780SDimitry Andric       LastLetter = 'L';
1974d8e91e46SDimitry Andric     raw_svector_ostream OS(Name);
1975e3b55780SDimitry Andric     OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
1976e3b55780SDimitry Andric     if (AddPrioritySuffix)
1977e3b55780SDimitry Andric       OS << format("%05u", Priority);
1978d8e91e46SDimitry Andric     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1979ac9a064cSDimitry Andric         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ);
1980d8e91e46SDimitry Andric     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1981d8e91e46SDimitry Andric   }
1982d8e91e46SDimitry Andric 
1983044eb2f6SDimitry Andric   std::string Name = IsCtor ? ".ctors" : ".dtors";
1984044eb2f6SDimitry Andric   if (Priority != 65535)
1985044eb2f6SDimitry Andric     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1986044eb2f6SDimitry Andric 
1987044eb2f6SDimitry Andric   return Ctx.getAssociativeCOFFSection(
1988044eb2f6SDimitry Andric       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1989044eb2f6SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ |
1990ac9a064cSDimitry Andric                                    COFF::IMAGE_SCN_MEM_WRITE),
1991044eb2f6SDimitry Andric       KeySym, 0);
1992044eb2f6SDimitry Andric }
1993044eb2f6SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const19945a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
19955ca98fd9SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1996344a3780SDimitry Andric   return getCOFFStaticStructorSection(
1997344a3780SDimitry Andric       getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
1998044eb2f6SDimitry Andric       cast<MCSectionCOFF>(StaticCtorSection));
19995ca98fd9SDimitry Andric }
20005ca98fd9SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const20015a5ac124SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
20025ca98fd9SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2003344a3780SDimitry Andric   return getCOFFStaticStructorSection(
2004344a3780SDimitry Andric       getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2005044eb2f6SDimitry Andric       cast<MCSectionCOFF>(StaticDtorSection));
20065ca98fd9SDimitry Andric }
20071a82d4c0SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const2008eb11fae6SDimitry Andric const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
2009eb11fae6SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
2010eb11fae6SDimitry Andric     const TargetMachine &TM) const {
2011eb11fae6SDimitry Andric   const Triple &T = TM.getTargetTriple();
2012e6d15924SDimitry Andric   if (T.isOSCygMing())
2013eb11fae6SDimitry Andric     return nullptr;
2014eb11fae6SDimitry Andric 
2015eb11fae6SDimitry Andric   // Our symbols should exist in address space zero, cowardly no-op if
2016eb11fae6SDimitry Andric   // otherwise.
2017eb11fae6SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2018eb11fae6SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0)
2019eb11fae6SDimitry Andric     return nullptr;
2020eb11fae6SDimitry Andric 
2021eb11fae6SDimitry Andric   // Both ptrtoint instructions must wrap global objects:
2022eb11fae6SDimitry Andric   // - Only global variables are eligible for image relative relocations.
2023eb11fae6SDimitry Andric   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
2024eb11fae6SDimitry Andric   // We expect __ImageBase to be a global variable without a section, externally
2025eb11fae6SDimitry Andric   // defined.
2026eb11fae6SDimitry Andric   //
2027eb11fae6SDimitry Andric   // It should look something like this: @__ImageBase = external constant i8
2028eb11fae6SDimitry Andric   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
2029eb11fae6SDimitry Andric       LHS->isThreadLocal() || RHS->isThreadLocal() ||
2030eb11fae6SDimitry Andric       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
2031eb11fae6SDimitry Andric       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2032eb11fae6SDimitry Andric     return nullptr;
2033eb11fae6SDimitry Andric 
2034eb11fae6SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
2035eb11fae6SDimitry Andric                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
2036eb11fae6SDimitry Andric                                  getContext());
2037eb11fae6SDimitry Andric }
2038eb11fae6SDimitry Andric 
APIntToHexString(const APInt & AI)2039eb11fae6SDimitry Andric static std::string APIntToHexString(const APInt &AI) {
2040eb11fae6SDimitry Andric   unsigned Width = (AI.getBitWidth() / 8) * 2;
2041344a3780SDimitry Andric   std::string HexString = toString(AI, 16, /*Signed=*/false);
2042cfca06d7SDimitry Andric   llvm::transform(HexString, HexString.begin(), tolower);
2043eb11fae6SDimitry Andric   unsigned Size = HexString.size();
2044eb11fae6SDimitry Andric   assert(Width >= Size && "hex string is too large!");
2045eb11fae6SDimitry Andric   HexString.insert(HexString.begin(), Width - Size, '0');
2046eb11fae6SDimitry Andric 
2047eb11fae6SDimitry Andric   return HexString;
2048eb11fae6SDimitry Andric }
2049eb11fae6SDimitry Andric 
scalarConstantToHexString(const Constant * C)2050eb11fae6SDimitry Andric static std::string scalarConstantToHexString(const Constant *C) {
2051eb11fae6SDimitry Andric   Type *Ty = C->getType();
2052eb11fae6SDimitry Andric   if (isa<UndefValue>(C)) {
2053c0981da4SDimitry Andric     return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
2054eb11fae6SDimitry Andric   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2055eb11fae6SDimitry Andric     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2056eb11fae6SDimitry Andric   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2057eb11fae6SDimitry Andric     return APIntToHexString(CI->getValue());
2058eb11fae6SDimitry Andric   } else {
2059eb11fae6SDimitry Andric     unsigned NumElements;
2060cfca06d7SDimitry Andric     if (auto *VTy = dyn_cast<VectorType>(Ty))
2061cfca06d7SDimitry Andric       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2062eb11fae6SDimitry Andric     else
2063eb11fae6SDimitry Andric       NumElements = Ty->getArrayNumElements();
2064eb11fae6SDimitry Andric     std::string HexString;
2065eb11fae6SDimitry Andric     for (int I = NumElements - 1, E = -1; I != E; --I)
2066eb11fae6SDimitry Andric       HexString += scalarConstantToHexString(C->getAggregateElement(I));
2067eb11fae6SDimitry Andric     return HexString;
2068eb11fae6SDimitry Andric   }
2069eb11fae6SDimitry Andric }
2070eb11fae6SDimitry Andric 
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const2071eb11fae6SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
2072eb11fae6SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
2073cfca06d7SDimitry Andric     Align &Alignment) const {
2074eb11fae6SDimitry Andric   if (Kind.isMergeableConst() && C &&
2075eb11fae6SDimitry Andric       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
2076eb11fae6SDimitry Andric     // This creates comdat sections with the given symbol name, but unless
2077eb11fae6SDimitry Andric     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2078eb11fae6SDimitry Andric     // will be created with a null storage class, which makes GNU binutils
2079eb11fae6SDimitry Andric     // error out.
2080eb11fae6SDimitry Andric     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2081eb11fae6SDimitry Andric                                      COFF::IMAGE_SCN_MEM_READ |
2082eb11fae6SDimitry Andric                                      COFF::IMAGE_SCN_LNK_COMDAT;
2083eb11fae6SDimitry Andric     std::string COMDATSymName;
2084eb11fae6SDimitry Andric     if (Kind.isMergeableConst4()) {
2085cfca06d7SDimitry Andric       if (Alignment <= 4) {
2086eb11fae6SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
2087cfca06d7SDimitry Andric         Alignment = Align(4);
2088eb11fae6SDimitry Andric       }
2089eb11fae6SDimitry Andric     } else if (Kind.isMergeableConst8()) {
2090cfca06d7SDimitry Andric       if (Alignment <= 8) {
2091eb11fae6SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
2092cfca06d7SDimitry Andric         Alignment = Align(8);
2093eb11fae6SDimitry Andric       }
2094eb11fae6SDimitry Andric     } else if (Kind.isMergeableConst16()) {
2095eb11fae6SDimitry Andric       // FIXME: These may not be appropriate for non-x86 architectures.
2096cfca06d7SDimitry Andric       if (Alignment <= 16) {
2097eb11fae6SDimitry Andric         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2098cfca06d7SDimitry Andric         Alignment = Align(16);
2099eb11fae6SDimitry Andric       }
2100eb11fae6SDimitry Andric     } else if (Kind.isMergeableConst32()) {
2101cfca06d7SDimitry Andric       if (Alignment <= 32) {
2102eb11fae6SDimitry Andric         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2103cfca06d7SDimitry Andric         Alignment = Align(32);
2104eb11fae6SDimitry Andric       }
2105eb11fae6SDimitry Andric     }
2106eb11fae6SDimitry Andric 
2107eb11fae6SDimitry Andric     if (!COMDATSymName.empty())
2108ac9a064cSDimitry Andric       return getContext().getCOFFSection(".rdata", Characteristics,
2109eb11fae6SDimitry Andric                                          COMDATSymName,
2110eb11fae6SDimitry Andric                                          COFF::IMAGE_COMDAT_SELECT_ANY);
2111eb11fae6SDimitry Andric   }
2112eb11fae6SDimitry Andric 
2113cfca06d7SDimitry Andric   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
2114cfca06d7SDimitry Andric                                                          Alignment);
2115eb11fae6SDimitry Andric }
2116eb11fae6SDimitry Andric 
211771d5a254SDimitry Andric //===----------------------------------------------------------------------===//
211871d5a254SDimitry Andric //                                  Wasm
211971d5a254SDimitry Andric //===----------------------------------------------------------------------===//
212071d5a254SDimitry Andric 
getWasmComdat(const GlobalValue * GV)2121eb11fae6SDimitry Andric static const Comdat *getWasmComdat(const GlobalValue *GV) {
212271d5a254SDimitry Andric   const Comdat *C = GV->getComdat();
212371d5a254SDimitry Andric   if (!C)
2124eb11fae6SDimitry Andric     return nullptr;
212571d5a254SDimitry Andric 
2126eb11fae6SDimitry Andric   if (C->getSelectionKind() != Comdat::Any)
2127eb11fae6SDimitry Andric     report_fatal_error("WebAssembly COMDATs only support "
2128eb11fae6SDimitry Andric                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
2129eb11fae6SDimitry Andric                        "lowered.");
2130eb11fae6SDimitry Andric 
2131eb11fae6SDimitry Andric   return C;
2132044eb2f6SDimitry Andric }
213371d5a254SDimitry Andric 
getWasmSectionFlags(SectionKind K,bool Retain)2134ac9a064cSDimitry Andric static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2135344a3780SDimitry Andric   unsigned Flags = 0;
2136344a3780SDimitry Andric 
2137344a3780SDimitry Andric   if (K.isThreadLocal())
2138344a3780SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_TLS;
2139344a3780SDimitry Andric 
2140344a3780SDimitry Andric   if (K.isMergeableCString())
2141344a3780SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_STRINGS;
2142344a3780SDimitry Andric 
2143ac9a064cSDimitry Andric   if (Retain)
2144ac9a064cSDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_RETAIN;
2145ac9a064cSDimitry Andric 
2146344a3780SDimitry Andric   // TODO(sbc): Add suport for K.isMergeableConst()
2147344a3780SDimitry Andric 
2148344a3780SDimitry Andric   return Flags;
2149344a3780SDimitry Andric }
2150344a3780SDimitry Andric 
getModuleMetadata(Module & M)2151ac9a064cSDimitry Andric void TargetLoweringObjectFileWasm::getModuleMetadata(Module &M) {
2152ac9a064cSDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
2153ac9a064cSDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
2154ac9a064cSDimitry Andric   for (GlobalValue *GV : Vec)
2155ac9a064cSDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
2156ac9a064cSDimitry Andric       Used.insert(GO);
2157ac9a064cSDimitry Andric }
2158ac9a064cSDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const215971d5a254SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
216071d5a254SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2161eb11fae6SDimitry Andric   // We don't support explict section names for functions in the wasm object
2162eb11fae6SDimitry Andric   // format.  Each function has to be in its own unique section.
2163eb11fae6SDimitry Andric   if (isa<Function>(GO)) {
2164eb11fae6SDimitry Andric     return SelectSectionForGlobal(GO, Kind, TM);
2165eb11fae6SDimitry Andric   }
2166eb11fae6SDimitry Andric 
2167044eb2f6SDimitry Andric   StringRef Name = GO->getSection();
2168eb11fae6SDimitry Andric 
2169cfca06d7SDimitry Andric   // Certain data sections we treat as named custom sections rather than
2170cfca06d7SDimitry Andric   // segments within the data section.
2171cfca06d7SDimitry Andric   // This could be avoided if all data segements (the wasm sense) were
2172cfca06d7SDimitry Andric   // represented as their own sections (in the llvm sense).
2173cfca06d7SDimitry Andric   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2174cfca06d7SDimitry Andric   if (Name == ".llvmcmd" || Name == ".llvmbc")
2175cfca06d7SDimitry Andric     Kind = SectionKind::getMetadata();
2176eb11fae6SDimitry Andric 
2177eb11fae6SDimitry Andric   StringRef Group = "";
2178eb11fae6SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2179eb11fae6SDimitry Andric     Group = C->getName();
2180eb11fae6SDimitry Andric   }
2181eb11fae6SDimitry Andric 
2182ac9a064cSDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2183344a3780SDimitry Andric   MCSectionWasm *Section = getContext().getWasmSection(
2184344a3780SDimitry Andric       Name, Kind, Flags, Group, MCContext::GenericSectionID);
2185e6d15924SDimitry Andric 
2186e6d15924SDimitry Andric   return Section;
218771d5a254SDimitry Andric }
218871d5a254SDimitry Andric 
2189ac9a064cSDimitry Andric static MCSectionWasm *
selectWasmSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool EmitUniqueSection,unsigned * NextUniqueID,bool Retain)2190ac9a064cSDimitry Andric selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
2191ac9a064cSDimitry Andric                            SectionKind Kind, Mangler &Mang,
2192ac9a064cSDimitry Andric                            const TargetMachine &TM, bool EmitUniqueSection,
2193ac9a064cSDimitry Andric                            unsigned *NextUniqueID, bool Retain) {
219471d5a254SDimitry Andric   StringRef Group = "";
2195eb11fae6SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2196eb11fae6SDimitry Andric     Group = C->getName();
2197eb11fae6SDimitry Andric   }
219871d5a254SDimitry Andric 
219971d5a254SDimitry Andric   bool UniqueSectionNames = TM.getUniqueSectionNames();
22007fa27ce4SDimitry Andric   SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
220171d5a254SDimitry Andric 
220271d5a254SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
220371d5a254SDimitry Andric     const auto &OptionalPrefix = F->getSectionPrefix();
220471d5a254SDimitry Andric     if (OptionalPrefix)
2205b60736ecSDimitry Andric       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
220671d5a254SDimitry Andric   }
220771d5a254SDimitry Andric 
220871d5a254SDimitry Andric   if (EmitUniqueSection && UniqueSectionNames) {
220971d5a254SDimitry Andric     Name.push_back('.');
221071d5a254SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, true);
221171d5a254SDimitry Andric   }
221271d5a254SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
221371d5a254SDimitry Andric   if (EmitUniqueSection && !UniqueSectionNames) {
221471d5a254SDimitry Andric     UniqueID = *NextUniqueID;
221571d5a254SDimitry Andric     (*NextUniqueID)++;
221671d5a254SDimitry Andric   }
2217e6d15924SDimitry Andric 
2218ac9a064cSDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind, Retain);
2219344a3780SDimitry Andric   return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
222071d5a254SDimitry Andric }
222171d5a254SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const222271d5a254SDimitry Andric MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
222371d5a254SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
222471d5a254SDimitry Andric 
222571d5a254SDimitry Andric   if (Kind.isCommon())
222671d5a254SDimitry Andric     report_fatal_error("mergable sections not supported yet on wasm");
222771d5a254SDimitry Andric 
222871d5a254SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
222971d5a254SDimitry Andric   // global value to a uniqued section specifically for it.
223071d5a254SDimitry Andric   bool EmitUniqueSection = false;
223171d5a254SDimitry Andric   if (Kind.isText())
223271d5a254SDimitry Andric     EmitUniqueSection = TM.getFunctionSections();
223371d5a254SDimitry Andric   else
223471d5a254SDimitry Andric     EmitUniqueSection = TM.getDataSections();
223571d5a254SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
2236ac9a064cSDimitry Andric   bool Retain = Used.count(GO);
2237ac9a064cSDimitry Andric   EmitUniqueSection |= Retain;
223871d5a254SDimitry Andric 
223971d5a254SDimitry Andric   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2240ac9a064cSDimitry Andric                                     EmitUniqueSection, &NextUniqueID, Retain);
224171d5a254SDimitry Andric }
224271d5a254SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const224371d5a254SDimitry Andric bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
224471d5a254SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
224571d5a254SDimitry Andric   // We can always create relative relocations, so use another section
224671d5a254SDimitry Andric   // that can be marked non-executable.
224771d5a254SDimitry Andric   return false;
224871d5a254SDimitry Andric }
224971d5a254SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const225071d5a254SDimitry Andric const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
225171d5a254SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
225271d5a254SDimitry Andric     const TargetMachine &TM) const {
225371d5a254SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
225471d5a254SDimitry Andric   // functions.
225571d5a254SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
225671d5a254SDimitry Andric     return nullptr;
225771d5a254SDimitry Andric 
2258f65dcba8SDimitry Andric   // Basic correctness checks.
225971d5a254SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
226071d5a254SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
226171d5a254SDimitry Andric       RHS->isThreadLocal())
226271d5a254SDimitry Andric     return nullptr;
226371d5a254SDimitry Andric 
226471d5a254SDimitry Andric   return MCBinaryExpr::createSub(
226571d5a254SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
226671d5a254SDimitry Andric                               getContext()),
226771d5a254SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
226871d5a254SDimitry Andric }
226971d5a254SDimitry Andric 
InitializeWasm()2270044eb2f6SDimitry Andric void TargetLoweringObjectFileWasm::InitializeWasm() {
2271044eb2f6SDimitry Andric   StaticCtorSection =
2272044eb2f6SDimitry Andric       getContext().getWasmSection(".init_array", SectionKind::getData());
2273d8e91e46SDimitry Andric 
2274d8e91e46SDimitry Andric   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2275d8e91e46SDimitry Andric   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2276d8e91e46SDimitry Andric   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2277044eb2f6SDimitry Andric }
2278044eb2f6SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const2279044eb2f6SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2280044eb2f6SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2281044eb2f6SDimitry Andric   return Priority == UINT16_MAX ?
2282044eb2f6SDimitry Andric          StaticCtorSection :
2283044eb2f6SDimitry Andric          getContext().getWasmSection(".init_array." + utostr(Priority),
2284044eb2f6SDimitry Andric                                      SectionKind::getData());
2285044eb2f6SDimitry Andric }
2286044eb2f6SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const2287044eb2f6SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2288044eb2f6SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2289145449b1SDimitry Andric   report_fatal_error("@llvm.global_dtors should have been lowered already");
22901a82d4c0SDimitry Andric }
22911d5ae102SDimitry Andric 
22921d5ae102SDimitry Andric //===----------------------------------------------------------------------===//
22931d5ae102SDimitry Andric //                                  XCOFF
22941d5ae102SDimitry Andric //===----------------------------------------------------------------------===//
ShouldEmitEHBlock(const MachineFunction * MF)2295b60736ecSDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2296b60736ecSDimitry Andric     const MachineFunction *MF) {
2297b60736ecSDimitry Andric   if (!MF->getLandingPads().empty())
2298b60736ecSDimitry Andric     return true;
2299b60736ecSDimitry Andric 
2300b60736ecSDimitry Andric   const Function &F = MF->getFunction();
2301b60736ecSDimitry Andric   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2302b60736ecSDimitry Andric     return false;
2303b60736ecSDimitry Andric 
2304344a3780SDimitry Andric   const GlobalValue *Per =
2305344a3780SDimitry Andric       dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2306344a3780SDimitry Andric   assert(Per && "Personality routine is not a GlobalValue type.");
2307b60736ecSDimitry Andric   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2308b60736ecSDimitry Andric     return false;
2309b60736ecSDimitry Andric 
2310b60736ecSDimitry Andric   return true;
2311b60736ecSDimitry Andric }
2312b60736ecSDimitry Andric 
ShouldSetSSPCanaryBitInTB(const MachineFunction * MF)2313344a3780SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
2314344a3780SDimitry Andric     const MachineFunction *MF) {
2315344a3780SDimitry Andric   const Function &F = MF->getFunction();
2316344a3780SDimitry Andric   if (!F.hasStackProtectorFnAttr())
2317344a3780SDimitry Andric     return false;
2318344a3780SDimitry Andric   // FIXME: check presence of canary word
2319344a3780SDimitry Andric   // There are cases that the stack protectors are not really inserted even if
2320344a3780SDimitry Andric   // the attributes are on.
2321344a3780SDimitry Andric   return true;
2322344a3780SDimitry Andric }
2323344a3780SDimitry Andric 
2324b60736ecSDimitry Andric MCSymbol *
getEHInfoTableSymbol(const MachineFunction * MF)2325b60736ecSDimitry Andric TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2326ac9a064cSDimitry Andric   MCSymbol *EHInfoSym = MF->getContext().getOrCreateSymbol(
2327b60736ecSDimitry Andric       "__ehinfo." + Twine(MF->getFunctionNumber()));
2328b1c73532SDimitry Andric   cast<MCSymbolXCOFF>(EHInfoSym)->setEHInfo();
2329b1c73532SDimitry Andric   return EHInfoSym;
2330b60736ecSDimitry Andric }
2331b60736ecSDimitry Andric 
2332cfca06d7SDimitry Andric MCSymbol *
getTargetSymbol(const GlobalValue * GV,const TargetMachine & TM) const2333cfca06d7SDimitry Andric TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
2334cfca06d7SDimitry Andric                                                const TargetMachine &TM) const {
2335cfca06d7SDimitry Andric   // We always use a qualname symbol for a GV that represents
2336cfca06d7SDimitry Andric   // a declaration, a function descriptor, or a common symbol.
2337b60736ecSDimitry Andric   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2338b60736ecSDimitry Andric   // also return a qualname so that a label symbol could be avoided.
2339cfca06d7SDimitry Andric   // It is inherently ambiguous when the GO represents the address of a
2340cfca06d7SDimitry Andric   // function, as the GO could either represent a function descriptor or a
2341cfca06d7SDimitry Andric   // function entry point. We choose to always return a function descriptor
2342cfca06d7SDimitry Andric   // here.
2343cfca06d7SDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2344e3b55780SDimitry Andric     if (GO->isDeclarationForLinker())
2345e3b55780SDimitry Andric       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2346e3b55780SDimitry Andric           ->getQualNameSymbol();
2347e3b55780SDimitry Andric 
2348344a3780SDimitry Andric     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2349344a3780SDimitry Andric       if (GVar->hasAttribute("toc-data"))
2350344a3780SDimitry Andric         return cast<MCSectionXCOFF>(
2351344a3780SDimitry Andric                    SectionForGlobal(GVar, SectionKind::getData(), TM))
2352344a3780SDimitry Andric             ->getQualNameSymbol();
2353344a3780SDimitry Andric 
2354cfca06d7SDimitry Andric     SectionKind GOKind = getKindForGlobal(GO, TM);
2355cfca06d7SDimitry Andric     if (GOKind.isText())
2356cfca06d7SDimitry Andric       return cast<MCSectionXCOFF>(
2357cfca06d7SDimitry Andric                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2358cfca06d7SDimitry Andric           ->getQualNameSymbol();
2359344a3780SDimitry Andric     if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2360344a3780SDimitry Andric         GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2361cfca06d7SDimitry Andric       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2362cfca06d7SDimitry Andric           ->getQualNameSymbol();
2363cfca06d7SDimitry Andric   }
2364cfca06d7SDimitry Andric 
2365cfca06d7SDimitry Andric   // For all other cases, fall back to getSymbol to return the unqualified name.
2366cfca06d7SDimitry Andric   return nullptr;
2367cfca06d7SDimitry Andric }
2368cfca06d7SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const23691d5ae102SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
23701d5ae102SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2371b60736ecSDimitry Andric   if (!GO->hasSection())
2372b60736ecSDimitry Andric     report_fatal_error("#pragma clang section is not yet supported");
2373b60736ecSDimitry Andric 
2374b60736ecSDimitry Andric   StringRef SectionName = GO->getSection();
2375344a3780SDimitry Andric 
2376344a3780SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2377344a3780SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2378344a3780SDimitry Andric     if (GVar->hasAttribute("toc-data"))
2379344a3780SDimitry Andric       return getContext().getXCOFFSection(
2380344a3780SDimitry Andric           SectionName, Kind,
2381344a3780SDimitry Andric           XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
2382344a3780SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2383344a3780SDimitry Andric 
2384b60736ecSDimitry Andric   XCOFF::StorageMappingClass MappingClass;
2385b60736ecSDimitry Andric   if (Kind.isText())
2386b60736ecSDimitry Andric     MappingClass = XCOFF::XMC_PR;
23877fa27ce4SDimitry Andric   else if (Kind.isData() || Kind.isBSS())
2388b60736ecSDimitry Andric     MappingClass = XCOFF::XMC_RW;
23897fa27ce4SDimitry Andric   else if (Kind.isReadOnlyWithRel())
23907fa27ce4SDimitry Andric     MappingClass =
23917fa27ce4SDimitry Andric         TM.Options.XCOFFReadOnlyPointers ? XCOFF::XMC_RO : XCOFF::XMC_RW;
2392b60736ecSDimitry Andric   else if (Kind.isReadOnly())
2393b60736ecSDimitry Andric     MappingClass = XCOFF::XMC_RO;
2394b60736ecSDimitry Andric   else
2395b60736ecSDimitry Andric     report_fatal_error("XCOFF other section types not yet implemented.");
2396b60736ecSDimitry Andric 
2397344a3780SDimitry Andric   return getContext().getXCOFFSection(
2398344a3780SDimitry Andric       SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2399344a3780SDimitry Andric       /* MultiSymbolsAllowed*/ true);
24001d5ae102SDimitry Andric }
24011d5ae102SDimitry Andric 
getSectionForExternalReference(const GlobalObject * GO,const TargetMachine & TM) const2402cfca06d7SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
2403cfca06d7SDimitry Andric     const GlobalObject *GO, const TargetMachine &TM) const {
2404cfca06d7SDimitry Andric   assert(GO->isDeclarationForLinker() &&
2405cfca06d7SDimitry Andric          "Tried to get ER section for a defined global.");
2406cfca06d7SDimitry Andric 
2407cfca06d7SDimitry Andric   SmallString<128> Name;
2408cfca06d7SDimitry Andric   getNameWithPrefix(Name, GO, TM);
2409cfca06d7SDimitry Andric 
2410ac9a064cSDimitry Andric   // AIX TLS local-dynamic does not need the external reference for the
2411ac9a064cSDimitry Andric   // "_$TLSML" symbol.
2412ac9a064cSDimitry Andric   if (GO->getThreadLocalMode() == GlobalVariable::LocalDynamicTLSModel &&
2413ac9a064cSDimitry Andric       GO->hasName() && GO->getName() == "_$TLSML") {
2414ac9a064cSDimitry Andric     return getContext().getXCOFFSection(
2415ac9a064cSDimitry Andric         Name, SectionKind::getData(),
2416ac9a064cSDimitry Andric         XCOFF::CsectProperties(XCOFF::XMC_TC, XCOFF::XTY_SD));
2417ac9a064cSDimitry Andric   }
2418ac9a064cSDimitry Andric 
2419344a3780SDimitry Andric   XCOFF::StorageMappingClass SMC =
2420344a3780SDimitry Andric       isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2421344a3780SDimitry Andric   if (GO->isThreadLocal())
2422344a3780SDimitry Andric     SMC = XCOFF::XMC_UL;
2423344a3780SDimitry Andric 
2424e3b55780SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2425e3b55780SDimitry Andric     if (GVar->hasAttribute("toc-data"))
2426e3b55780SDimitry Andric       SMC = XCOFF::XMC_TD;
2427e3b55780SDimitry Andric 
2428cfca06d7SDimitry Andric   // Externals go into a csect of type ER.
2429cfca06d7SDimitry Andric   return getContext().getXCOFFSection(
2430344a3780SDimitry Andric       Name, SectionKind::getMetadata(),
2431344a3780SDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
2432cfca06d7SDimitry Andric }
2433cfca06d7SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const24341d5ae102SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
24351d5ae102SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2436344a3780SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2437344a3780SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2438344a3780SDimitry Andric     if (GVar->hasAttribute("toc-data")) {
24391d5ae102SDimitry Andric       SmallString<128> Name;
24401d5ae102SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2441ac9a064cSDimitry Andric       XCOFF::SymbolType symType =
2442ac9a064cSDimitry Andric           GO->hasCommonLinkage() ? XCOFF::XTY_CM : XCOFF::XTY_SD;
24431d5ae102SDimitry Andric       return getContext().getXCOFFSection(
2444ac9a064cSDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2445344a3780SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2446344a3780SDimitry Andric     }
2447344a3780SDimitry Andric 
2448344a3780SDimitry Andric   // Common symbols go into a csect with matching name which will get mapped
2449344a3780SDimitry Andric   // into the .bss section.
2450344a3780SDimitry Andric   // Zero-initialized local TLS symbols go into a csect with matching name which
2451344a3780SDimitry Andric   // will get mapped into the .tbss section.
2452344a3780SDimitry Andric   if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2453344a3780SDimitry Andric     SmallString<128> Name;
2454344a3780SDimitry Andric     getNameWithPrefix(Name, GO, TM);
2455344a3780SDimitry Andric     XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2456344a3780SDimitry Andric                                      : Kind.isCommon() ? XCOFF::XMC_RW
2457344a3780SDimitry Andric                                                        : XCOFF::XMC_UL;
2458344a3780SDimitry Andric     return getContext().getXCOFFSection(
2459344a3780SDimitry Andric         Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
24601d5ae102SDimitry Andric   }
24611d5ae102SDimitry Andric 
2462b60736ecSDimitry Andric   if (Kind.isText()) {
2463b60736ecSDimitry Andric     if (TM.getFunctionSections()) {
2464b60736ecSDimitry Andric       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2465b60736ecSDimitry Andric           ->getRepresentedCsect();
2466b60736ecSDimitry Andric     }
24671d5ae102SDimitry Andric     return TextSection;
2468b60736ecSDimitry Andric   }
24691d5ae102SDimitry Andric 
24707fa27ce4SDimitry Andric   if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
24717fa27ce4SDimitry Andric     if (!TM.getDataSections())
24727fa27ce4SDimitry Andric       report_fatal_error(
24737fa27ce4SDimitry Andric           "ReadOnlyPointers is supported only if data sections is turned on");
24747fa27ce4SDimitry Andric 
24757fa27ce4SDimitry Andric     SmallString<128> Name;
24767fa27ce4SDimitry Andric     getNameWithPrefix(Name, GO, TM);
24777fa27ce4SDimitry Andric     return getContext().getXCOFFSection(
24787fa27ce4SDimitry Andric         Name, SectionKind::getReadOnly(),
24797fa27ce4SDimitry Andric         XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
24807fa27ce4SDimitry Andric   }
24817fa27ce4SDimitry Andric 
2482b60736ecSDimitry Andric   // For BSS kind, zero initialized data must be emitted to the .data section
2483b60736ecSDimitry Andric   // because external linkage control sections that get mapped to the .bss
2484b60736ecSDimitry Andric   // section will be linked as tentative defintions, which is only appropriate
2485b60736ecSDimitry Andric   // for SectionKind::Common.
2486b60736ecSDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2487b60736ecSDimitry Andric     if (TM.getDataSections()) {
2488b60736ecSDimitry Andric       SmallString<128> Name;
2489b60736ecSDimitry Andric       getNameWithPrefix(Name, GO, TM);
2490344a3780SDimitry Andric       return getContext().getXCOFFSection(
2491344a3780SDimitry Andric           Name, SectionKind::getData(),
2492344a3780SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
2493b60736ecSDimitry Andric     }
24941d5ae102SDimitry Andric     return DataSection;
2495b60736ecSDimitry Andric   }
24961d5ae102SDimitry Andric 
2497b60736ecSDimitry Andric   if (Kind.isReadOnly()) {
2498b60736ecSDimitry Andric     if (TM.getDataSections()) {
2499b60736ecSDimitry Andric       SmallString<128> Name;
2500b60736ecSDimitry Andric       getNameWithPrefix(Name, GO, TM);
2501344a3780SDimitry Andric       return getContext().getXCOFFSection(
2502344a3780SDimitry Andric           Name, SectionKind::getReadOnly(),
2503344a3780SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2504b60736ecSDimitry Andric     }
2505706b4fc4SDimitry Andric     return ReadOnlySection;
2506b60736ecSDimitry Andric   }
2507706b4fc4SDimitry Andric 
2508344a3780SDimitry Andric   // External/weak TLS data and initialized local TLS data are not eligible
2509344a3780SDimitry Andric   // to be put into common csect. If data sections are enabled, thread
2510344a3780SDimitry Andric   // data are emitted into separate sections. Otherwise, thread data
2511344a3780SDimitry Andric   // are emitted into the .tdata section.
2512344a3780SDimitry Andric   if (Kind.isThreadLocal()) {
2513344a3780SDimitry Andric     if (TM.getDataSections()) {
2514344a3780SDimitry Andric       SmallString<128> Name;
2515344a3780SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2516344a3780SDimitry Andric       return getContext().getXCOFFSection(
2517344a3780SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
2518344a3780SDimitry Andric     }
2519344a3780SDimitry Andric     return TLSDataSection;
2520344a3780SDimitry Andric   }
2521344a3780SDimitry Andric 
25221d5ae102SDimitry Andric   report_fatal_error("XCOFF other section types not yet implemented.");
25231d5ae102SDimitry Andric }
25241d5ae102SDimitry Andric 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const2525706b4fc4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2526706b4fc4SDimitry Andric     const Function &F, const TargetMachine &TM) const {
2527706b4fc4SDimitry Andric   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2528b60736ecSDimitry Andric 
2529b60736ecSDimitry Andric   if (!TM.getFunctionSections())
2530706b4fc4SDimitry Andric     return ReadOnlySection;
2531b60736ecSDimitry Andric 
2532b60736ecSDimitry Andric   // If the function can be removed, produce a unique section so that
2533b60736ecSDimitry Andric   // the table doesn't prevent the removal.
2534b60736ecSDimitry Andric   SmallString<128> NameStr(".rodata.jmp..");
2535b60736ecSDimitry Andric   getNameWithPrefix(NameStr, &F, TM);
2536344a3780SDimitry Andric   return getContext().getXCOFFSection(
2537344a3780SDimitry Andric       NameStr, SectionKind::getReadOnly(),
2538344a3780SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2539706b4fc4SDimitry Andric }
2540706b4fc4SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const25411d5ae102SDimitry Andric bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
25421d5ae102SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2543706b4fc4SDimitry Andric   return false;
2544706b4fc4SDimitry Andric }
2545706b4fc4SDimitry Andric 
2546706b4fc4SDimitry Andric /// Given a mergeable constant with the specified size and relocation
2547706b4fc4SDimitry Andric /// information, return a section that it should be placed in.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const2548706b4fc4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2549706b4fc4SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
2550cfca06d7SDimitry Andric     Align &Alignment) const {
2551706b4fc4SDimitry Andric   // TODO: Enable emiting constant pool to unique sections when we support it.
2552c0981da4SDimitry Andric   if (Alignment > Align(16))
2553c0981da4SDimitry Andric     report_fatal_error("Alignments greater than 16 not yet supported.");
2554c0981da4SDimitry Andric 
2555c0981da4SDimitry Andric   if (Alignment == Align(8)) {
2556c0981da4SDimitry Andric     assert(ReadOnly8Section && "Section should always be initialized.");
2557c0981da4SDimitry Andric     return ReadOnly8Section;
2558c0981da4SDimitry Andric   }
2559c0981da4SDimitry Andric 
2560c0981da4SDimitry Andric   if (Alignment == Align(16)) {
2561c0981da4SDimitry Andric     assert(ReadOnly16Section && "Section should always be initialized.");
2562c0981da4SDimitry Andric     return ReadOnly16Section;
2563c0981da4SDimitry Andric   }
2564c0981da4SDimitry Andric 
2565706b4fc4SDimitry Andric   return ReadOnlySection;
25661d5ae102SDimitry Andric }
25671d5ae102SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TgtM)25681d5ae102SDimitry Andric void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
25691d5ae102SDimitry Andric                                                const TargetMachine &TgtM) {
25701d5ae102SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2571b60736ecSDimitry Andric   TTypeEncoding =
2572b60736ecSDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2573b60736ecSDimitry Andric       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2574b60736ecSDimitry Andric                                             : dwarf::DW_EH_PE_sdata8);
25751d5ae102SDimitry Andric   PersonalityEncoding = 0;
25761d5ae102SDimitry Andric   LSDAEncoding = 0;
2577b60736ecSDimitry Andric   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
2578e3b55780SDimitry Andric 
2579e3b55780SDimitry Andric   // AIX debug for thread local location is not ready. And for integrated as
2580e3b55780SDimitry Andric   // mode, the relocatable address for the thread local variable will cause
2581e3b55780SDimitry Andric   // linker error. So disable the location attribute generation for thread local
2582e3b55780SDimitry Andric   // variables for now.
2583e3b55780SDimitry Andric   // FIXME: when TLS debug on AIX is ready, remove this setting.
2584e3b55780SDimitry Andric   SupportDebugThreadLocalLocation = false;
25851d5ae102SDimitry Andric }
25861d5ae102SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const25871d5ae102SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
25881d5ae102SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2589b60736ecSDimitry Andric   report_fatal_error("no static constructor section on AIX");
25901d5ae102SDimitry Andric }
25911d5ae102SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const25921d5ae102SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
25931d5ae102SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2594b60736ecSDimitry Andric   report_fatal_error("no static destructor section on AIX");
25951d5ae102SDimitry Andric }
25961d5ae102SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const25971d5ae102SDimitry Andric const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
25981d5ae102SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
25991d5ae102SDimitry Andric     const TargetMachine &TM) const {
2600c0981da4SDimitry Andric   /* Not implemented yet, but don't crash, return nullptr. */
2601c0981da4SDimitry Andric   return nullptr;
26021d5ae102SDimitry Andric }
26031d5ae102SDimitry Andric 
2604b60736ecSDimitry Andric XCOFF::StorageClass
getStorageClassForGlobal(const GlobalValue * GV)2605b60736ecSDimitry Andric TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2606b60736ecSDimitry Andric   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2607b60736ecSDimitry Andric 
2608b60736ecSDimitry Andric   switch (GV->getLinkage()) {
26091d5ae102SDimitry Andric   case GlobalValue::InternalLinkage:
2610706b4fc4SDimitry Andric   case GlobalValue::PrivateLinkage:
26111d5ae102SDimitry Andric     return XCOFF::C_HIDEXT;
26121d5ae102SDimitry Andric   case GlobalValue::ExternalLinkage:
26131d5ae102SDimitry Andric   case GlobalValue::CommonLinkage:
2614cfca06d7SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
26151d5ae102SDimitry Andric     return XCOFF::C_EXT;
26161d5ae102SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
2617cfca06d7SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
2618cfca06d7SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
2619cfca06d7SDimitry Andric   case GlobalValue::WeakAnyLinkage:
2620cfca06d7SDimitry Andric   case GlobalValue::WeakODRLinkage:
26211d5ae102SDimitry Andric     return XCOFF::C_WEAKEXT;
2622cfca06d7SDimitry Andric   case GlobalValue::AppendingLinkage:
26231d5ae102SDimitry Andric     report_fatal_error(
2624cfca06d7SDimitry Andric         "There is no mapping that implements AppendingLinkage for XCOFF.");
26251d5ae102SDimitry Andric   }
2626cfca06d7SDimitry Andric   llvm_unreachable("Unknown linkage type!");
2627cfca06d7SDimitry Andric }
2628cfca06d7SDimitry Andric 
getFunctionEntryPointSymbol(const GlobalValue * Func,const TargetMachine & TM) const2629cfca06d7SDimitry Andric MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2630b60736ecSDimitry Andric     const GlobalValue *Func, const TargetMachine &TM) const {
2631c0981da4SDimitry Andric   assert((isa<Function>(Func) ||
2632b60736ecSDimitry Andric           (isa<GlobalAlias>(Func) &&
2633c0981da4SDimitry Andric            isa_and_nonnull<Function>(
2634c0981da4SDimitry Andric                cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2635b60736ecSDimitry Andric          "Func must be a function or an alias which has a function as base "
2636b60736ecSDimitry Andric          "object.");
2637b60736ecSDimitry Andric 
2638cfca06d7SDimitry Andric   SmallString<128> NameStr;
2639cfca06d7SDimitry Andric   NameStr.push_back('.');
2640b60736ecSDimitry Andric   getNameWithPrefix(NameStr, Func, TM);
2641b60736ecSDimitry Andric 
2642b60736ecSDimitry Andric   // When -function-sections is enabled and explicit section is not specified,
2643b60736ecSDimitry Andric   // it's not necessary to emit function entry point label any more. We will use
2644b60736ecSDimitry Andric   // function entry point csect instead. And for function delcarations, the
2645b60736ecSDimitry Andric   // undefined symbols gets treated as csect with XTY_ER property.
2646b60736ecSDimitry Andric   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2647b1c73532SDimitry Andric        Func->isDeclarationForLinker()) &&
2648b60736ecSDimitry Andric       isa<Function>(Func)) {
2649b60736ecSDimitry Andric     return getContext()
2650344a3780SDimitry Andric         .getXCOFFSection(
2651344a3780SDimitry Andric             NameStr, SectionKind::getText(),
2652b1c73532SDimitry Andric             XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2653344a3780SDimitry Andric                                                       ? XCOFF::XTY_ER
2654344a3780SDimitry Andric                                                       : XCOFF::XTY_SD))
2655b60736ecSDimitry Andric         ->getQualNameSymbol();
2656b60736ecSDimitry Andric   }
2657b60736ecSDimitry Andric 
2658cfca06d7SDimitry Andric   return getContext().getOrCreateSymbol(NameStr);
2659cfca06d7SDimitry Andric }
2660cfca06d7SDimitry Andric 
getSectionForFunctionDescriptor(const Function * F,const TargetMachine & TM) const2661cfca06d7SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
2662cfca06d7SDimitry Andric     const Function *F, const TargetMachine &TM) const {
2663cfca06d7SDimitry Andric   SmallString<128> NameStr;
2664cfca06d7SDimitry Andric   getNameWithPrefix(NameStr, F, TM);
2665344a3780SDimitry Andric   return getContext().getXCOFFSection(
2666344a3780SDimitry Andric       NameStr, SectionKind::getData(),
2667344a3780SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
2668cfca06d7SDimitry Andric }
2669cfca06d7SDimitry Andric 
getSectionForTOCEntry(const MCSymbol * Sym,const TargetMachine & TM) const2670cfca06d7SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2671b60736ecSDimitry Andric     const MCSymbol *Sym, const TargetMachine &TM) const {
2672ac9a064cSDimitry Andric   const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2673ac9a064cSDimitry Andric                                             const TargetMachine &TM) {
2674ac9a064cSDimitry Andric     const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(Sym);
2675ac9a064cSDimitry Andric 
2676ac9a064cSDimitry Andric     // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2677ac9a064cSDimitry Andric     // otherwise the AIX assembler will complain.
2678ac9a064cSDimitry Andric     if (XSym->getSymbolTableName() == "_$TLSML")
2679ac9a064cSDimitry Andric       return XCOFF::XMC_TC;
2680ac9a064cSDimitry Andric 
2681ac9a064cSDimitry Andric     // Use large code model toc entries for ehinfo symbols as they are
2682ac9a064cSDimitry Andric     // never referenced directly. The runtime loads their TOC entry
2683ac9a064cSDimitry Andric     // addresses from the trace-back table.
2684ac9a064cSDimitry Andric     if (XSym->isEHInfo())
2685ac9a064cSDimitry Andric       return XCOFF::XMC_TE;
2686ac9a064cSDimitry Andric 
2687ac9a064cSDimitry Andric     // If the symbol does not have a code model specified use the module value.
2688ac9a064cSDimitry Andric     if (!XSym->hasPerSymbolCodeModel())
2689ac9a064cSDimitry Andric       return TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE
2690ac9a064cSDimitry Andric                                                    : XCOFF::XMC_TC;
2691ac9a064cSDimitry Andric 
2692ac9a064cSDimitry Andric     return XSym->getPerSymbolCodeModel() == MCSymbolXCOFF::CM_Large
2693ac9a064cSDimitry Andric                ? XCOFF::XMC_TE
2694ac9a064cSDimitry Andric                : XCOFF::XMC_TC;
2695ac9a064cSDimitry Andric   }(Sym, TM);
2696ac9a064cSDimitry Andric 
2697cfca06d7SDimitry Andric   return getContext().getXCOFFSection(
2698344a3780SDimitry Andric       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2699ac9a064cSDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_SD));
2700344a3780SDimitry Andric }
2701344a3780SDimitry Andric 
getSectionForLSDA(const Function & F,const MCSymbol & FnSym,const TargetMachine & TM) const2702145449b1SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForLSDA(
2703145449b1SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2704145449b1SDimitry Andric   auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
2705145449b1SDimitry Andric   if (TM.getFunctionSections()) {
2706145449b1SDimitry Andric     // If option -ffunction-sections is on, append the function name to the
2707145449b1SDimitry Andric     // name of the LSDA csect so that each function has its own LSDA csect.
2708145449b1SDimitry Andric     // This helps the linker to garbage-collect EH info of unused functions.
2709145449b1SDimitry Andric     SmallString<128> NameStr = LSDA->getName();
2710145449b1SDimitry Andric     raw_svector_ostream(NameStr) << '.' << F.getName();
2711145449b1SDimitry Andric     LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2712145449b1SDimitry Andric                                         LSDA->getCsectProp());
2713145449b1SDimitry Andric   }
2714145449b1SDimitry Andric   return LSDA;
2715145449b1SDimitry Andric }
2716344a3780SDimitry Andric //===----------------------------------------------------------------------===//
2717344a3780SDimitry Andric //                                  GOFF
2718344a3780SDimitry Andric //===----------------------------------------------------------------------===//
2719145449b1SDimitry Andric TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() = default;
2720344a3780SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const2721344a3780SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
2722344a3780SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2723344a3780SDimitry Andric   return SelectSectionForGlobal(GO, Kind, TM);
2724344a3780SDimitry Andric }
2725344a3780SDimitry Andric 
getSectionForLSDA(const Function & F,const MCSymbol & FnSym,const TargetMachine & TM) const272699aabd70SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getSectionForLSDA(
272799aabd70SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
272899aabd70SDimitry Andric   std::string Name = ".gcc_exception_table." + F.getName().str();
2729ac9a064cSDimitry Andric   return getContext().getGOFFSection(Name, SectionKind::getData(), nullptr, 0);
273099aabd70SDimitry Andric }
273199aabd70SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const2732344a3780SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
2733344a3780SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2734344a3780SDimitry Andric   auto *Symbol = TM.getSymbol(GO);
2735344a3780SDimitry Andric   if (Kind.isBSS())
2736145449b1SDimitry Andric     return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
2737ac9a064cSDimitry Andric                                        nullptr, 0);
2738344a3780SDimitry Andric 
2739344a3780SDimitry Andric   return getContext().getObjectFileInfo()->getTextSection();
27401d5ae102SDimitry Andric }
2741