1*0b57cec5SDimitry Andric //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements classes used to handle lowerings specific to common
10*0b57cec5SDimitry Andric // object file formats.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
20*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
21*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
22*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
23*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/MachO.h"
24fe6060f1SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
25e8d8bef9SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
265ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
275ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
345ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
355ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
42*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
44e8d8bef9SDimitry Andric #include "llvm/IR/PseudoProbe.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
46*0b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
47*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
48*0b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
49*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionCOFF.h"
50*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionELF.h"
51fe6060f1SDimitry Andric #include "llvm/MC/MCSectionGOFF.h"
52*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionMachO.h"
53*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
548bcb0991SDimitry Andric #include "llvm/MC/MCSectionXCOFF.h"
55*0b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
56*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
57*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbolELF.h"
58*0b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
59*0b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
60*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
61*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
645ffd83dbSDimitry Andric #include "llvm/Support/Format.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
66*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
67*0b57cec5SDimitry Andric #include <cassert>
68*0b57cec5SDimitry Andric #include <string>
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric using namespace llvm;
71*0b57cec5SDimitry Andric using namespace dwarf;
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
74*0b57cec5SDimitry Andric                              StringRef &Section) {
75*0b57cec5SDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
76*0b57cec5SDimitry Andric   M.getModuleFlagsMetadata(ModuleFlags);
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric   for (const auto &MFE: ModuleFlags) {
79*0b57cec5SDimitry Andric     // Ignore flags with 'Require' behaviour.
80*0b57cec5SDimitry Andric     if (MFE.Behavior == Module::Require)
81*0b57cec5SDimitry Andric       continue;
82*0b57cec5SDimitry Andric 
83*0b57cec5SDimitry Andric     StringRef Key = MFE.Key->getString();
84*0b57cec5SDimitry Andric     if (Key == "Objective-C Image Info Version") {
85*0b57cec5SDimitry Andric       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
86*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Garbage Collection" ||
87*0b57cec5SDimitry Andric                Key == "Objective-C GC Only" ||
88*0b57cec5SDimitry Andric                Key == "Objective-C Is Simulated" ||
89*0b57cec5SDimitry Andric                Key == "Objective-C Class Properties" ||
90*0b57cec5SDimitry Andric                Key == "Objective-C Image Swift Version") {
91*0b57cec5SDimitry Andric       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
92*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Image Info Section") {
93*0b57cec5SDimitry Andric       Section = cast<MDString>(MFE.Val)->getString();
94*0b57cec5SDimitry Andric     }
955ffd83dbSDimitry Andric     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
965ffd83dbSDimitry Andric     // "Objective-C Garbage Collection".
975ffd83dbSDimitry Andric     else if (Key == "Swift ABI Version") {
985ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
995ffd83dbSDimitry Andric     } else if (Key == "Swift Major Version") {
1005ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
1015ffd83dbSDimitry Andric     } else if (Key == "Swift Minor Version") {
1025ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
1035ffd83dbSDimitry Andric     }
104*0b57cec5SDimitry Andric   }
105*0b57cec5SDimitry Andric }
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
108*0b57cec5SDimitry Andric //                                  ELF
109*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
110*0b57cec5SDimitry Andric 
111e8d8bef9SDimitry Andric TargetLoweringObjectFileELF::TargetLoweringObjectFileELF()
112e8d8bef9SDimitry Andric     : TargetLoweringObjectFile() {
113e8d8bef9SDimitry Andric   SupportDSOLocalEquivalentLowering = true;
114e8d8bef9SDimitry Andric }
115e8d8bef9SDimitry Andric 
116*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
117*0b57cec5SDimitry Andric                                              const TargetMachine &TgtM) {
118*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
119*0b57cec5SDimitry Andric 
120*0b57cec5SDimitry Andric   CodeModel::Model CM = TgtM.getCodeModel();
1215ffd83dbSDimitry Andric   InitializeELF(TgtM.Options.UseInitArray);
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric   switch (TgtM.getTargetTriple().getArch()) {
124*0b57cec5SDimitry Andric   case Triple::arm:
125*0b57cec5SDimitry Andric   case Triple::armeb:
126*0b57cec5SDimitry Andric   case Triple::thumb:
127*0b57cec5SDimitry Andric   case Triple::thumbeb:
128*0b57cec5SDimitry Andric     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
129*0b57cec5SDimitry Andric       break;
130*0b57cec5SDimitry Andric     // Fallthrough if not using EHABI
131*0b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
132*0b57cec5SDimitry Andric   case Triple::ppc:
133e8d8bef9SDimitry Andric   case Triple::ppcle:
134*0b57cec5SDimitry Andric   case Triple::x86:
135*0b57cec5SDimitry Andric     PersonalityEncoding = isPositionIndependent()
136*0b57cec5SDimitry Andric                               ? dwarf::DW_EH_PE_indirect |
137*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_pcrel |
138*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_sdata4
139*0b57cec5SDimitry Andric                               : dwarf::DW_EH_PE_absptr;
140*0b57cec5SDimitry Andric     LSDAEncoding = isPositionIndependent()
141*0b57cec5SDimitry Andric                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
142*0b57cec5SDimitry Andric                        : dwarf::DW_EH_PE_absptr;
143*0b57cec5SDimitry Andric     TTypeEncoding = isPositionIndependent()
144*0b57cec5SDimitry Andric                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
145*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata4
146*0b57cec5SDimitry Andric                         : dwarf::DW_EH_PE_absptr;
147*0b57cec5SDimitry Andric     break;
148*0b57cec5SDimitry Andric   case Triple::x86_64:
149*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
150*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
151*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
152*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
153*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
154*0b57cec5SDimitry Andric         (CM == CodeModel::Small
155*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
156*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
157*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
158fe6060f1SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
159*0b57cec5SDimitry Andric     } else {
160*0b57cec5SDimitry Andric       PersonalityEncoding =
161*0b57cec5SDimitry Andric         (CM == CodeModel::Small || CM == CodeModel::Medium)
162*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
163*0b57cec5SDimitry Andric       LSDAEncoding = (CM == CodeModel::Small)
164*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
165*0b57cec5SDimitry Andric       TTypeEncoding = (CM == CodeModel::Small)
166*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
167*0b57cec5SDimitry Andric     }
168*0b57cec5SDimitry Andric     break;
169*0b57cec5SDimitry Andric   case Triple::hexagon:
170*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
171*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
172*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
173*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
174*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
175*0b57cec5SDimitry Andric       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
176*0b57cec5SDimitry Andric       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
177*0b57cec5SDimitry Andric     }
178*0b57cec5SDimitry Andric     break;
179*0b57cec5SDimitry Andric   case Triple::aarch64:
180*0b57cec5SDimitry Andric   case Triple::aarch64_be:
1818bcb0991SDimitry Andric   case Triple::aarch64_32:
182*0b57cec5SDimitry Andric     // The small model guarantees static code/data size < 4GB, but not where it
183*0b57cec5SDimitry Andric     // will be in memory. Most of these could end up >2GB away so even a signed
184*0b57cec5SDimitry Andric     // pc-relative 32-bit address is insufficient, theoretically.
185*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
186e8d8bef9SDimitry Andric       // ILP32 uses sdata4 instead of sdata8
187e8d8bef9SDimitry Andric       if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
188e8d8bef9SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
189e8d8bef9SDimitry Andric                               dwarf::DW_EH_PE_sdata4;
190e8d8bef9SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
191e8d8bef9SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
192e8d8bef9SDimitry Andric                         dwarf::DW_EH_PE_sdata4;
193e8d8bef9SDimitry Andric       } else {
194*0b57cec5SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
195*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata8;
196*0b57cec5SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
197*0b57cec5SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
198*0b57cec5SDimitry Andric                         dwarf::DW_EH_PE_sdata8;
199e8d8bef9SDimitry Andric       }
200*0b57cec5SDimitry Andric     } else {
201*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
202*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
203*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
204*0b57cec5SDimitry Andric     }
205*0b57cec5SDimitry Andric     break;
206*0b57cec5SDimitry Andric   case Triple::lanai:
207*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
208*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
209*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
210*0b57cec5SDimitry Andric     break;
211*0b57cec5SDimitry Andric   case Triple::mips:
212*0b57cec5SDimitry Andric   case Triple::mipsel:
213*0b57cec5SDimitry Andric   case Triple::mips64:
214*0b57cec5SDimitry Andric   case Triple::mips64el:
215*0b57cec5SDimitry Andric     // MIPS uses indirect pointer to refer personality functions and types, so
216*0b57cec5SDimitry Andric     // that the eh_frame section can be read-only. DW.ref.personality will be
217*0b57cec5SDimitry Andric     // generated for relocation.
218*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
219*0b57cec5SDimitry Andric     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
220*0b57cec5SDimitry Andric     //        identify N64 from just a triple.
221*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
222*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
223*0b57cec5SDimitry Andric     // We don't support PC-relative LSDA references in GAS so we use the default
224*0b57cec5SDimitry Andric     // DW_EH_PE_absptr for those.
225*0b57cec5SDimitry Andric 
226*0b57cec5SDimitry Andric     // FreeBSD must be explicit about the data size and using pcrel since it's
227*0b57cec5SDimitry Andric     // assembler/linker won't do the automatic conversion that the Linux tools
228*0b57cec5SDimitry Andric     // do.
229*0b57cec5SDimitry Andric     if (TgtM.getTargetTriple().isOSFreeBSD()) {
230*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
231*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
232*0b57cec5SDimitry Andric     }
233*0b57cec5SDimitry Andric     break;
234*0b57cec5SDimitry Andric   case Triple::ppc64:
235*0b57cec5SDimitry Andric   case Triple::ppc64le:
236*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
237*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
238*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
239*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
240*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
241*0b57cec5SDimitry Andric     break;
242*0b57cec5SDimitry Andric   case Triple::sparcel:
243*0b57cec5SDimitry Andric   case Triple::sparc:
244*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
245*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
246*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
247*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
248*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
249*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
250*0b57cec5SDimitry Andric     } else {
251*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
252*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
253*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
254*0b57cec5SDimitry Andric     }
255*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
256*0b57cec5SDimitry Andric     break;
257*0b57cec5SDimitry Andric   case Triple::riscv32:
258*0b57cec5SDimitry Andric   case Triple::riscv64:
259*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
260*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
261*0b57cec5SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
262*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
263*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
264*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
265*0b57cec5SDimitry Andric     break;
266*0b57cec5SDimitry Andric   case Triple::sparcv9:
267*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
268*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
269*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
270*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
271*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
272*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
273*0b57cec5SDimitry Andric     } else {
274*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
275*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
276*0b57cec5SDimitry Andric     }
277*0b57cec5SDimitry Andric     break;
278*0b57cec5SDimitry Andric   case Triple::systemz:
279*0b57cec5SDimitry Andric     // All currently-defined code models guarantee that 4-byte PC-relative
280*0b57cec5SDimitry Andric     // values will be in range.
281*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
282*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
283*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
284*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
285*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
286*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
287*0b57cec5SDimitry Andric     } else {
288*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
289*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
290*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
291*0b57cec5SDimitry Andric     }
292*0b57cec5SDimitry Andric     break;
293*0b57cec5SDimitry Andric   default:
294*0b57cec5SDimitry Andric     break;
295*0b57cec5SDimitry Andric   }
296*0b57cec5SDimitry Andric }
297*0b57cec5SDimitry Andric 
298fe6060f1SDimitry Andric void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
299fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
300fe6060f1SDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
301fe6060f1SDimitry Andric   for (GlobalValue *GV : Vec)
302fe6060f1SDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
303fe6060f1SDimitry Andric       Used.insert(GO);
304fe6060f1SDimitry Andric }
305fe6060f1SDimitry Andric 
306*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
307*0b57cec5SDimitry Andric                                                      Module &M) const {
308*0b57cec5SDimitry Andric   auto &C = getContext();
309*0b57cec5SDimitry Andric 
310*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
311*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
312*0b57cec5SDimitry Andric                               ELF::SHF_EXCLUDE);
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
315*0b57cec5SDimitry Andric 
316480093f4SDimitry Andric     for (const auto *Operand : LinkerOptions->operands()) {
317*0b57cec5SDimitry Andric       if (cast<MDNode>(Operand)->getNumOperands() != 2)
318*0b57cec5SDimitry Andric         report_fatal_error("invalid llvm.linker.options");
319*0b57cec5SDimitry Andric       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
3205ffd83dbSDimitry Andric         Streamer.emitBytes(cast<MDString>(Option)->getString());
3215ffd83dbSDimitry Andric         Streamer.emitInt8(0);
322*0b57cec5SDimitry Andric       }
323*0b57cec5SDimitry Andric     }
324*0b57cec5SDimitry Andric   }
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
327*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
328fe6060f1SDimitry Andric                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
329*0b57cec5SDimitry Andric 
330*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
331*0b57cec5SDimitry Andric 
332480093f4SDimitry Andric     for (const auto *Operand : DependentLibraries->operands()) {
3335ffd83dbSDimitry Andric       Streamer.emitBytes(
334*0b57cec5SDimitry Andric           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
3355ffd83dbSDimitry Andric       Streamer.emitInt8(0);
336*0b57cec5SDimitry Andric     }
337*0b57cec5SDimitry Andric   }
338*0b57cec5SDimitry Andric 
339e8d8bef9SDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
340e8d8bef9SDimitry Andric     // Emit a descriptor for every function including functions that have an
341e8d8bef9SDimitry Andric     // available external linkage. We may not want this for imported functions
342e8d8bef9SDimitry Andric     // that has code in another thinLTO module but we don't have a good way to
343e8d8bef9SDimitry Andric     // tell them apart from inline functions defined in header files. Therefore
344e8d8bef9SDimitry Andric     // we put each descriptor in a separate comdat section and rely on the
345e8d8bef9SDimitry Andric     // linker to deduplicate.
346e8d8bef9SDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
347e8d8bef9SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
348e8d8bef9SDimitry Andric       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
349e8d8bef9SDimitry Andric       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
350e8d8bef9SDimitry Andric       auto *Name = cast<MDString>(MD->getOperand(2));
351e8d8bef9SDimitry Andric       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
352e8d8bef9SDimitry Andric           TM->getFunctionSections() ? Name->getString() : StringRef());
353e8d8bef9SDimitry Andric 
354e8d8bef9SDimitry Andric       Streamer.SwitchSection(S);
355e8d8bef9SDimitry Andric       Streamer.emitInt64(GUID->getZExtValue());
356e8d8bef9SDimitry Andric       Streamer.emitInt64(Hash->getZExtValue());
357e8d8bef9SDimitry Andric       Streamer.emitULEB128IntValue(Name->getString().size());
358e8d8bef9SDimitry Andric       Streamer.emitBytes(Name->getString());
359e8d8bef9SDimitry Andric     }
360e8d8bef9SDimitry Andric   }
361e8d8bef9SDimitry Andric 
362*0b57cec5SDimitry Andric   unsigned Version = 0;
363*0b57cec5SDimitry Andric   unsigned Flags = 0;
364*0b57cec5SDimitry Andric   StringRef Section;
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
367*0b57cec5SDimitry Andric   if (!Section.empty()) {
368*0b57cec5SDimitry Andric     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
369*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
3705ffd83dbSDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
3715ffd83dbSDimitry Andric     Streamer.emitInt32(Version);
3725ffd83dbSDimitry Andric     Streamer.emitInt32(Flags);
373*0b57cec5SDimitry Andric     Streamer.AddBlankLine();
374*0b57cec5SDimitry Andric   }
375*0b57cec5SDimitry Andric 
376e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
377*0b57cec5SDimitry Andric }
378*0b57cec5SDimitry Andric 
379*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
380*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
381*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
382*0b57cec5SDimitry Andric   unsigned Encoding = getPersonalityEncoding();
383*0b57cec5SDimitry Andric   if ((Encoding & 0x80) == DW_EH_PE_indirect)
384*0b57cec5SDimitry Andric     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
385*0b57cec5SDimitry Andric                                           TM.getSymbol(GV)->getName());
386*0b57cec5SDimitry Andric   if ((Encoding & 0x70) == DW_EH_PE_absptr)
387*0b57cec5SDimitry Andric     return TM.getSymbol(GV);
388*0b57cec5SDimitry Andric   report_fatal_error("We do not support this DWARF encoding yet!");
389*0b57cec5SDimitry Andric }
390*0b57cec5SDimitry Andric 
391*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitPersonalityValue(
392*0b57cec5SDimitry Andric     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
393*0b57cec5SDimitry Andric   SmallString<64> NameData("DW.ref.");
394*0b57cec5SDimitry Andric   NameData += Sym->getName();
395*0b57cec5SDimitry Andric   MCSymbolELF *Label =
396*0b57cec5SDimitry Andric       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
3975ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
3985ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
399*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
400*0b57cec5SDimitry Andric   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
401*0b57cec5SDimitry Andric                                                    ELF::SHT_PROGBITS, Flags, 0);
402*0b57cec5SDimitry Andric   unsigned Size = DL.getPointerSize();
403*0b57cec5SDimitry Andric   Streamer.SwitchSection(Sec);
4045ffd83dbSDimitry Andric   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
4055ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
406*0b57cec5SDimitry Andric   const MCExpr *E = MCConstantExpr::create(Size, getContext());
407*0b57cec5SDimitry Andric   Streamer.emitELFSize(Label, E);
4085ffd83dbSDimitry Andric   Streamer.emitLabel(Label);
409*0b57cec5SDimitry Andric 
4105ffd83dbSDimitry Andric   Streamer.emitSymbolValue(Sym, Size);
411*0b57cec5SDimitry Andric }
412*0b57cec5SDimitry Andric 
413*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
414*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
415*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
416*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
417*0b57cec5SDimitry Andric     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
420*0b57cec5SDimitry Andric 
421*0b57cec5SDimitry Andric     // Add information about the stub reference to ELFMMI so that the stub
422*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
423*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
424*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
425*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
426*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
427*0b57cec5SDimitry Andric     }
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
430*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
431*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
432*0b57cec5SDimitry Andric   }
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
435*0b57cec5SDimitry Andric                                                            MMI, Streamer);
436*0b57cec5SDimitry Andric }
437*0b57cec5SDimitry Andric 
438*0b57cec5SDimitry Andric static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
439*0b57cec5SDimitry Andric   // N.B.: The defaults used in here are not the same ones used in MC.
440*0b57cec5SDimitry Andric   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
441*0b57cec5SDimitry Andric   // both gas and MC will produce a section with no flags. Given
442*0b57cec5SDimitry Andric   // section(".eh_frame") gcc will produce:
443*0b57cec5SDimitry Andric   //
444*0b57cec5SDimitry Andric   //   .section   .eh_frame,"a",@progbits
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
4475ffd83dbSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
4485ffd83dbSDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
449e8d8bef9SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
450e8d8bef9SDimitry Andric       Name == ".llvmbc" || Name == ".llvmcmd")
451*0b57cec5SDimitry Andric     return SectionKind::getMetadata();
452*0b57cec5SDimitry Andric 
453*0b57cec5SDimitry Andric   if (Name.empty() || Name[0] != '.') return K;
454*0b57cec5SDimitry Andric 
455*0b57cec5SDimitry Andric   // Default implementation based on some magic section names.
456*0b57cec5SDimitry Andric   if (Name == ".bss" ||
457*0b57cec5SDimitry Andric       Name.startswith(".bss.") ||
458*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.b.") ||
459*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.b.") ||
460*0b57cec5SDimitry Andric       Name == ".sbss" ||
461*0b57cec5SDimitry Andric       Name.startswith(".sbss.") ||
462*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.sb.") ||
463*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.sb."))
464*0b57cec5SDimitry Andric     return SectionKind::getBSS();
465*0b57cec5SDimitry Andric 
466*0b57cec5SDimitry Andric   if (Name == ".tdata" ||
467*0b57cec5SDimitry Andric       Name.startswith(".tdata.") ||
468*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.td.") ||
469*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.td."))
470*0b57cec5SDimitry Andric     return SectionKind::getThreadData();
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   if (Name == ".tbss" ||
473*0b57cec5SDimitry Andric       Name.startswith(".tbss.") ||
474*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.tb.") ||
475*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.tb."))
476*0b57cec5SDimitry Andric     return SectionKind::getThreadBSS();
477*0b57cec5SDimitry Andric 
478*0b57cec5SDimitry Andric   return K;
479*0b57cec5SDimitry Andric }
480*0b57cec5SDimitry Andric 
481*0b57cec5SDimitry Andric static unsigned getELFSectionType(StringRef Name, SectionKind K) {
482*0b57cec5SDimitry Andric   // Use SHT_NOTE for section whose name starts with ".note" to allow
483*0b57cec5SDimitry Andric   // emitting ELF notes from C variable declaration.
484*0b57cec5SDimitry Andric   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
485*0b57cec5SDimitry Andric   if (Name.startswith(".note"))
486*0b57cec5SDimitry Andric     return ELF::SHT_NOTE;
487*0b57cec5SDimitry Andric 
488*0b57cec5SDimitry Andric   if (Name == ".init_array")
489*0b57cec5SDimitry Andric     return ELF::SHT_INIT_ARRAY;
490*0b57cec5SDimitry Andric 
491*0b57cec5SDimitry Andric   if (Name == ".fini_array")
492*0b57cec5SDimitry Andric     return ELF::SHT_FINI_ARRAY;
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric   if (Name == ".preinit_array")
495*0b57cec5SDimitry Andric     return ELF::SHT_PREINIT_ARRAY;
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric   if (K.isBSS() || K.isThreadBSS())
498*0b57cec5SDimitry Andric     return ELF::SHT_NOBITS;
499*0b57cec5SDimitry Andric 
500*0b57cec5SDimitry Andric   return ELF::SHT_PROGBITS;
501*0b57cec5SDimitry Andric }
502*0b57cec5SDimitry Andric 
503*0b57cec5SDimitry Andric static unsigned getELFSectionFlags(SectionKind K) {
504*0b57cec5SDimitry Andric   unsigned Flags = 0;
505*0b57cec5SDimitry Andric 
506*0b57cec5SDimitry Andric   if (!K.isMetadata())
507*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ALLOC;
508*0b57cec5SDimitry Andric 
509*0b57cec5SDimitry Andric   if (K.isText())
510*0b57cec5SDimitry Andric     Flags |= ELF::SHF_EXECINSTR;
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric   if (K.isExecuteOnly())
513*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ARM_PURECODE;
514*0b57cec5SDimitry Andric 
515*0b57cec5SDimitry Andric   if (K.isWriteable())
516*0b57cec5SDimitry Andric     Flags |= ELF::SHF_WRITE;
517*0b57cec5SDimitry Andric 
518*0b57cec5SDimitry Andric   if (K.isThreadLocal())
519*0b57cec5SDimitry Andric     Flags |= ELF::SHF_TLS;
520*0b57cec5SDimitry Andric 
521*0b57cec5SDimitry Andric   if (K.isMergeableCString() || K.isMergeableConst())
522*0b57cec5SDimitry Andric     Flags |= ELF::SHF_MERGE;
523*0b57cec5SDimitry Andric 
524*0b57cec5SDimitry Andric   if (K.isMergeableCString())
525*0b57cec5SDimitry Andric     Flags |= ELF::SHF_STRINGS;
526*0b57cec5SDimitry Andric 
527*0b57cec5SDimitry Andric   return Flags;
528*0b57cec5SDimitry Andric }
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric static const Comdat *getELFComdat(const GlobalValue *GV) {
531*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
532*0b57cec5SDimitry Andric   if (!C)
533*0b57cec5SDimitry Andric     return nullptr;
534*0b57cec5SDimitry Andric 
535fe6060f1SDimitry Andric   if (C->getSelectionKind() != Comdat::Any &&
536fe6060f1SDimitry Andric       C->getSelectionKind() != Comdat::NoDeduplicate)
537fe6060f1SDimitry Andric     report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
538fe6060f1SDimitry Andric                        "SelectionKind::NoDeduplicate, '" +
539*0b57cec5SDimitry Andric                        C->getName() + "' cannot be lowered.");
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric   return C;
542*0b57cec5SDimitry Andric }
543*0b57cec5SDimitry Andric 
5445ffd83dbSDimitry Andric static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
545*0b57cec5SDimitry Andric                                             const TargetMachine &TM) {
546*0b57cec5SDimitry Andric   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
547*0b57cec5SDimitry Andric   if (!MD)
548*0b57cec5SDimitry Andric     return nullptr;
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric   const MDOperand &Op = MD->getOperand(0);
551*0b57cec5SDimitry Andric   if (!Op.get())
552*0b57cec5SDimitry Andric     return nullptr;
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric   auto *VM = dyn_cast<ValueAsMetadata>(Op);
555*0b57cec5SDimitry Andric   if (!VM)
556*0b57cec5SDimitry Andric     report_fatal_error("MD_associated operand is not ValueAsMetadata");
557*0b57cec5SDimitry Andric 
5588bcb0991SDimitry Andric   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
5598bcb0991SDimitry Andric   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
560*0b57cec5SDimitry Andric }
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric static unsigned getEntrySizeForKind(SectionKind Kind) {
563*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString())
564*0b57cec5SDimitry Andric     return 1;
565*0b57cec5SDimitry Andric   else if (Kind.isMergeable2ByteCString())
566*0b57cec5SDimitry Andric     return 2;
567*0b57cec5SDimitry Andric   else if (Kind.isMergeable4ByteCString())
568*0b57cec5SDimitry Andric     return 4;
569*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst4())
570*0b57cec5SDimitry Andric     return 4;
571*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst8())
572*0b57cec5SDimitry Andric     return 8;
573*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst16())
574*0b57cec5SDimitry Andric     return 16;
575*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst32())
576*0b57cec5SDimitry Andric     return 32;
577*0b57cec5SDimitry Andric   else {
578*0b57cec5SDimitry Andric     // We shouldn't have mergeable C strings or mergeable constants that we
579*0b57cec5SDimitry Andric     // didn't handle above.
580*0b57cec5SDimitry Andric     assert(!Kind.isMergeableCString() && "unknown string width");
581*0b57cec5SDimitry Andric     assert(!Kind.isMergeableConst() && "unknown data width");
582*0b57cec5SDimitry Andric     return 0;
583*0b57cec5SDimitry Andric   }
584*0b57cec5SDimitry Andric }
585*0b57cec5SDimitry Andric 
5865ffd83dbSDimitry Andric /// Return the section prefix name used by options FunctionsSections and
5875ffd83dbSDimitry Andric /// DataSections.
5885ffd83dbSDimitry Andric static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
5895ffd83dbSDimitry Andric   if (Kind.isText())
5905ffd83dbSDimitry Andric     return ".text";
5915ffd83dbSDimitry Andric   if (Kind.isReadOnly())
5925ffd83dbSDimitry Andric     return ".rodata";
5935ffd83dbSDimitry Andric   if (Kind.isBSS())
5945ffd83dbSDimitry Andric     return ".bss";
5955ffd83dbSDimitry Andric   if (Kind.isThreadData())
5965ffd83dbSDimitry Andric     return ".tdata";
5975ffd83dbSDimitry Andric   if (Kind.isThreadBSS())
5985ffd83dbSDimitry Andric     return ".tbss";
5995ffd83dbSDimitry Andric   if (Kind.isData())
6005ffd83dbSDimitry Andric     return ".data";
6015ffd83dbSDimitry Andric   if (Kind.isReadOnlyWithRel())
6025ffd83dbSDimitry Andric     return ".data.rel.ro";
6035ffd83dbSDimitry Andric   llvm_unreachable("Unknown section kind");
6045ffd83dbSDimitry Andric }
6055ffd83dbSDimitry Andric 
6065ffd83dbSDimitry Andric static SmallString<128>
6075ffd83dbSDimitry Andric getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
6085ffd83dbSDimitry Andric                            Mangler &Mang, const TargetMachine &TM,
6095ffd83dbSDimitry Andric                            unsigned EntrySize, bool UniqueSectionName) {
6105ffd83dbSDimitry Andric   SmallString<128> Name;
6115ffd83dbSDimitry Andric   if (Kind.isMergeableCString()) {
6125ffd83dbSDimitry Andric     // We also need alignment here.
6135ffd83dbSDimitry Andric     // FIXME: this is getting the alignment of the character, not the
6145ffd83dbSDimitry Andric     // alignment of the global!
6155ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
6165ffd83dbSDimitry Andric         cast<GlobalVariable>(GO));
6175ffd83dbSDimitry Andric 
6185ffd83dbSDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
6195ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
6205ffd83dbSDimitry Andric   } else if (Kind.isMergeableConst()) {
6215ffd83dbSDimitry Andric     Name = ".rodata.cst";
6225ffd83dbSDimitry Andric     Name += utostr(EntrySize);
6235ffd83dbSDimitry Andric   } else {
6245ffd83dbSDimitry Andric     Name = getSectionPrefixForGlobal(Kind);
6255ffd83dbSDimitry Andric   }
6265ffd83dbSDimitry Andric 
6275ffd83dbSDimitry Andric   bool HasPrefix = false;
6285ffd83dbSDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
6295ffd83dbSDimitry Andric     if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
630e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *Prefix;
6315ffd83dbSDimitry Andric       HasPrefix = true;
6325ffd83dbSDimitry Andric     }
6335ffd83dbSDimitry Andric   }
6345ffd83dbSDimitry Andric 
6355ffd83dbSDimitry Andric   if (UniqueSectionName) {
6365ffd83dbSDimitry Andric     Name.push_back('.');
6375ffd83dbSDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
6385ffd83dbSDimitry Andric   } else if (HasPrefix)
639fe6060f1SDimitry Andric     // For distinguishing between .text.${text-section-prefix}. (with trailing
640fe6060f1SDimitry Andric     // dot) and .text.${function-name}
6415ffd83dbSDimitry Andric     Name.push_back('.');
6425ffd83dbSDimitry Andric   return Name;
6435ffd83dbSDimitry Andric }
6445ffd83dbSDimitry Andric 
6455ffd83dbSDimitry Andric namespace {
6465ffd83dbSDimitry Andric class LoweringDiagnosticInfo : public DiagnosticInfo {
6475ffd83dbSDimitry Andric   const Twine &Msg;
6485ffd83dbSDimitry Andric 
6495ffd83dbSDimitry Andric public:
6505ffd83dbSDimitry Andric   LoweringDiagnosticInfo(const Twine &DiagMsg,
6515ffd83dbSDimitry Andric                          DiagnosticSeverity Severity = DS_Error)
6525ffd83dbSDimitry Andric       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
6535ffd83dbSDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6545ffd83dbSDimitry Andric };
6555ffd83dbSDimitry Andric }
6565ffd83dbSDimitry Andric 
657fe6060f1SDimitry Andric /// Calculate an appropriate unique ID for a section, and update Flags,
658fe6060f1SDimitry Andric /// EntrySize and NextUniqueID where appropriate.
659fe6060f1SDimitry Andric static unsigned
660fe6060f1SDimitry Andric calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
661fe6060f1SDimitry Andric                                SectionKind Kind, const TargetMachine &TM,
662fe6060f1SDimitry Andric                                MCContext &Ctx, Mangler &Mang, unsigned &Flags,
663fe6060f1SDimitry Andric                                unsigned &EntrySize, unsigned &NextUniqueID,
664fe6060f1SDimitry Andric                                const bool Retain, const bool ForceUnique) {
665fe6060f1SDimitry Andric   // Increment uniqueID if we are forced to emit a unique section.
666fe6060f1SDimitry Andric   // This works perfectly fine with section attribute or pragma section as the
667fe6060f1SDimitry Andric   // sections with the same name are grouped together by the assembler.
668fe6060f1SDimitry Andric   if (ForceUnique)
669fe6060f1SDimitry Andric     return NextUniqueID++;
670fe6060f1SDimitry Andric 
671fe6060f1SDimitry Andric   // A section can have at most one associated section. Put each global with
672fe6060f1SDimitry Andric   // MD_associated in a unique section.
673fe6060f1SDimitry Andric   const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
674fe6060f1SDimitry Andric   if (Associated) {
675fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
676fe6060f1SDimitry Andric     return NextUniqueID++;
677fe6060f1SDimitry Andric   }
678fe6060f1SDimitry Andric 
679fe6060f1SDimitry Andric   if (Retain) {
6806e75b2fbSDimitry Andric     if ((Ctx.getAsmInfo()->useIntegratedAssembler() ||
6816e75b2fbSDimitry Andric          Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
6826e75b2fbSDimitry Andric         !TM.getTargetTriple().isOSSolaris())
683fe6060f1SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
684fe6060f1SDimitry Andric     return NextUniqueID++;
685fe6060f1SDimitry Andric   }
686fe6060f1SDimitry Andric 
687fe6060f1SDimitry Andric   // If two symbols with differing sizes end up in the same mergeable section
688fe6060f1SDimitry Andric   // that section can be assigned an incorrect entry size. To avoid this we
689fe6060f1SDimitry Andric   // usually put symbols of the same size into distinct mergeable sections with
690fe6060f1SDimitry Andric   // the same name. Doing so relies on the ",unique ," assembly feature. This
691fe6060f1SDimitry Andric   // feature is not avalible until bintuils version 2.35
692fe6060f1SDimitry Andric   // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
693fe6060f1SDimitry Andric   const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
694fe6060f1SDimitry Andric                               Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
695fe6060f1SDimitry Andric   if (!SupportsUnique) {
696fe6060f1SDimitry Andric     Flags &= ~ELF::SHF_MERGE;
697fe6060f1SDimitry Andric     EntrySize = 0;
698fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
699fe6060f1SDimitry Andric   }
700fe6060f1SDimitry Andric 
701fe6060f1SDimitry Andric   const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
702fe6060f1SDimitry Andric   const bool SeenSectionNameBefore =
703fe6060f1SDimitry Andric       Ctx.isELFGenericMergeableSection(SectionName);
704fe6060f1SDimitry Andric   // If this is the first ocurrence of this section name, treat it as the
705fe6060f1SDimitry Andric   // generic section
706fe6060f1SDimitry Andric   if (!SymbolMergeable && !SeenSectionNameBefore)
707fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
708fe6060f1SDimitry Andric 
709fe6060f1SDimitry Andric   // Symbols must be placed into sections with compatible entry sizes. Generate
710fe6060f1SDimitry Andric   // unique sections for symbols that have not been assigned to compatible
711fe6060f1SDimitry Andric   // sections.
712fe6060f1SDimitry Andric   const auto PreviousID =
713fe6060f1SDimitry Andric       Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
714fe6060f1SDimitry Andric   if (PreviousID)
715fe6060f1SDimitry Andric     return *PreviousID;
716fe6060f1SDimitry Andric 
717fe6060f1SDimitry Andric   // If the user has specified the same section name as would be created
718fe6060f1SDimitry Andric   // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
719fe6060f1SDimitry Andric   // to unique the section as the entry size for this symbol will be
720fe6060f1SDimitry Andric   // compatible with implicitly created sections.
721fe6060f1SDimitry Andric   SmallString<128> ImplicitSectionNameStem =
722fe6060f1SDimitry Andric       getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
723fe6060f1SDimitry Andric   if (SymbolMergeable &&
724fe6060f1SDimitry Andric       Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
725fe6060f1SDimitry Andric       SectionName.startswith(ImplicitSectionNameStem))
726fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
727fe6060f1SDimitry Andric 
728fe6060f1SDimitry Andric   // We have seen this section name before, but with different flags or entity
729fe6060f1SDimitry Andric   // size. Create a new unique ID.
730fe6060f1SDimitry Andric   return NextUniqueID++;
731fe6060f1SDimitry Andric }
732fe6060f1SDimitry Andric 
733fe6060f1SDimitry Andric static MCSection *selectExplicitSectionGlobal(
734fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
735fe6060f1SDimitry Andric     MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
736fe6060f1SDimitry Andric     bool Retain, bool ForceUnique) {
737*0b57cec5SDimitry Andric   StringRef SectionName = GO->getSection();
738*0b57cec5SDimitry Andric 
739*0b57cec5SDimitry Andric   // Check if '#pragma clang section' name is applicable.
740*0b57cec5SDimitry Andric   // Note that pragma directive overrides -ffunction-section, -fdata-section
741*0b57cec5SDimitry Andric   // and so section name is exactly as user specified and not uniqued.
742*0b57cec5SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
743*0b57cec5SDimitry Andric   if (GV && GV->hasImplicitSection()) {
744*0b57cec5SDimitry Andric     auto Attrs = GV->getAttributes();
745*0b57cec5SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
746*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
747*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
748*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
7498bcb0991SDimitry Andric     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
7508bcb0991SDimitry Andric       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
751*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
752*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
753*0b57cec5SDimitry Andric     }
754*0b57cec5SDimitry Andric   }
755*0b57cec5SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
756*0b57cec5SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
757*0b57cec5SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
758*0b57cec5SDimitry Andric   }
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric   // Infer section flags from the section name if we can.
761*0b57cec5SDimitry Andric   Kind = getELFKindForNamedSection(SectionName, Kind);
762*0b57cec5SDimitry Andric 
763*0b57cec5SDimitry Andric   StringRef Group = "";
764fe6060f1SDimitry Andric   bool IsComdat = false;
765*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
766*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
767*0b57cec5SDimitry Andric     Group = C->getName();
768fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
769*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
770*0b57cec5SDimitry Andric   }
771*0b57cec5SDimitry Andric 
7725ffd83dbSDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
773fe6060f1SDimitry Andric   const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
774fe6060f1SDimitry Andric       GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
775fe6060f1SDimitry Andric       Retain, ForceUnique);
7765ffd83dbSDimitry Andric 
7775ffd83dbSDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
778fe6060f1SDimitry Andric   MCSectionELF *Section = Ctx.getELFSection(
779fe6060f1SDimitry Andric       SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
780fe6060f1SDimitry Andric       Group, IsComdat, UniqueID, LinkedToSym);
781*0b57cec5SDimitry Andric   // Make sure that we did not get some other section with incompatible sh_link.
782*0b57cec5SDimitry Andric   // This should not be possible due to UniqueID code above.
7835ffd83dbSDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym &&
784*0b57cec5SDimitry Andric          "Associated symbol mismatch between sections");
7855ffd83dbSDimitry Andric 
786fe6060f1SDimitry Andric   if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
787fe6060f1SDimitry Andric         Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
788e8d8bef9SDimitry Andric     // If we are using GNU as before 2.35, then this symbol might have
7895ffd83dbSDimitry Andric     // been placed in an incompatible mergeable section. Emit an error if this
7905ffd83dbSDimitry Andric     // is the case to avoid creating broken output.
7915ffd83dbSDimitry Andric     if ((Section->getFlags() & ELF::SHF_MERGE) &&
7925ffd83dbSDimitry Andric         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
7935ffd83dbSDimitry Andric       GO->getContext().diagnose(LoweringDiagnosticInfo(
7945ffd83dbSDimitry Andric           "Symbol '" + GO->getName() + "' from module '" +
7955ffd83dbSDimitry Andric           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
7965ffd83dbSDimitry Andric           "' required a section with entry-size=" +
7975ffd83dbSDimitry Andric           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
7985ffd83dbSDimitry Andric           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
7995ffd83dbSDimitry Andric           ": Explicit assignment by pragma or attribute of an incompatible "
8005ffd83dbSDimitry Andric           "symbol to this section?"));
801*0b57cec5SDimitry Andric   }
802*0b57cec5SDimitry Andric 
8035ffd83dbSDimitry Andric   return Section;
804*0b57cec5SDimitry Andric }
805*0b57cec5SDimitry Andric 
806fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
807fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
808fe6060f1SDimitry Andric   return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
809fe6060f1SDimitry Andric                                      NextUniqueID, Used.count(GO),
810fe6060f1SDimitry Andric                                      /* ForceUnique = */false);
811fe6060f1SDimitry Andric }
812fe6060f1SDimitry Andric 
813*0b57cec5SDimitry Andric static MCSectionELF *selectELFSectionForGlobal(
814*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
815*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
816*0b57cec5SDimitry Andric     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
817*0b57cec5SDimitry Andric 
818*0b57cec5SDimitry Andric   StringRef Group = "";
819fe6060f1SDimitry Andric   bool IsComdat = false;
820*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
821*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
822*0b57cec5SDimitry Andric     Group = C->getName();
823fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
824*0b57cec5SDimitry Andric   }
825*0b57cec5SDimitry Andric 
826*0b57cec5SDimitry Andric   // Get the section entry size based on the kind.
827*0b57cec5SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
828*0b57cec5SDimitry Andric 
8295ffd83dbSDimitry Andric   bool UniqueSectionName = false;
830*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
831*0b57cec5SDimitry Andric   if (EmitUniqueSection) {
832*0b57cec5SDimitry Andric     if (TM.getUniqueSectionNames()) {
8335ffd83dbSDimitry Andric       UniqueSectionName = true;
834*0b57cec5SDimitry Andric     } else {
835*0b57cec5SDimitry Andric       UniqueID = *NextUniqueID;
836*0b57cec5SDimitry Andric       (*NextUniqueID)++;
837*0b57cec5SDimitry Andric     }
838*0b57cec5SDimitry Andric   }
8395ffd83dbSDimitry Andric   SmallString<128> Name = getELFSectionNameForGlobal(
8405ffd83dbSDimitry Andric       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
8415ffd83dbSDimitry Andric 
842*0b57cec5SDimitry Andric   // Use 0 as the unique ID for execute-only text.
843*0b57cec5SDimitry Andric   if (Kind.isExecuteOnly())
844*0b57cec5SDimitry Andric     UniqueID = 0;
845*0b57cec5SDimitry Andric   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
846fe6060f1SDimitry Andric                            EntrySize, Group, IsComdat, UniqueID,
847fe6060f1SDimitry Andric                            AssociatedSymbol);
848fe6060f1SDimitry Andric }
849fe6060f1SDimitry Andric 
850fe6060f1SDimitry Andric static MCSection *selectELFSectionForGlobal(
851fe6060f1SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
852fe6060f1SDimitry Andric     const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
853fe6060f1SDimitry Andric     unsigned Flags, unsigned *NextUniqueID) {
854fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
855fe6060f1SDimitry Andric   if (LinkedToSym) {
856fe6060f1SDimitry Andric     EmitUniqueSection = true;
857fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
858fe6060f1SDimitry Andric   }
8596e75b2fbSDimitry Andric   if (Retain &&
8606e75b2fbSDimitry Andric       (Ctx.getAsmInfo()->useIntegratedAssembler() ||
8616e75b2fbSDimitry Andric        Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
8626e75b2fbSDimitry Andric       !TM.getTargetTriple().isOSSolaris()) {
863fe6060f1SDimitry Andric     EmitUniqueSection = true;
864fe6060f1SDimitry Andric     Flags |= ELF::SHF_GNU_RETAIN;
865fe6060f1SDimitry Andric   }
866fe6060f1SDimitry Andric 
867fe6060f1SDimitry Andric   MCSectionELF *Section = selectELFSectionForGlobal(
868fe6060f1SDimitry Andric       Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
869fe6060f1SDimitry Andric       NextUniqueID, LinkedToSym);
870fe6060f1SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym);
871fe6060f1SDimitry Andric   return Section;
872*0b57cec5SDimitry Andric }
873*0b57cec5SDimitry Andric 
874*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
875*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
876*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
877*0b57cec5SDimitry Andric 
878*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
879*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
880*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
881*0b57cec5SDimitry Andric   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
882*0b57cec5SDimitry Andric     if (Kind.isText())
883*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getFunctionSections();
884*0b57cec5SDimitry Andric     else
885*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getDataSections();
886*0b57cec5SDimitry Andric   }
887*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
888fe6060f1SDimitry Andric   return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
889fe6060f1SDimitry Andric                                    Used.count(GO), EmitUniqueSection, Flags,
890fe6060f1SDimitry Andric                                    &NextUniqueID);
891*0b57cec5SDimitry Andric }
892*0b57cec5SDimitry Andric 
893fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
894fe6060f1SDimitry Andric     const Function &F, const TargetMachine &TM) const {
895fe6060f1SDimitry Andric   SectionKind Kind = SectionKind::getText();
896fe6060f1SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
897fe6060f1SDimitry Andric   // If the function's section names is pre-determined via pragma or a
898fe6060f1SDimitry Andric   // section attribute, call selectExplicitSectionGlobal.
899fe6060f1SDimitry Andric   if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
900fe6060f1SDimitry Andric     return selectExplicitSectionGlobal(
901fe6060f1SDimitry Andric         &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
902fe6060f1SDimitry Andric         Used.count(&F), /* ForceUnique = */true);
903fe6060f1SDimitry Andric   else
904fe6060f1SDimitry Andric     return selectELFSectionForGlobal(
905fe6060f1SDimitry Andric         getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
906fe6060f1SDimitry Andric         /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
907*0b57cec5SDimitry Andric }
908*0b57cec5SDimitry Andric 
909*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
910*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
911*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
912*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
913*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
914*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
915*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
916*0b57cec5SDimitry Andric     return ReadOnlySection;
917*0b57cec5SDimitry Andric 
918*0b57cec5SDimitry Andric   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
919*0b57cec5SDimitry Andric                                    getMangler(), TM, EmitUniqueSection,
920*0b57cec5SDimitry Andric                                    ELF::SHF_ALLOC, &NextUniqueID,
921*0b57cec5SDimitry Andric                                    /* AssociatedSymbol */ nullptr);
922*0b57cec5SDimitry Andric }
923*0b57cec5SDimitry Andric 
924fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
925fe6060f1SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
926e8d8bef9SDimitry Andric   // If neither COMDAT nor function sections, use the monolithic LSDA section.
927e8d8bef9SDimitry Andric   // Re-use this path if LSDASection is null as in the Arm EHABI.
928e8d8bef9SDimitry Andric   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
929e8d8bef9SDimitry Andric     return LSDASection;
930e8d8bef9SDimitry Andric 
931e8d8bef9SDimitry Andric   const auto *LSDA = cast<MCSectionELF>(LSDASection);
932e8d8bef9SDimitry Andric   unsigned Flags = LSDA->getFlags();
933fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = nullptr;
934e8d8bef9SDimitry Andric   StringRef Group;
935fe6060f1SDimitry Andric   bool IsComdat = false;
936fe6060f1SDimitry Andric   if (const Comdat *C = getELFComdat(&F)) {
937e8d8bef9SDimitry Andric     Flags |= ELF::SHF_GROUP;
938fe6060f1SDimitry Andric     Group = C->getName();
939fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
940fe6060f1SDimitry Andric   }
941fe6060f1SDimitry Andric   // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
942fe6060f1SDimitry Andric   // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
943fe6060f1SDimitry Andric   if (TM.getFunctionSections() &&
944fe6060f1SDimitry Andric       (getContext().getAsmInfo()->useIntegratedAssembler() &&
945fe6060f1SDimitry Andric        getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
946fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
947fe6060f1SDimitry Andric     LinkedToSym = cast<MCSymbolELF>(&FnSym);
948e8d8bef9SDimitry Andric   }
949e8d8bef9SDimitry Andric 
950e8d8bef9SDimitry Andric   // Append the function name as the suffix like GCC, assuming
951e8d8bef9SDimitry Andric   // -funique-section-names applies to .gcc_except_table sections.
952fe6060f1SDimitry Andric   return getContext().getELFSection(
953fe6060f1SDimitry Andric       (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
954fe6060f1SDimitry Andric                                   : LSDA->getName()),
955fe6060f1SDimitry Andric       LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
956fe6060f1SDimitry Andric       LinkedToSym);
957e8d8bef9SDimitry Andric }
958e8d8bef9SDimitry Andric 
959*0b57cec5SDimitry Andric bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
960*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
961*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
962*0b57cec5SDimitry Andric   // that can be marked non-executable.
963*0b57cec5SDimitry Andric   return false;
964*0b57cec5SDimitry Andric }
965*0b57cec5SDimitry Andric 
966*0b57cec5SDimitry Andric /// Given a mergeable constant with the specified size and relocation
967*0b57cec5SDimitry Andric /// information, return a section that it should be placed in.
968*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
969*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
9705ffd83dbSDimitry Andric     Align &Alignment) const {
971*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4() && MergeableConst4Section)
972*0b57cec5SDimitry Andric     return MergeableConst4Section;
973*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8() && MergeableConst8Section)
974*0b57cec5SDimitry Andric     return MergeableConst8Section;
975*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16() && MergeableConst16Section)
976*0b57cec5SDimitry Andric     return MergeableConst16Section;
977*0b57cec5SDimitry Andric   if (Kind.isMergeableConst32() && MergeableConst32Section)
978*0b57cec5SDimitry Andric     return MergeableConst32Section;
979*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
980*0b57cec5SDimitry Andric     return ReadOnlySection;
981*0b57cec5SDimitry Andric 
982*0b57cec5SDimitry Andric   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
983*0b57cec5SDimitry Andric   return DataRelROSection;
984*0b57cec5SDimitry Andric }
985*0b57cec5SDimitry Andric 
9865ffd83dbSDimitry Andric /// Returns a unique section for the given machine basic block.
9875ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
9885ffd83dbSDimitry Andric     const Function &F, const MachineBasicBlock &MBB,
9895ffd83dbSDimitry Andric     const TargetMachine &TM) const {
9905ffd83dbSDimitry Andric   assert(MBB.isBeginSection() && "Basic block does not start a section!");
9915ffd83dbSDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
9925ffd83dbSDimitry Andric 
993e8d8bef9SDimitry Andric   // For cold sections use the .text.split. prefix along with the parent
9945ffd83dbSDimitry Andric   // function name. All cold blocks for the same function go to the same
9955ffd83dbSDimitry Andric   // section. Similarly all exception blocks are grouped by symbol name
9965ffd83dbSDimitry Andric   // under the .text.eh prefix. For regular sections, we either use a unique
9975ffd83dbSDimitry Andric   // name, or a unique ID for the section.
9985ffd83dbSDimitry Andric   SmallString<128> Name;
9995ffd83dbSDimitry Andric   if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1000e8d8bef9SDimitry Andric     Name += BBSectionsColdTextPrefix;
10015ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10025ffd83dbSDimitry Andric   } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
10035ffd83dbSDimitry Andric     Name += ".text.eh.";
10045ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10055ffd83dbSDimitry Andric   } else {
10065ffd83dbSDimitry Andric     Name += MBB.getParent()->getSection()->getName();
10075ffd83dbSDimitry Andric     if (TM.getUniqueBasicBlockSectionNames()) {
1008fe6060f1SDimitry Andric       if (!Name.endswith("."))
10095ffd83dbSDimitry Andric         Name += ".";
10105ffd83dbSDimitry Andric       Name += MBB.getSymbol()->getName();
10115ffd83dbSDimitry Andric     } else {
10125ffd83dbSDimitry Andric       UniqueID = NextUniqueID++;
10135ffd83dbSDimitry Andric     }
10145ffd83dbSDimitry Andric   }
10155ffd83dbSDimitry Andric 
10165ffd83dbSDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1017e8d8bef9SDimitry Andric   std::string GroupName;
10185ffd83dbSDimitry Andric   if (F.hasComdat()) {
10195ffd83dbSDimitry Andric     Flags |= ELF::SHF_GROUP;
10205ffd83dbSDimitry Andric     GroupName = F.getComdat()->getName().str();
10215ffd83dbSDimitry Andric   }
10225ffd83dbSDimitry Andric   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1023fe6060f1SDimitry Andric                                     0 /* Entry Size */, GroupName,
1024fe6060f1SDimitry Andric                                     F.hasComdat(), UniqueID, nullptr);
10255ffd83dbSDimitry Andric }
10265ffd83dbSDimitry Andric 
1027*0b57cec5SDimitry Andric static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1028*0b57cec5SDimitry Andric                                               bool IsCtor, unsigned Priority,
1029*0b57cec5SDimitry Andric                                               const MCSymbol *KeySym) {
1030*0b57cec5SDimitry Andric   std::string Name;
1031*0b57cec5SDimitry Andric   unsigned Type;
1032*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1033fe6060f1SDimitry Andric   StringRef Comdat = KeySym ? KeySym->getName() : "";
1034*0b57cec5SDimitry Andric 
1035*0b57cec5SDimitry Andric   if (KeySym)
1036*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
1037*0b57cec5SDimitry Andric 
1038*0b57cec5SDimitry Andric   if (UseInitArray) {
1039*0b57cec5SDimitry Andric     if (IsCtor) {
1040*0b57cec5SDimitry Andric       Type = ELF::SHT_INIT_ARRAY;
1041*0b57cec5SDimitry Andric       Name = ".init_array";
1042*0b57cec5SDimitry Andric     } else {
1043*0b57cec5SDimitry Andric       Type = ELF::SHT_FINI_ARRAY;
1044*0b57cec5SDimitry Andric       Name = ".fini_array";
1045*0b57cec5SDimitry Andric     }
1046*0b57cec5SDimitry Andric     if (Priority != 65535) {
1047*0b57cec5SDimitry Andric       Name += '.';
1048*0b57cec5SDimitry Andric       Name += utostr(Priority);
1049*0b57cec5SDimitry Andric     }
1050*0b57cec5SDimitry Andric   } else {
1051*0b57cec5SDimitry Andric     // The default scheme is .ctor / .dtor, so we have to invert the priority
1052*0b57cec5SDimitry Andric     // numbering.
1053*0b57cec5SDimitry Andric     if (IsCtor)
1054*0b57cec5SDimitry Andric       Name = ".ctors";
1055*0b57cec5SDimitry Andric     else
1056*0b57cec5SDimitry Andric       Name = ".dtors";
1057*0b57cec5SDimitry Andric     if (Priority != 65535)
1058*0b57cec5SDimitry Andric       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1059*0b57cec5SDimitry Andric     Type = ELF::SHT_PROGBITS;
1060*0b57cec5SDimitry Andric   }
1061*0b57cec5SDimitry Andric 
1062fe6060f1SDimitry Andric   return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1063*0b57cec5SDimitry Andric }
1064*0b57cec5SDimitry Andric 
1065*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
1066*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1067*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1068*0b57cec5SDimitry Andric                                   KeySym);
1069*0b57cec5SDimitry Andric }
1070*0b57cec5SDimitry Andric 
1071*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
1072*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1073*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1074*0b57cec5SDimitry Andric                                   KeySym);
1075*0b57cec5SDimitry Andric }
1076*0b57cec5SDimitry Andric 
1077*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
1078*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1079*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1080*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
1081*0b57cec5SDimitry Andric   // functions.
1082*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1083*0b57cec5SDimitry Andric     return nullptr;
1084*0b57cec5SDimitry Andric 
1085*0b57cec5SDimitry Andric   // Basic sanity checks.
1086*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1087*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1088*0b57cec5SDimitry Andric       RHS->isThreadLocal())
1089*0b57cec5SDimitry Andric     return nullptr;
1090*0b57cec5SDimitry Andric 
1091*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
1092*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
1093*0b57cec5SDimitry Andric                               getContext()),
1094*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1095*0b57cec5SDimitry Andric }
1096*0b57cec5SDimitry Andric 
1097e8d8bef9SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1098e8d8bef9SDimitry Andric     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1099e8d8bef9SDimitry Andric   assert(supportDSOLocalEquivalentLowering());
1100e8d8bef9SDimitry Andric 
1101e8d8bef9SDimitry Andric   const auto *GV = Equiv->getGlobalValue();
1102e8d8bef9SDimitry Andric 
1103e8d8bef9SDimitry Andric   // A PLT entry is not needed for dso_local globals.
1104e8d8bef9SDimitry Andric   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1105e8d8bef9SDimitry Andric     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1106e8d8bef9SDimitry Andric 
1107e8d8bef9SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1108e8d8bef9SDimitry Andric                                  getContext());
1109e8d8bef9SDimitry Andric }
1110e8d8bef9SDimitry Andric 
1111*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1112*0b57cec5SDimitry Andric   // Use ".GCC.command.line" since this feature is to support clang's
1113*0b57cec5SDimitry Andric   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1114*0b57cec5SDimitry Andric   // same name.
1115*0b57cec5SDimitry Andric   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1116fe6060f1SDimitry Andric                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
1117*0b57cec5SDimitry Andric }
1118*0b57cec5SDimitry Andric 
1119*0b57cec5SDimitry Andric void
1120*0b57cec5SDimitry Andric TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
1121*0b57cec5SDimitry Andric   UseInitArray = UseInitArray_;
1122*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1123*0b57cec5SDimitry Andric   if (!UseInitArray) {
1124*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1125*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1126*0b57cec5SDimitry Andric 
1127*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1128*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1129*0b57cec5SDimitry Andric     return;
1130*0b57cec5SDimitry Andric   }
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1133*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1134*0b57cec5SDimitry Andric   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1135*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1136*0b57cec5SDimitry Andric }
1137*0b57cec5SDimitry Andric 
1138*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1139*0b57cec5SDimitry Andric //                                 MachO
1140*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
1143*0b57cec5SDimitry Andric   : TargetLoweringObjectFile() {
1144*0b57cec5SDimitry Andric   SupportIndirectSymViaGOTPCRel = true;
1145*0b57cec5SDimitry Andric }
1146*0b57cec5SDimitry Andric 
1147*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1148*0b57cec5SDimitry Andric                                                const TargetMachine &TM) {
1149*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1150*0b57cec5SDimitry Andric   if (TM.getRelocationModel() == Reloc::Static) {
1151*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1152*0b57cec5SDimitry Andric                                             SectionKind::getData());
1153*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1154*0b57cec5SDimitry Andric                                             SectionKind::getData());
1155*0b57cec5SDimitry Andric   } else {
1156*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1157*0b57cec5SDimitry Andric                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1158*0b57cec5SDimitry Andric                                             SectionKind::getData());
1159*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1160*0b57cec5SDimitry Andric                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1161*0b57cec5SDimitry Andric                                             SectionKind::getData());
1162*0b57cec5SDimitry Andric   }
1163*0b57cec5SDimitry Andric 
1164*0b57cec5SDimitry Andric   PersonalityEncoding =
1165*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1166*0b57cec5SDimitry Andric   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1167*0b57cec5SDimitry Andric   TTypeEncoding =
1168*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1169*0b57cec5SDimitry Andric }
1170*0b57cec5SDimitry Andric 
1171*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1172*0b57cec5SDimitry Andric                                                        Module &M) const {
1173*0b57cec5SDimitry Andric   // Emit the linker options if present.
1174*0b57cec5SDimitry Andric   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1175480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1176*0b57cec5SDimitry Andric       SmallVector<std::string, 4> StrOptions;
1177*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands())
11785ffd83dbSDimitry Andric         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
11795ffd83dbSDimitry Andric       Streamer.emitLinkerOptions(StrOptions);
1180*0b57cec5SDimitry Andric     }
1181*0b57cec5SDimitry Andric   }
1182*0b57cec5SDimitry Andric 
1183*0b57cec5SDimitry Andric   unsigned VersionVal = 0;
1184*0b57cec5SDimitry Andric   unsigned ImageInfoFlags = 0;
1185*0b57cec5SDimitry Andric   StringRef SectionVal;
1186*0b57cec5SDimitry Andric 
1187*0b57cec5SDimitry Andric   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1188*0b57cec5SDimitry Andric 
1189*0b57cec5SDimitry Andric   // The section is mandatory. If we don't have it, then we don't have GC info.
1190*0b57cec5SDimitry Andric   if (SectionVal.empty())
1191*0b57cec5SDimitry Andric     return;
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric   StringRef Segment, Section;
1194*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1195*0b57cec5SDimitry Andric   bool TAAParsed;
1196fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1197fe6060f1SDimitry Andric           SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1198*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1199fe6060f1SDimitry Andric     report_fatal_error("Invalid section specifier '" + Section +
1200fe6060f1SDimitry Andric                        "': " + toString(std::move(E)) + ".");
1201fe6060f1SDimitry Andric   }
1202*0b57cec5SDimitry Andric 
1203*0b57cec5SDimitry Andric   // Get the section.
1204*0b57cec5SDimitry Andric   MCSectionMachO *S = getContext().getMachOSection(
1205*0b57cec5SDimitry Andric       Segment, Section, TAA, StubSize, SectionKind::getData());
1206*0b57cec5SDimitry Andric   Streamer.SwitchSection(S);
12075ffd83dbSDimitry Andric   Streamer.emitLabel(getContext().
1208*0b57cec5SDimitry Andric                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
12095ffd83dbSDimitry Andric   Streamer.emitInt32(VersionVal);
12105ffd83dbSDimitry Andric   Streamer.emitInt32(ImageInfoFlags);
1211*0b57cec5SDimitry Andric   Streamer.AddBlankLine();
1212*0b57cec5SDimitry Andric }
1213*0b57cec5SDimitry Andric 
1214*0b57cec5SDimitry Andric static void checkMachOComdat(const GlobalValue *GV) {
1215*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1216*0b57cec5SDimitry Andric   if (!C)
1217*0b57cec5SDimitry Andric     return;
1218*0b57cec5SDimitry Andric 
1219*0b57cec5SDimitry Andric   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1220*0b57cec5SDimitry Andric                      "' cannot be lowered.");
1221*0b57cec5SDimitry Andric }
1222*0b57cec5SDimitry Andric 
1223*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1224*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1225fe6060f1SDimitry Andric 
1226fe6060f1SDimitry Andric   StringRef SectionName = GO->getSection();
1227fe6060f1SDimitry Andric 
1228fe6060f1SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
1229fe6060f1SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
1230fe6060f1SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
1231fe6060f1SDimitry Andric   }
1232fe6060f1SDimitry Andric 
1233*0b57cec5SDimitry Andric   // Parse the section specifier and create it if valid.
1234*0b57cec5SDimitry Andric   StringRef Segment, Section;
1235*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1236*0b57cec5SDimitry Andric   bool TAAParsed;
1237*0b57cec5SDimitry Andric 
1238*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1239*0b57cec5SDimitry Andric 
1240fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1241fe6060f1SDimitry Andric           SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1242*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1243*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1244*0b57cec5SDimitry Andric                        "' has an invalid section specifier '" +
1245fe6060f1SDimitry Andric                        GO->getSection() + "': " + toString(std::move(E)) + ".");
1246*0b57cec5SDimitry Andric   }
1247*0b57cec5SDimitry Andric 
1248*0b57cec5SDimitry Andric   // Get the section.
1249*0b57cec5SDimitry Andric   MCSectionMachO *S =
1250*0b57cec5SDimitry Andric       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1251*0b57cec5SDimitry Andric 
1252*0b57cec5SDimitry Andric   // If TAA wasn't set by ParseSectionSpecifier() above,
1253*0b57cec5SDimitry Andric   // use the value returned by getMachOSection() as a default.
1254*0b57cec5SDimitry Andric   if (!TAAParsed)
1255*0b57cec5SDimitry Andric     TAA = S->getTypeAndAttributes();
1256*0b57cec5SDimitry Andric 
1257*0b57cec5SDimitry Andric   // Okay, now that we got the section, verify that the TAA & StubSize agree.
1258*0b57cec5SDimitry Andric   // If the user declared multiple globals with different section flags, we need
1259*0b57cec5SDimitry Andric   // to reject it here.
1260*0b57cec5SDimitry Andric   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1261*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1262*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1263*0b57cec5SDimitry Andric                        "' section type or attributes does not match previous"
1264*0b57cec5SDimitry Andric                        " section specifier");
1265*0b57cec5SDimitry Andric   }
1266*0b57cec5SDimitry Andric 
1267*0b57cec5SDimitry Andric   return S;
1268*0b57cec5SDimitry Andric }
1269*0b57cec5SDimitry Andric 
1270*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1271*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1272*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1273*0b57cec5SDimitry Andric 
1274*0b57cec5SDimitry Andric   // Handle thread local data.
1275*0b57cec5SDimitry Andric   if (Kind.isThreadBSS()) return TLSBSSSection;
1276*0b57cec5SDimitry Andric   if (Kind.isThreadData()) return TLSDataSection;
1277*0b57cec5SDimitry Andric 
1278*0b57cec5SDimitry Andric   if (Kind.isText())
1279*0b57cec5SDimitry Andric     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1280*0b57cec5SDimitry Andric 
1281*0b57cec5SDimitry Andric   // If this is weak/linkonce, put this in a coalescable section, either in text
1282*0b57cec5SDimitry Andric   // or data depending on if it is writable.
1283*0b57cec5SDimitry Andric   if (GO->isWeakForLinker()) {
1284*0b57cec5SDimitry Andric     if (Kind.isReadOnly())
1285*0b57cec5SDimitry Andric       return ConstTextCoalSection;
1286*0b57cec5SDimitry Andric     if (Kind.isReadOnlyWithRel())
1287*0b57cec5SDimitry Andric       return ConstDataCoalSection;
1288*0b57cec5SDimitry Andric     return DataCoalSection;
1289*0b57cec5SDimitry Andric   }
1290*0b57cec5SDimitry Andric 
1291*0b57cec5SDimitry Andric   // FIXME: Alignment check should be handled by section classifier.
1292*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString() &&
12935ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
12945ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1295*0b57cec5SDimitry Andric     return CStringSection;
1296*0b57cec5SDimitry Andric 
1297*0b57cec5SDimitry Andric   // Do not put 16-bit arrays in the UString section if they have an
1298*0b57cec5SDimitry Andric   // externally visible label, this runs into issues with certain linker
1299*0b57cec5SDimitry Andric   // versions.
1300*0b57cec5SDimitry Andric   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
13015ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
13025ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1303*0b57cec5SDimitry Andric     return UStringSection;
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric   // With MachO only variables whose corresponding symbol starts with 'l' or
1306*0b57cec5SDimitry Andric   // 'L' can be merged, so we only try merging GVs with private linkage.
1307*0b57cec5SDimitry Andric   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1308*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4())
1309*0b57cec5SDimitry Andric       return FourByteConstantSection;
1310*0b57cec5SDimitry Andric     if (Kind.isMergeableConst8())
1311*0b57cec5SDimitry Andric       return EightByteConstantSection;
1312*0b57cec5SDimitry Andric     if (Kind.isMergeableConst16())
1313*0b57cec5SDimitry Andric       return SixteenByteConstantSection;
1314*0b57cec5SDimitry Andric   }
1315*0b57cec5SDimitry Andric 
1316*0b57cec5SDimitry Andric   // Otherwise, if it is readonly, but not something we can specially optimize,
1317*0b57cec5SDimitry Andric   // just drop it in .const.
1318*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
1319*0b57cec5SDimitry Andric     return ReadOnlySection;
1320*0b57cec5SDimitry Andric 
1321*0b57cec5SDimitry Andric   // If this is marked const, put it into a const section.  But if the dynamic
1322*0b57cec5SDimitry Andric   // linker needs to write to it, put it in the data segment.
1323*0b57cec5SDimitry Andric   if (Kind.isReadOnlyWithRel())
1324*0b57cec5SDimitry Andric     return ConstDataSection;
1325*0b57cec5SDimitry Andric 
1326*0b57cec5SDimitry Andric   // Put zero initialized globals with strong external linkage in the
1327*0b57cec5SDimitry Andric   // DATA, __common section with the .zerofill directive.
1328*0b57cec5SDimitry Andric   if (Kind.isBSSExtern())
1329*0b57cec5SDimitry Andric     return DataCommonSection;
1330*0b57cec5SDimitry Andric 
1331*0b57cec5SDimitry Andric   // Put zero initialized globals with local linkage in __DATA,__bss directive
1332*0b57cec5SDimitry Andric   // with the .zerofill directive (aka .lcomm).
1333*0b57cec5SDimitry Andric   if (Kind.isBSSLocal())
1334*0b57cec5SDimitry Andric     return DataBSSSection;
1335*0b57cec5SDimitry Andric 
1336*0b57cec5SDimitry Andric   // Otherwise, just drop the variable in the normal data section.
1337*0b57cec5SDimitry Andric   return DataSection;
1338*0b57cec5SDimitry Andric }
1339*0b57cec5SDimitry Andric 
1340*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1341*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
13425ffd83dbSDimitry Andric     Align &Alignment) const {
1343*0b57cec5SDimitry Andric   // If this constant requires a relocation, we have to put it in the data
1344*0b57cec5SDimitry Andric   // segment, not in the text segment.
1345*0b57cec5SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel())
1346*0b57cec5SDimitry Andric     return ConstDataSection;
1347*0b57cec5SDimitry Andric 
1348*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4())
1349*0b57cec5SDimitry Andric     return FourByteConstantSection;
1350*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8())
1351*0b57cec5SDimitry Andric     return EightByteConstantSection;
1352*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16())
1353*0b57cec5SDimitry Andric     return SixteenByteConstantSection;
1354*0b57cec5SDimitry Andric   return ReadOnlySection;  // .const
1355*0b57cec5SDimitry Andric }
1356*0b57cec5SDimitry Andric 
1357*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1358*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1359*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1360*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1361*0b57cec5SDimitry Andric 
1362*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
1363*0b57cec5SDimitry Andric     MachineModuleInfoMachO &MachOMMI =
1364*0b57cec5SDimitry Andric       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1365*0b57cec5SDimitry Andric 
1366*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1367*0b57cec5SDimitry Andric 
1368*0b57cec5SDimitry Andric     // Add information about the stub reference to MachOMMI so that the stub
1369*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
1370*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1371*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
1372*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
1373*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1374*0b57cec5SDimitry Andric     }
1375*0b57cec5SDimitry Andric 
1376*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
1377*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1378*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
1379*0b57cec5SDimitry Andric   }
1380*0b57cec5SDimitry Andric 
1381*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1382*0b57cec5SDimitry Andric                                                            MMI, Streamer);
1383*0b57cec5SDimitry Andric }
1384*0b57cec5SDimitry Andric 
1385*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1386*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
1387*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
1388*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1389*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1390*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1391*0b57cec5SDimitry Andric 
1392*0b57cec5SDimitry Andric   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1393*0b57cec5SDimitry Andric 
1394*0b57cec5SDimitry Andric   // Add information about the stub reference to MachOMMI so that the stub
1395*0b57cec5SDimitry Andric   // gets emitted by the asmprinter.
1396*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1397*0b57cec5SDimitry Andric   if (!StubSym.getPointer()) {
1398*0b57cec5SDimitry Andric     MCSymbol *Sym = TM.getSymbol(GV);
1399*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1400*0b57cec5SDimitry Andric   }
1401*0b57cec5SDimitry Andric 
1402*0b57cec5SDimitry Andric   return SSym;
1403*0b57cec5SDimitry Andric }
1404*0b57cec5SDimitry Andric 
1405*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
14068bcb0991SDimitry Andric     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
14078bcb0991SDimitry Andric     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1408*0b57cec5SDimitry Andric   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1409*0b57cec5SDimitry Andric   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1410*0b57cec5SDimitry Andric   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1411*0b57cec5SDimitry Andric   // computation of deltas to final external symbols. Example:
1412*0b57cec5SDimitry Andric   //
1413*0b57cec5SDimitry Andric   //    _extgotequiv:
1414*0b57cec5SDimitry Andric   //       .long   _extfoo
1415*0b57cec5SDimitry Andric   //
1416*0b57cec5SDimitry Andric   //    _delta:
1417*0b57cec5SDimitry Andric   //       .long   _extgotequiv-_delta
1418*0b57cec5SDimitry Andric   //
1419*0b57cec5SDimitry Andric   // is transformed to:
1420*0b57cec5SDimitry Andric   //
1421*0b57cec5SDimitry Andric   //    _delta:
1422*0b57cec5SDimitry Andric   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1423*0b57cec5SDimitry Andric   //
1424*0b57cec5SDimitry Andric   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1425*0b57cec5SDimitry Andric   //    L_extfoo$non_lazy_ptr:
1426*0b57cec5SDimitry Andric   //       .indirect_symbol        _extfoo
1427*0b57cec5SDimitry Andric   //       .long   0
1428*0b57cec5SDimitry Andric   //
1429*0b57cec5SDimitry Andric   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1430*0b57cec5SDimitry Andric   // may point to both local (same translation unit) and global (other
1431*0b57cec5SDimitry Andric   // translation units) symbols. Example:
1432*0b57cec5SDimitry Andric   //
1433*0b57cec5SDimitry Andric   // .section __DATA,__pointers,non_lazy_symbol_pointers
1434*0b57cec5SDimitry Andric   // L1:
1435*0b57cec5SDimitry Andric   //    .indirect_symbol _myGlobal
1436*0b57cec5SDimitry Andric   //    .long 0
1437*0b57cec5SDimitry Andric   // L2:
1438*0b57cec5SDimitry Andric   //    .indirect_symbol _myLocal
1439*0b57cec5SDimitry Andric   //    .long _myLocal
1440*0b57cec5SDimitry Andric   //
1441*0b57cec5SDimitry Andric   // If the symbol is local, instead of the symbol's index, the assembler
1442*0b57cec5SDimitry Andric   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1443*0b57cec5SDimitry Andric   // Then the linker will notice the constant in the table and will look at the
1444*0b57cec5SDimitry Andric   // content of the symbol.
1445*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1446*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1447*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1448*0b57cec5SDimitry Andric 
1449*0b57cec5SDimitry Andric   // The offset must consider the original displacement from the base symbol
1450*0b57cec5SDimitry Andric   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1451*0b57cec5SDimitry Andric   Offset = -MV.getConstant();
1452*0b57cec5SDimitry Andric   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1453*0b57cec5SDimitry Andric 
1454*0b57cec5SDimitry Andric   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1455*0b57cec5SDimitry Andric   // non_lazy_ptr stubs.
1456*0b57cec5SDimitry Andric   SmallString<128> Name;
1457*0b57cec5SDimitry Andric   StringRef Suffix = "$non_lazy_ptr";
1458*0b57cec5SDimitry Andric   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1459*0b57cec5SDimitry Andric   Name += Sym->getName();
1460*0b57cec5SDimitry Andric   Name += Suffix;
1461*0b57cec5SDimitry Andric   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1462*0b57cec5SDimitry Andric 
1463*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
14648bcb0991SDimitry Andric 
14658bcb0991SDimitry Andric   if (!StubSym.getPointer())
1466*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
14678bcb0991SDimitry Andric                                                  !GV->hasLocalLinkage());
1468*0b57cec5SDimitry Andric 
1469*0b57cec5SDimitry Andric   const MCExpr *BSymExpr =
1470*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1471*0b57cec5SDimitry Andric   const MCExpr *LHS =
1472*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1473*0b57cec5SDimitry Andric 
1474*0b57cec5SDimitry Andric   if (!Offset)
1475*0b57cec5SDimitry Andric     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1476*0b57cec5SDimitry Andric 
1477*0b57cec5SDimitry Andric   const MCExpr *RHS =
1478*0b57cec5SDimitry Andric     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1479*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1480*0b57cec5SDimitry Andric }
1481*0b57cec5SDimitry Andric 
1482*0b57cec5SDimitry Andric static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1483*0b57cec5SDimitry Andric                                const MCSection &Section) {
1484*0b57cec5SDimitry Andric   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1485*0b57cec5SDimitry Andric     return true;
1486*0b57cec5SDimitry Andric 
1487fe6060f1SDimitry Andric   // FIXME: we should be able to use private labels for sections that can't be
1488fe6060f1SDimitry Andric   // dead-stripped (there's no issue with blocking atomization there), but `ld
1489fe6060f1SDimitry Andric   // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1490fe6060f1SDimitry Andric   // we don't allow it.
1491*0b57cec5SDimitry Andric   return false;
1492*0b57cec5SDimitry Andric }
1493*0b57cec5SDimitry Andric 
1494*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::getNameWithPrefix(
1495*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1496*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1497*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = true;
1498*0b57cec5SDimitry Andric   if (auto *GO = GV->getBaseObject()) {
1499*0b57cec5SDimitry Andric     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1500*0b57cec5SDimitry Andric     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1501*0b57cec5SDimitry Andric     CannotUsePrivateLabel =
1502*0b57cec5SDimitry Andric         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1503*0b57cec5SDimitry Andric   }
1504*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1505*0b57cec5SDimitry Andric }
1506*0b57cec5SDimitry Andric 
1507*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1508*0b57cec5SDimitry Andric //                                  COFF
1509*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric static unsigned
1512*0b57cec5SDimitry Andric getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1513*0b57cec5SDimitry Andric   unsigned Flags = 0;
1514*0b57cec5SDimitry Andric   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1515*0b57cec5SDimitry Andric 
1516*0b57cec5SDimitry Andric   if (K.isMetadata())
1517*0b57cec5SDimitry Andric     Flags |=
1518*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1519*0b57cec5SDimitry Andric   else if (K.isText())
1520*0b57cec5SDimitry Andric     Flags |=
1521*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_EXECUTE |
1522*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1523*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_CODE |
1524*0b57cec5SDimitry Andric       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1525*0b57cec5SDimitry Andric   else if (K.isBSS())
1526*0b57cec5SDimitry Andric     Flags |=
1527*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1528*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1529*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1530*0b57cec5SDimitry Andric   else if (K.isThreadLocal())
1531*0b57cec5SDimitry Andric     Flags |=
1532*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1533*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1534*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1535*0b57cec5SDimitry Andric   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1536*0b57cec5SDimitry Andric     Flags |=
1537*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1538*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ;
1539*0b57cec5SDimitry Andric   else if (K.isWriteable())
1540*0b57cec5SDimitry Andric     Flags |=
1541*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1542*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1543*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1544*0b57cec5SDimitry Andric 
1545*0b57cec5SDimitry Andric   return Flags;
1546*0b57cec5SDimitry Andric }
1547*0b57cec5SDimitry Andric 
1548*0b57cec5SDimitry Andric static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1549*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1550*0b57cec5SDimitry Andric   assert(C && "expected GV to have a Comdat!");
1551*0b57cec5SDimitry Andric 
1552*0b57cec5SDimitry Andric   StringRef ComdatGVName = C->getName();
1553*0b57cec5SDimitry Andric   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1554*0b57cec5SDimitry Andric   if (!ComdatGV)
1555*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1556*0b57cec5SDimitry Andric                        "' does not exist.");
1557*0b57cec5SDimitry Andric 
1558*0b57cec5SDimitry Andric   if (ComdatGV->getComdat() != C)
1559*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1560*0b57cec5SDimitry Andric                        "' is not a key for its COMDAT.");
1561*0b57cec5SDimitry Andric 
1562*0b57cec5SDimitry Andric   return ComdatGV;
1563*0b57cec5SDimitry Andric }
1564*0b57cec5SDimitry Andric 
1565*0b57cec5SDimitry Andric static int getSelectionForCOFF(const GlobalValue *GV) {
1566*0b57cec5SDimitry Andric   if (const Comdat *C = GV->getComdat()) {
1567*0b57cec5SDimitry Andric     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1568*0b57cec5SDimitry Andric     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1569*0b57cec5SDimitry Andric       ComdatKey = GA->getBaseObject();
1570*0b57cec5SDimitry Andric     if (ComdatKey == GV) {
1571*0b57cec5SDimitry Andric       switch (C->getSelectionKind()) {
1572*0b57cec5SDimitry Andric       case Comdat::Any:
1573*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_ANY;
1574*0b57cec5SDimitry Andric       case Comdat::ExactMatch:
1575*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1576*0b57cec5SDimitry Andric       case Comdat::Largest:
1577*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1578fe6060f1SDimitry Andric       case Comdat::NoDeduplicate:
1579*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1580*0b57cec5SDimitry Andric       case Comdat::SameSize:
1581*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1582*0b57cec5SDimitry Andric       }
1583*0b57cec5SDimitry Andric     } else {
1584*0b57cec5SDimitry Andric       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1585*0b57cec5SDimitry Andric     }
1586*0b57cec5SDimitry Andric   }
1587*0b57cec5SDimitry Andric   return 0;
1588*0b57cec5SDimitry Andric }
1589*0b57cec5SDimitry Andric 
1590*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1591*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1592*0b57cec5SDimitry Andric   int Selection = 0;
1593*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1594*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
1595*0b57cec5SDimitry Andric   StringRef COMDATSymName = "";
1596*0b57cec5SDimitry Andric   if (GO->hasComdat()) {
1597*0b57cec5SDimitry Andric     Selection = getSelectionForCOFF(GO);
1598*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1599*0b57cec5SDimitry Andric     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1600*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1601*0b57cec5SDimitry Andric     else
1602*0b57cec5SDimitry Andric       ComdatGV = GO;
1603*0b57cec5SDimitry Andric 
1604*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1605*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1606*0b57cec5SDimitry Andric       COMDATSymName = Sym->getName();
1607*0b57cec5SDimitry Andric       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1608*0b57cec5SDimitry Andric     } else {
1609*0b57cec5SDimitry Andric       Selection = 0;
1610*0b57cec5SDimitry Andric     }
1611*0b57cec5SDimitry Andric   }
1612*0b57cec5SDimitry Andric 
1613*0b57cec5SDimitry Andric   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1614*0b57cec5SDimitry Andric                                      Selection);
1615*0b57cec5SDimitry Andric }
1616*0b57cec5SDimitry Andric 
1617*0b57cec5SDimitry Andric static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1618*0b57cec5SDimitry Andric   if (Kind.isText())
1619*0b57cec5SDimitry Andric     return ".text";
1620*0b57cec5SDimitry Andric   if (Kind.isBSS())
1621*0b57cec5SDimitry Andric     return ".bss";
1622*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1623*0b57cec5SDimitry Andric     return ".tls$";
1624*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1625*0b57cec5SDimitry Andric     return ".rdata";
1626*0b57cec5SDimitry Andric   return ".data";
1627*0b57cec5SDimitry Andric }
1628*0b57cec5SDimitry Andric 
1629*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1630*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1631*0b57cec5SDimitry Andric   // If we have -ffunction-sections then we should emit the global value to a
1632*0b57cec5SDimitry Andric   // uniqued section specifically for it.
1633*0b57cec5SDimitry Andric   bool EmitUniquedSection;
1634*0b57cec5SDimitry Andric   if (Kind.isText())
1635*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getFunctionSections();
1636*0b57cec5SDimitry Andric   else
1637*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getDataSections();
1638*0b57cec5SDimitry Andric 
1639*0b57cec5SDimitry Andric   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1640*0b57cec5SDimitry Andric     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1641*0b57cec5SDimitry Andric 
1642*0b57cec5SDimitry Andric     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1643*0b57cec5SDimitry Andric 
1644*0b57cec5SDimitry Andric     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1645*0b57cec5SDimitry Andric     int Selection = getSelectionForCOFF(GO);
1646*0b57cec5SDimitry Andric     if (!Selection)
1647*0b57cec5SDimitry Andric       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1648*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1649*0b57cec5SDimitry Andric     if (GO->hasComdat())
1650*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1651*0b57cec5SDimitry Andric     else
1652*0b57cec5SDimitry Andric       ComdatGV = GO;
1653*0b57cec5SDimitry Andric 
1654*0b57cec5SDimitry Andric     unsigned UniqueID = MCContext::GenericSectionID;
1655*0b57cec5SDimitry Andric     if (EmitUniquedSection)
1656*0b57cec5SDimitry Andric       UniqueID = NextUniqueID++;
1657*0b57cec5SDimitry Andric 
1658*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1659*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1660*0b57cec5SDimitry Andric       StringRef COMDATSymName = Sym->getName();
1661*0b57cec5SDimitry Andric 
1662e8d8bef9SDimitry Andric       if (const auto *F = dyn_cast<Function>(GO))
1663e8d8bef9SDimitry Andric         if (Optional<StringRef> Prefix = F->getSectionPrefix())
1664e8d8bef9SDimitry Andric           raw_svector_ostream(Name) << '$' << *Prefix;
1665e8d8bef9SDimitry Andric 
1666*0b57cec5SDimitry Andric       // Append "$symbol" to the section name *before* IR-level mangling is
1667*0b57cec5SDimitry Andric       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1668*0b57cec5SDimitry Andric       // COFF linker will not properly handle comdats otherwise.
1669fe6060f1SDimitry Andric       if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1670*0b57cec5SDimitry Andric         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1671*0b57cec5SDimitry Andric 
1672*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind,
1673*0b57cec5SDimitry Andric                                          COMDATSymName, Selection, UniqueID);
1674*0b57cec5SDimitry Andric     } else {
1675*0b57cec5SDimitry Andric       SmallString<256> TmpData;
1676*0b57cec5SDimitry Andric       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1677*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1678*0b57cec5SDimitry Andric                                          Selection, UniqueID);
1679*0b57cec5SDimitry Andric     }
1680*0b57cec5SDimitry Andric   }
1681*0b57cec5SDimitry Andric 
1682*0b57cec5SDimitry Andric   if (Kind.isText())
1683*0b57cec5SDimitry Andric     return TextSection;
1684*0b57cec5SDimitry Andric 
1685*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1686*0b57cec5SDimitry Andric     return TLSDataSection;
1687*0b57cec5SDimitry Andric 
1688*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1689*0b57cec5SDimitry Andric     return ReadOnlySection;
1690*0b57cec5SDimitry Andric 
1691*0b57cec5SDimitry Andric   // Note: we claim that common symbols are put in BSSSection, but they are
1692*0b57cec5SDimitry Andric   // really emitted with the magic .comm directive, which creates a symbol table
1693*0b57cec5SDimitry Andric   // entry but not a section.
1694*0b57cec5SDimitry Andric   if (Kind.isBSS() || Kind.isCommon())
1695*0b57cec5SDimitry Andric     return BSSSection;
1696*0b57cec5SDimitry Andric 
1697*0b57cec5SDimitry Andric   return DataSection;
1698*0b57cec5SDimitry Andric }
1699*0b57cec5SDimitry Andric 
1700*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1701*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1702*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1703*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = false;
1704*0b57cec5SDimitry Andric   if (GV->hasPrivateLinkage() &&
1705*0b57cec5SDimitry Andric       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1706*0b57cec5SDimitry Andric        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1707*0b57cec5SDimitry Andric     CannotUsePrivateLabel = true;
1708*0b57cec5SDimitry Andric 
1709*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1710*0b57cec5SDimitry Andric }
1711*0b57cec5SDimitry Andric 
1712*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1713*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
1714*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
1715*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
1716*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
1717*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
1718*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
1719*0b57cec5SDimitry Andric     return ReadOnlySection;
1720*0b57cec5SDimitry Andric 
1721*0b57cec5SDimitry Andric   // FIXME: we should produce a symbol for F instead.
1722*0b57cec5SDimitry Andric   if (F.hasPrivateLinkage())
1723*0b57cec5SDimitry Andric     return ReadOnlySection;
1724*0b57cec5SDimitry Andric 
1725*0b57cec5SDimitry Andric   MCSymbol *Sym = TM.getSymbol(&F);
1726*0b57cec5SDimitry Andric   StringRef COMDATSymName = Sym->getName();
1727*0b57cec5SDimitry Andric 
1728*0b57cec5SDimitry Andric   SectionKind Kind = SectionKind::getReadOnly();
1729*0b57cec5SDimitry Andric   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1730*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1731*0b57cec5SDimitry Andric   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1732*0b57cec5SDimitry Andric   unsigned UniqueID = NextUniqueID++;
1733*0b57cec5SDimitry Andric 
1734*0b57cec5SDimitry Andric   return getContext().getCOFFSection(
1735*0b57cec5SDimitry Andric       SecName, Characteristics, Kind, COMDATSymName,
1736*0b57cec5SDimitry Andric       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1737*0b57cec5SDimitry Andric }
1738*0b57cec5SDimitry Andric 
1739*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1740*0b57cec5SDimitry Andric                                                       Module &M) const {
1741e8d8bef9SDimitry Andric   emitLinkerDirectives(Streamer, M);
1742e8d8bef9SDimitry Andric 
1743e8d8bef9SDimitry Andric   unsigned Version = 0;
1744e8d8bef9SDimitry Andric   unsigned Flags = 0;
1745e8d8bef9SDimitry Andric   StringRef Section;
1746e8d8bef9SDimitry Andric 
1747e8d8bef9SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
1748e8d8bef9SDimitry Andric   if (!Section.empty()) {
1749e8d8bef9SDimitry Andric     auto &C = getContext();
1750e8d8bef9SDimitry Andric     auto *S = C.getCOFFSection(Section,
1751e8d8bef9SDimitry Andric                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1752e8d8bef9SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ,
1753e8d8bef9SDimitry Andric                                SectionKind::getReadOnly());
1754e8d8bef9SDimitry Andric     Streamer.SwitchSection(S);
1755e8d8bef9SDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1756e8d8bef9SDimitry Andric     Streamer.emitInt32(Version);
1757e8d8bef9SDimitry Andric     Streamer.emitInt32(Flags);
1758e8d8bef9SDimitry Andric     Streamer.AddBlankLine();
1759e8d8bef9SDimitry Andric   }
1760e8d8bef9SDimitry Andric 
1761e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1762e8d8bef9SDimitry Andric }
1763e8d8bef9SDimitry Andric 
1764e8d8bef9SDimitry Andric void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1765e8d8bef9SDimitry Andric     MCStreamer &Streamer, Module &M) const {
1766*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1767*0b57cec5SDimitry Andric     // Emit the linker options to the linker .drectve section.  According to the
1768*0b57cec5SDimitry Andric     // spec, this section is a space-separated string containing flags for
1769*0b57cec5SDimitry Andric     // linker.
1770*0b57cec5SDimitry Andric     MCSection *Sec = getDrectveSection();
1771*0b57cec5SDimitry Andric     Streamer.SwitchSection(Sec);
1772480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1773*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1774*0b57cec5SDimitry Andric         // Lead with a space for consistency with our dllexport implementation.
1775*0b57cec5SDimitry Andric         std::string Directive(" ");
17765ffd83dbSDimitry Andric         Directive.append(std::string(cast<MDString>(Piece)->getString()));
17775ffd83dbSDimitry Andric         Streamer.emitBytes(Directive);
1778*0b57cec5SDimitry Andric       }
1779*0b57cec5SDimitry Andric     }
1780*0b57cec5SDimitry Andric   }
1781*0b57cec5SDimitry Andric 
1782e8d8bef9SDimitry Andric   // Emit /EXPORT: flags for each exported global as necessary.
1783e8d8bef9SDimitry Andric   std::string Flags;
1784e8d8bef9SDimitry Andric   for (const GlobalValue &GV : M.global_values()) {
1785e8d8bef9SDimitry Andric     raw_string_ostream OS(Flags);
1786fe6060f1SDimitry Andric     emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1787fe6060f1SDimitry Andric                                  getMangler());
1788e8d8bef9SDimitry Andric     OS.flush();
1789e8d8bef9SDimitry Andric     if (!Flags.empty()) {
1790e8d8bef9SDimitry Andric       Streamer.SwitchSection(getDrectveSection());
1791e8d8bef9SDimitry Andric       Streamer.emitBytes(Flags);
1792e8d8bef9SDimitry Andric     }
1793e8d8bef9SDimitry Andric     Flags.clear();
1794e8d8bef9SDimitry Andric   }
1795*0b57cec5SDimitry Andric 
1796e8d8bef9SDimitry Andric   // Emit /INCLUDE: flags for each used global as necessary.
1797e8d8bef9SDimitry Andric   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1798e8d8bef9SDimitry Andric     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1799e8d8bef9SDimitry Andric     assert(isa<ArrayType>(LU->getValueType()) &&
1800e8d8bef9SDimitry Andric            "expected llvm.used to be an array type");
1801e8d8bef9SDimitry Andric     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1802e8d8bef9SDimitry Andric       for (const Value *Op : A->operands()) {
1803e8d8bef9SDimitry Andric         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1804e8d8bef9SDimitry Andric         // Global symbols with internal or private linkage are not visible to
1805e8d8bef9SDimitry Andric         // the linker, and thus would cause an error when the linker tried to
1806e8d8bef9SDimitry Andric         // preserve the symbol due to the `/include:` directive.
1807e8d8bef9SDimitry Andric         if (GV->hasLocalLinkage())
1808e8d8bef9SDimitry Andric           continue;
1809*0b57cec5SDimitry Andric 
1810e8d8bef9SDimitry Andric         raw_string_ostream OS(Flags);
1811fe6060f1SDimitry Andric         emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1812fe6060f1SDimitry Andric                                    getMangler());
1813e8d8bef9SDimitry Andric         OS.flush();
1814e8d8bef9SDimitry Andric 
1815e8d8bef9SDimitry Andric         if (!Flags.empty()) {
1816e8d8bef9SDimitry Andric           Streamer.SwitchSection(getDrectveSection());
1817e8d8bef9SDimitry Andric           Streamer.emitBytes(Flags);
1818e8d8bef9SDimitry Andric         }
1819e8d8bef9SDimitry Andric         Flags.clear();
1820e8d8bef9SDimitry Andric       }
1821e8d8bef9SDimitry Andric     }
1822e8d8bef9SDimitry Andric   }
1823*0b57cec5SDimitry Andric }
1824*0b57cec5SDimitry Andric 
1825*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1826*0b57cec5SDimitry Andric                                               const TargetMachine &TM) {
1827*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1828e8d8bef9SDimitry Andric   this->TM = &TM;
1829*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1830*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1831*0b57cec5SDimitry Andric     StaticCtorSection =
1832*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1833*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1834*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1835*0b57cec5SDimitry Andric     StaticDtorSection =
1836*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1837*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1838*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1839*0b57cec5SDimitry Andric   } else {
1840*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getCOFFSection(
1841*0b57cec5SDimitry Andric         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1842*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1843*0b57cec5SDimitry Andric         SectionKind::getData());
1844*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getCOFFSection(
1845*0b57cec5SDimitry Andric         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1846*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1847*0b57cec5SDimitry Andric         SectionKind::getData());
1848*0b57cec5SDimitry Andric   }
1849*0b57cec5SDimitry Andric }
1850*0b57cec5SDimitry Andric 
1851*0b57cec5SDimitry Andric static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1852*0b57cec5SDimitry Andric                                                    const Triple &T, bool IsCtor,
1853*0b57cec5SDimitry Andric                                                    unsigned Priority,
1854*0b57cec5SDimitry Andric                                                    const MCSymbol *KeySym,
1855*0b57cec5SDimitry Andric                                                    MCSectionCOFF *Default) {
1856*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1857*0b57cec5SDimitry Andric     // If the priority is the default, use .CRT$XCU, possibly associative.
1858*0b57cec5SDimitry Andric     if (Priority == 65535)
1859*0b57cec5SDimitry Andric       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1860*0b57cec5SDimitry Andric 
1861*0b57cec5SDimitry Andric     // Otherwise, we need to compute a new section name. Low priorities should
1862*0b57cec5SDimitry Andric     // run earlier. The linker will sort sections ASCII-betically, and we need a
1863*0b57cec5SDimitry Andric     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1864*0b57cec5SDimitry Andric     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1865*0b57cec5SDimitry Andric     // low priorities need to sort before 'L', since the CRT uses that
1866*0b57cec5SDimitry Andric     // internally, so we use ".CRT$XCA00001" for them.
1867*0b57cec5SDimitry Andric     SmallString<24> Name;
1868*0b57cec5SDimitry Andric     raw_svector_ostream OS(Name);
18698bcb0991SDimitry Andric     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
18708bcb0991SDimitry Andric         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1871*0b57cec5SDimitry Andric     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1872*0b57cec5SDimitry Andric         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1873*0b57cec5SDimitry Andric         SectionKind::getReadOnly());
1874*0b57cec5SDimitry Andric     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1875*0b57cec5SDimitry Andric   }
1876*0b57cec5SDimitry Andric 
1877*0b57cec5SDimitry Andric   std::string Name = IsCtor ? ".ctors" : ".dtors";
1878*0b57cec5SDimitry Andric   if (Priority != 65535)
1879*0b57cec5SDimitry Andric     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1880*0b57cec5SDimitry Andric 
1881*0b57cec5SDimitry Andric   return Ctx.getAssociativeCOFFSection(
1882*0b57cec5SDimitry Andric       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1883*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ |
1884*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_WRITE,
1885*0b57cec5SDimitry Andric                          SectionKind::getData()),
1886*0b57cec5SDimitry Andric       KeySym, 0);
1887*0b57cec5SDimitry Andric }
1888*0b57cec5SDimitry Andric 
1889*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1890*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1891fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1892fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
1893*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticCtorSection));
1894*0b57cec5SDimitry Andric }
1895*0b57cec5SDimitry Andric 
1896*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1897*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1898fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1899fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
1900*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticDtorSection));
1901*0b57cec5SDimitry Andric }
1902*0b57cec5SDimitry Andric 
1903*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1904*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1905*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1906*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1907*0b57cec5SDimitry Andric   if (T.isOSCygMing())
1908*0b57cec5SDimitry Andric     return nullptr;
1909*0b57cec5SDimitry Andric 
1910*0b57cec5SDimitry Andric   // Our symbols should exist in address space zero, cowardly no-op if
1911*0b57cec5SDimitry Andric   // otherwise.
1912*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1913*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0)
1914*0b57cec5SDimitry Andric     return nullptr;
1915*0b57cec5SDimitry Andric 
1916*0b57cec5SDimitry Andric   // Both ptrtoint instructions must wrap global objects:
1917*0b57cec5SDimitry Andric   // - Only global variables are eligible for image relative relocations.
1918*0b57cec5SDimitry Andric   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1919*0b57cec5SDimitry Andric   // We expect __ImageBase to be a global variable without a section, externally
1920*0b57cec5SDimitry Andric   // defined.
1921*0b57cec5SDimitry Andric   //
1922*0b57cec5SDimitry Andric   // It should look something like this: @__ImageBase = external constant i8
1923*0b57cec5SDimitry Andric   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1924*0b57cec5SDimitry Andric       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1925*0b57cec5SDimitry Andric       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1926*0b57cec5SDimitry Andric       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1927*0b57cec5SDimitry Andric     return nullptr;
1928*0b57cec5SDimitry Andric 
1929*0b57cec5SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1930*0b57cec5SDimitry Andric                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1931*0b57cec5SDimitry Andric                                  getContext());
1932*0b57cec5SDimitry Andric }
1933*0b57cec5SDimitry Andric 
1934*0b57cec5SDimitry Andric static std::string APIntToHexString(const APInt &AI) {
1935*0b57cec5SDimitry Andric   unsigned Width = (AI.getBitWidth() / 8) * 2;
1936fe6060f1SDimitry Andric   std::string HexString = toString(AI, 16, /*Signed=*/false);
19375ffd83dbSDimitry Andric   llvm::transform(HexString, HexString.begin(), tolower);
1938*0b57cec5SDimitry Andric   unsigned Size = HexString.size();
1939*0b57cec5SDimitry Andric   assert(Width >= Size && "hex string is too large!");
1940*0b57cec5SDimitry Andric   HexString.insert(HexString.begin(), Width - Size, '0');
1941*0b57cec5SDimitry Andric 
1942*0b57cec5SDimitry Andric   return HexString;
1943*0b57cec5SDimitry Andric }
1944*0b57cec5SDimitry Andric 
1945*0b57cec5SDimitry Andric static std::string scalarConstantToHexString(const Constant *C) {
1946*0b57cec5SDimitry Andric   Type *Ty = C->getType();
1947*0b57cec5SDimitry Andric   if (isa<UndefValue>(C)) {
1948*0b57cec5SDimitry Andric     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1949*0b57cec5SDimitry Andric   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1950*0b57cec5SDimitry Andric     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1951*0b57cec5SDimitry Andric   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1952*0b57cec5SDimitry Andric     return APIntToHexString(CI->getValue());
1953*0b57cec5SDimitry Andric   } else {
1954*0b57cec5SDimitry Andric     unsigned NumElements;
19555ffd83dbSDimitry Andric     if (auto *VTy = dyn_cast<VectorType>(Ty))
19565ffd83dbSDimitry Andric       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
1957*0b57cec5SDimitry Andric     else
1958*0b57cec5SDimitry Andric       NumElements = Ty->getArrayNumElements();
1959*0b57cec5SDimitry Andric     std::string HexString;
1960*0b57cec5SDimitry Andric     for (int I = NumElements - 1, E = -1; I != E; --I)
1961*0b57cec5SDimitry Andric       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1962*0b57cec5SDimitry Andric     return HexString;
1963*0b57cec5SDimitry Andric   }
1964*0b57cec5SDimitry Andric }
1965*0b57cec5SDimitry Andric 
1966*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1967*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
19685ffd83dbSDimitry Andric     Align &Alignment) const {
1969*0b57cec5SDimitry Andric   if (Kind.isMergeableConst() && C &&
1970*0b57cec5SDimitry Andric       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1971*0b57cec5SDimitry Andric     // This creates comdat sections with the given symbol name, but unless
1972*0b57cec5SDimitry Andric     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1973*0b57cec5SDimitry Andric     // will be created with a null storage class, which makes GNU binutils
1974*0b57cec5SDimitry Andric     // error out.
1975*0b57cec5SDimitry Andric     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1976*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_MEM_READ |
1977*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_LNK_COMDAT;
1978*0b57cec5SDimitry Andric     std::string COMDATSymName;
1979*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4()) {
19805ffd83dbSDimitry Andric       if (Alignment <= 4) {
1981*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19825ffd83dbSDimitry Andric         Alignment = Align(4);
1983*0b57cec5SDimitry Andric       }
1984*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst8()) {
19855ffd83dbSDimitry Andric       if (Alignment <= 8) {
1986*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19875ffd83dbSDimitry Andric         Alignment = Align(8);
1988*0b57cec5SDimitry Andric       }
1989*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst16()) {
1990*0b57cec5SDimitry Andric       // FIXME: These may not be appropriate for non-x86 architectures.
19915ffd83dbSDimitry Andric       if (Alignment <= 16) {
1992*0b57cec5SDimitry Andric         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
19935ffd83dbSDimitry Andric         Alignment = Align(16);
1994*0b57cec5SDimitry Andric       }
1995*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst32()) {
19965ffd83dbSDimitry Andric       if (Alignment <= 32) {
1997*0b57cec5SDimitry Andric         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
19985ffd83dbSDimitry Andric         Alignment = Align(32);
1999*0b57cec5SDimitry Andric       }
2000*0b57cec5SDimitry Andric     }
2001*0b57cec5SDimitry Andric 
2002*0b57cec5SDimitry Andric     if (!COMDATSymName.empty())
2003*0b57cec5SDimitry Andric       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
2004*0b57cec5SDimitry Andric                                          COMDATSymName,
2005*0b57cec5SDimitry Andric                                          COFF::IMAGE_COMDAT_SELECT_ANY);
2006*0b57cec5SDimitry Andric   }
2007*0b57cec5SDimitry Andric 
20085ffd83dbSDimitry Andric   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
20095ffd83dbSDimitry Andric                                                          Alignment);
2010*0b57cec5SDimitry Andric }
2011*0b57cec5SDimitry Andric 
2012*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2013*0b57cec5SDimitry Andric //                                  Wasm
2014*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2015*0b57cec5SDimitry Andric 
2016*0b57cec5SDimitry Andric static const Comdat *getWasmComdat(const GlobalValue *GV) {
2017*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
2018*0b57cec5SDimitry Andric   if (!C)
2019*0b57cec5SDimitry Andric     return nullptr;
2020*0b57cec5SDimitry Andric 
2021*0b57cec5SDimitry Andric   if (C->getSelectionKind() != Comdat::Any)
2022*0b57cec5SDimitry Andric     report_fatal_error("WebAssembly COMDATs only support "
2023*0b57cec5SDimitry Andric                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
2024*0b57cec5SDimitry Andric                        "lowered.");
2025*0b57cec5SDimitry Andric 
2026*0b57cec5SDimitry Andric   return C;
2027*0b57cec5SDimitry Andric }
2028*0b57cec5SDimitry Andric 
2029fe6060f1SDimitry Andric static unsigned getWasmSectionFlags(SectionKind K) {
2030fe6060f1SDimitry Andric   unsigned Flags = 0;
2031fe6060f1SDimitry Andric 
2032fe6060f1SDimitry Andric   if (K.isThreadLocal())
2033fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_TLS;
2034fe6060f1SDimitry Andric 
2035fe6060f1SDimitry Andric   if (K.isMergeableCString())
2036fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_STRINGS;
2037fe6060f1SDimitry Andric 
2038fe6060f1SDimitry Andric   // TODO(sbc): Add suport for K.isMergeableConst()
2039fe6060f1SDimitry Andric 
2040fe6060f1SDimitry Andric   return Flags;
2041fe6060f1SDimitry Andric }
2042fe6060f1SDimitry Andric 
2043*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
2044*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2045*0b57cec5SDimitry Andric   // We don't support explict section names for functions in the wasm object
2046*0b57cec5SDimitry Andric   // format.  Each function has to be in its own unique section.
2047*0b57cec5SDimitry Andric   if (isa<Function>(GO)) {
2048*0b57cec5SDimitry Andric     return SelectSectionForGlobal(GO, Kind, TM);
2049*0b57cec5SDimitry Andric   }
2050*0b57cec5SDimitry Andric 
2051*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
2052*0b57cec5SDimitry Andric 
20535ffd83dbSDimitry Andric   // Certain data sections we treat as named custom sections rather than
20545ffd83dbSDimitry Andric   // segments within the data section.
20555ffd83dbSDimitry Andric   // This could be avoided if all data segements (the wasm sense) were
20565ffd83dbSDimitry Andric   // represented as their own sections (in the llvm sense).
20575ffd83dbSDimitry Andric   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
20585ffd83dbSDimitry Andric   if (Name == ".llvmcmd" || Name == ".llvmbc")
20595ffd83dbSDimitry Andric     Kind = SectionKind::getMetadata();
2060*0b57cec5SDimitry Andric 
2061*0b57cec5SDimitry Andric   StringRef Group = "";
2062*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2063*0b57cec5SDimitry Andric     Group = C->getName();
2064*0b57cec5SDimitry Andric   }
2065*0b57cec5SDimitry Andric 
2066fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2067fe6060f1SDimitry Andric   MCSectionWasm *Section = getContext().getWasmSection(
2068fe6060f1SDimitry Andric       Name, Kind, Flags, Group, MCContext::GenericSectionID);
2069*0b57cec5SDimitry Andric 
2070*0b57cec5SDimitry Andric   return Section;
2071*0b57cec5SDimitry Andric }
2072*0b57cec5SDimitry Andric 
2073*0b57cec5SDimitry Andric static MCSectionWasm *selectWasmSectionForGlobal(
2074*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
2075*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
2076*0b57cec5SDimitry Andric   StringRef Group = "";
2077*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2078*0b57cec5SDimitry Andric     Group = C->getName();
2079*0b57cec5SDimitry Andric   }
2080*0b57cec5SDimitry Andric 
2081*0b57cec5SDimitry Andric   bool UniqueSectionNames = TM.getUniqueSectionNames();
2082*0b57cec5SDimitry Andric   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
2083*0b57cec5SDimitry Andric 
2084*0b57cec5SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
2085*0b57cec5SDimitry Andric     const auto &OptionalPrefix = F->getSectionPrefix();
2086*0b57cec5SDimitry Andric     if (OptionalPrefix)
2087e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2088*0b57cec5SDimitry Andric   }
2089*0b57cec5SDimitry Andric 
2090*0b57cec5SDimitry Andric   if (EmitUniqueSection && UniqueSectionNames) {
2091*0b57cec5SDimitry Andric     Name.push_back('.');
2092*0b57cec5SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, true);
2093*0b57cec5SDimitry Andric   }
2094*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
2095*0b57cec5SDimitry Andric   if (EmitUniqueSection && !UniqueSectionNames) {
2096*0b57cec5SDimitry Andric     UniqueID = *NextUniqueID;
2097*0b57cec5SDimitry Andric     (*NextUniqueID)++;
2098*0b57cec5SDimitry Andric   }
2099*0b57cec5SDimitry Andric 
2100fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2101fe6060f1SDimitry Andric   return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2102*0b57cec5SDimitry Andric }
2103*0b57cec5SDimitry Andric 
2104*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
2105*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2106*0b57cec5SDimitry Andric 
2107*0b57cec5SDimitry Andric   if (Kind.isCommon())
2108*0b57cec5SDimitry Andric     report_fatal_error("mergable sections not supported yet on wasm");
2109*0b57cec5SDimitry Andric 
2110*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
2111*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
2112*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
2113*0b57cec5SDimitry Andric   if (Kind.isText())
2114*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getFunctionSections();
2115*0b57cec5SDimitry Andric   else
2116*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getDataSections();
2117*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
2118*0b57cec5SDimitry Andric 
2119*0b57cec5SDimitry Andric   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2120*0b57cec5SDimitry Andric                                     EmitUniqueSection, &NextUniqueID);
2121*0b57cec5SDimitry Andric }
2122*0b57cec5SDimitry Andric 
2123*0b57cec5SDimitry Andric bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
2124*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2125*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
2126*0b57cec5SDimitry Andric   // that can be marked non-executable.
2127*0b57cec5SDimitry Andric   return false;
2128*0b57cec5SDimitry Andric }
2129*0b57cec5SDimitry Andric 
2130*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
2131*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
2132*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
2133*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
2134*0b57cec5SDimitry Andric   // functions.
2135*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2136*0b57cec5SDimitry Andric     return nullptr;
2137*0b57cec5SDimitry Andric 
2138*0b57cec5SDimitry Andric   // Basic sanity checks.
2139*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2140*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2141*0b57cec5SDimitry Andric       RHS->isThreadLocal())
2142*0b57cec5SDimitry Andric     return nullptr;
2143*0b57cec5SDimitry Andric 
2144*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
2145*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
2146*0b57cec5SDimitry Andric                               getContext()),
2147*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
2148*0b57cec5SDimitry Andric }
2149*0b57cec5SDimitry Andric 
2150*0b57cec5SDimitry Andric void TargetLoweringObjectFileWasm::InitializeWasm() {
2151*0b57cec5SDimitry Andric   StaticCtorSection =
2152*0b57cec5SDimitry Andric       getContext().getWasmSection(".init_array", SectionKind::getData());
2153*0b57cec5SDimitry Andric 
2154*0b57cec5SDimitry Andric   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2155*0b57cec5SDimitry Andric   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2156*0b57cec5SDimitry Andric   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2157*0b57cec5SDimitry Andric }
2158*0b57cec5SDimitry Andric 
2159*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2160*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2161*0b57cec5SDimitry Andric   return Priority == UINT16_MAX ?
2162*0b57cec5SDimitry Andric          StaticCtorSection :
2163*0b57cec5SDimitry Andric          getContext().getWasmSection(".init_array." + utostr(Priority),
2164*0b57cec5SDimitry Andric                                      SectionKind::getData());
2165*0b57cec5SDimitry Andric }
2166*0b57cec5SDimitry Andric 
2167*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2168*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2169*0b57cec5SDimitry Andric   llvm_unreachable("@llvm.global_dtors should have been lowered already");
2170*0b57cec5SDimitry Andric   return nullptr;
2171*0b57cec5SDimitry Andric }
21728bcb0991SDimitry Andric 
21738bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
21748bcb0991SDimitry Andric //                                  XCOFF
21758bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
2176e8d8bef9SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2177e8d8bef9SDimitry Andric     const MachineFunction *MF) {
2178e8d8bef9SDimitry Andric   if (!MF->getLandingPads().empty())
2179e8d8bef9SDimitry Andric     return true;
2180e8d8bef9SDimitry Andric 
2181e8d8bef9SDimitry Andric   const Function &F = MF->getFunction();
2182e8d8bef9SDimitry Andric   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2183e8d8bef9SDimitry Andric     return false;
2184e8d8bef9SDimitry Andric 
2185fe6060f1SDimitry Andric   const GlobalValue *Per =
2186fe6060f1SDimitry Andric       dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2187fe6060f1SDimitry Andric   assert(Per && "Personality routine is not a GlobalValue type.");
2188e8d8bef9SDimitry Andric   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2189e8d8bef9SDimitry Andric     return false;
2190e8d8bef9SDimitry Andric 
2191e8d8bef9SDimitry Andric   return true;
2192e8d8bef9SDimitry Andric }
2193e8d8bef9SDimitry Andric 
2194fe6060f1SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
2195fe6060f1SDimitry Andric     const MachineFunction *MF) {
2196fe6060f1SDimitry Andric   const Function &F = MF->getFunction();
2197fe6060f1SDimitry Andric   if (!F.hasStackProtectorFnAttr())
2198fe6060f1SDimitry Andric     return false;
2199fe6060f1SDimitry Andric   // FIXME: check presence of canary word
2200fe6060f1SDimitry Andric   // There are cases that the stack protectors are not really inserted even if
2201fe6060f1SDimitry Andric   // the attributes are on.
2202fe6060f1SDimitry Andric   return true;
2203fe6060f1SDimitry Andric }
2204fe6060f1SDimitry Andric 
2205e8d8bef9SDimitry Andric MCSymbol *
2206e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2207e8d8bef9SDimitry Andric   return MF->getMMI().getContext().getOrCreateSymbol(
2208e8d8bef9SDimitry Andric       "__ehinfo." + Twine(MF->getFunctionNumber()));
2209e8d8bef9SDimitry Andric }
2210e8d8bef9SDimitry Andric 
22115ffd83dbSDimitry Andric MCSymbol *
22125ffd83dbSDimitry Andric TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
22135ffd83dbSDimitry Andric                                                const TargetMachine &TM) const {
22145ffd83dbSDimitry Andric   // We always use a qualname symbol for a GV that represents
22155ffd83dbSDimitry Andric   // a declaration, a function descriptor, or a common symbol.
2216e8d8bef9SDimitry Andric   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2217e8d8bef9SDimitry Andric   // also return a qualname so that a label symbol could be avoided.
22185ffd83dbSDimitry Andric   // It is inherently ambiguous when the GO represents the address of a
22195ffd83dbSDimitry Andric   // function, as the GO could either represent a function descriptor or a
22205ffd83dbSDimitry Andric   // function entry point. We choose to always return a function descriptor
22215ffd83dbSDimitry Andric   // here.
22225ffd83dbSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2223fe6060f1SDimitry Andric     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2224fe6060f1SDimitry Andric       if (GVar->hasAttribute("toc-data"))
2225fe6060f1SDimitry Andric         return cast<MCSectionXCOFF>(
2226fe6060f1SDimitry Andric                    SectionForGlobal(GVar, SectionKind::getData(), TM))
2227fe6060f1SDimitry Andric             ->getQualNameSymbol();
2228fe6060f1SDimitry Andric 
22295ffd83dbSDimitry Andric     if (GO->isDeclarationForLinker())
22305ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
22315ffd83dbSDimitry Andric           ->getQualNameSymbol();
22325ffd83dbSDimitry Andric 
22335ffd83dbSDimitry Andric     SectionKind GOKind = getKindForGlobal(GO, TM);
22345ffd83dbSDimitry Andric     if (GOKind.isText())
22355ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(
22365ffd83dbSDimitry Andric                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
22375ffd83dbSDimitry Andric           ->getQualNameSymbol();
2238fe6060f1SDimitry Andric     if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2239fe6060f1SDimitry Andric         GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
22405ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
22415ffd83dbSDimitry Andric           ->getQualNameSymbol();
22425ffd83dbSDimitry Andric   }
22435ffd83dbSDimitry Andric 
22445ffd83dbSDimitry Andric   // For all other cases, fall back to getSymbol to return the unqualified name.
22455ffd83dbSDimitry Andric   return nullptr;
22465ffd83dbSDimitry Andric }
22475ffd83dbSDimitry Andric 
22488bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
22498bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2250e8d8bef9SDimitry Andric   if (!GO->hasSection())
2251e8d8bef9SDimitry Andric     report_fatal_error("#pragma clang section is not yet supported");
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   StringRef SectionName = GO->getSection();
2254fe6060f1SDimitry Andric 
2255fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2256fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2257fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data"))
2258fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2259fe6060f1SDimitry Andric           SectionName, Kind,
2260fe6060f1SDimitry Andric           XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
2261fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2262fe6060f1SDimitry Andric 
2263e8d8bef9SDimitry Andric   XCOFF::StorageMappingClass MappingClass;
2264e8d8bef9SDimitry Andric   if (Kind.isText())
2265e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_PR;
2266e8d8bef9SDimitry Andric   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2267e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RW;
2268e8d8bef9SDimitry Andric   else if (Kind.isReadOnly())
2269e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RO;
2270e8d8bef9SDimitry Andric   else
2271e8d8bef9SDimitry Andric     report_fatal_error("XCOFF other section types not yet implemented.");
2272e8d8bef9SDimitry Andric 
2273fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2274fe6060f1SDimitry Andric       SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2275fe6060f1SDimitry Andric       /* MultiSymbolsAllowed*/ true);
22768bcb0991SDimitry Andric }
22778bcb0991SDimitry Andric 
22785ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
22795ffd83dbSDimitry Andric     const GlobalObject *GO, const TargetMachine &TM) const {
22805ffd83dbSDimitry Andric   assert(GO->isDeclarationForLinker() &&
22815ffd83dbSDimitry Andric          "Tried to get ER section for a defined global.");
22825ffd83dbSDimitry Andric 
22835ffd83dbSDimitry Andric   SmallString<128> Name;
22845ffd83dbSDimitry Andric   getNameWithPrefix(Name, GO, TM);
22855ffd83dbSDimitry Andric 
2286fe6060f1SDimitry Andric   XCOFF::StorageMappingClass SMC =
2287fe6060f1SDimitry Andric       isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2288fe6060f1SDimitry Andric   if (GO->isThreadLocal())
2289fe6060f1SDimitry Andric     SMC = XCOFF::XMC_UL;
2290fe6060f1SDimitry Andric 
22915ffd83dbSDimitry Andric   // Externals go into a csect of type ER.
22925ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2293fe6060f1SDimitry Andric       Name, SectionKind::getMetadata(),
2294fe6060f1SDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
22955ffd83dbSDimitry Andric }
22965ffd83dbSDimitry Andric 
22978bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
22988bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2299fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2300fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2301fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data")) {
23028bcb0991SDimitry Andric       SmallString<128> Name;
23038bcb0991SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23048bcb0991SDimitry Andric       return getContext().getXCOFFSection(
2305fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
2306fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2307fe6060f1SDimitry Andric     }
2308fe6060f1SDimitry Andric 
2309fe6060f1SDimitry Andric   // Common symbols go into a csect with matching name which will get mapped
2310fe6060f1SDimitry Andric   // into the .bss section.
2311fe6060f1SDimitry Andric   // Zero-initialized local TLS symbols go into a csect with matching name which
2312fe6060f1SDimitry Andric   // will get mapped into the .tbss section.
2313fe6060f1SDimitry Andric   if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2314fe6060f1SDimitry Andric     SmallString<128> Name;
2315fe6060f1SDimitry Andric     getNameWithPrefix(Name, GO, TM);
2316fe6060f1SDimitry Andric     XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2317fe6060f1SDimitry Andric                                      : Kind.isCommon() ? XCOFF::XMC_RW
2318fe6060f1SDimitry Andric                                                        : XCOFF::XMC_UL;
2319fe6060f1SDimitry Andric     return getContext().getXCOFFSection(
2320fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
23218bcb0991SDimitry Andric   }
23228bcb0991SDimitry Andric 
2323480093f4SDimitry Andric   if (Kind.isMergeableCString()) {
23245ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2325480093f4SDimitry Andric         cast<GlobalVariable>(GO));
2326480093f4SDimitry Andric 
2327480093f4SDimitry Andric     unsigned EntrySize = getEntrySizeForKind(Kind);
2328480093f4SDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2329480093f4SDimitry Andric     SmallString<128> Name;
23305ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
2331480093f4SDimitry Andric 
2332e8d8bef9SDimitry Andric     if (TM.getDataSections())
2333e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2334e8d8bef9SDimitry Andric 
2335480093f4SDimitry Andric     return getContext().getXCOFFSection(
2336fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
2337e8d8bef9SDimitry Andric         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2338480093f4SDimitry Andric   }
2339480093f4SDimitry Andric 
2340e8d8bef9SDimitry Andric   if (Kind.isText()) {
2341e8d8bef9SDimitry Andric     if (TM.getFunctionSections()) {
2342e8d8bef9SDimitry Andric       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2343e8d8bef9SDimitry Andric           ->getRepresentedCsect();
2344e8d8bef9SDimitry Andric     }
23458bcb0991SDimitry Andric     return TextSection;
2346e8d8bef9SDimitry Andric   }
23478bcb0991SDimitry Andric 
2348e8d8bef9SDimitry Andric   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2349e8d8bef9SDimitry Andric   // user may want to have read-only data with relocations placed into a
2350e8d8bef9SDimitry Andric   // read-only section by the compiler.
2351e8d8bef9SDimitry Andric   // For BSS kind, zero initialized data must be emitted to the .data section
2352e8d8bef9SDimitry Andric   // because external linkage control sections that get mapped to the .bss
2353e8d8bef9SDimitry Andric   // section will be linked as tentative defintions, which is only appropriate
2354e8d8bef9SDimitry Andric   // for SectionKind::Common.
2355e8d8bef9SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2356e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2357e8d8bef9SDimitry Andric       SmallString<128> Name;
2358e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2359fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2360fe6060f1SDimitry Andric           Name, SectionKind::getData(),
2361fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
2362e8d8bef9SDimitry Andric     }
23638bcb0991SDimitry Andric     return DataSection;
2364e8d8bef9SDimitry Andric   }
23658bcb0991SDimitry Andric 
2366e8d8bef9SDimitry Andric   if (Kind.isReadOnly()) {
2367e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2368e8d8bef9SDimitry Andric       SmallString<128> Name;
2369e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2370fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2371fe6060f1SDimitry Andric           Name, SectionKind::getReadOnly(),
2372fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2373e8d8bef9SDimitry Andric     }
2374480093f4SDimitry Andric     return ReadOnlySection;
2375e8d8bef9SDimitry Andric   }
2376480093f4SDimitry Andric 
2377fe6060f1SDimitry Andric   // External/weak TLS data and initialized local TLS data are not eligible
2378fe6060f1SDimitry Andric   // to be put into common csect. If data sections are enabled, thread
2379fe6060f1SDimitry Andric   // data are emitted into separate sections. Otherwise, thread data
2380fe6060f1SDimitry Andric   // are emitted into the .tdata section.
2381fe6060f1SDimitry Andric   if (Kind.isThreadLocal()) {
2382fe6060f1SDimitry Andric     if (TM.getDataSections()) {
2383fe6060f1SDimitry Andric       SmallString<128> Name;
2384fe6060f1SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2385fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2386fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
2387fe6060f1SDimitry Andric     }
2388fe6060f1SDimitry Andric     return TLSDataSection;
2389fe6060f1SDimitry Andric   }
2390fe6060f1SDimitry Andric 
23918bcb0991SDimitry Andric   report_fatal_error("XCOFF other section types not yet implemented.");
23928bcb0991SDimitry Andric }
23938bcb0991SDimitry Andric 
2394480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2395480093f4SDimitry Andric     const Function &F, const TargetMachine &TM) const {
2396480093f4SDimitry Andric   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2397e8d8bef9SDimitry Andric 
2398e8d8bef9SDimitry Andric   if (!TM.getFunctionSections())
2399480093f4SDimitry Andric     return ReadOnlySection;
2400e8d8bef9SDimitry Andric 
2401e8d8bef9SDimitry Andric   // If the function can be removed, produce a unique section so that
2402e8d8bef9SDimitry Andric   // the table doesn't prevent the removal.
2403e8d8bef9SDimitry Andric   SmallString<128> NameStr(".rodata.jmp..");
2404e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, &F, TM);
2405fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2406fe6060f1SDimitry Andric       NameStr, SectionKind::getReadOnly(),
2407fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2408480093f4SDimitry Andric }
2409480093f4SDimitry Andric 
24108bcb0991SDimitry Andric bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
24118bcb0991SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2412480093f4SDimitry Andric   return false;
2413480093f4SDimitry Andric }
2414480093f4SDimitry Andric 
2415480093f4SDimitry Andric /// Given a mergeable constant with the specified size and relocation
2416480093f4SDimitry Andric /// information, return a section that it should be placed in.
2417480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2418480093f4SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
24195ffd83dbSDimitry Andric     Align &Alignment) const {
2420480093f4SDimitry Andric   //TODO: Enable emiting constant pool to unique sections when we support it.
2421480093f4SDimitry Andric   return ReadOnlySection;
24228bcb0991SDimitry Andric }
24238bcb0991SDimitry Andric 
24248bcb0991SDimitry Andric void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
24258bcb0991SDimitry Andric                                                const TargetMachine &TgtM) {
24268bcb0991SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2427e8d8bef9SDimitry Andric   TTypeEncoding =
2428e8d8bef9SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2429e8d8bef9SDimitry Andric       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2430e8d8bef9SDimitry Andric                                             : dwarf::DW_EH_PE_sdata8);
24318bcb0991SDimitry Andric   PersonalityEncoding = 0;
24328bcb0991SDimitry Andric   LSDAEncoding = 0;
2433e8d8bef9SDimitry Andric   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
24348bcb0991SDimitry Andric }
24358bcb0991SDimitry Andric 
24368bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
24378bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2438e8d8bef9SDimitry Andric   report_fatal_error("no static constructor section on AIX");
24398bcb0991SDimitry Andric }
24408bcb0991SDimitry Andric 
24418bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
24428bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2443e8d8bef9SDimitry Andric   report_fatal_error("no static destructor section on AIX");
24448bcb0991SDimitry Andric }
24458bcb0991SDimitry Andric 
24468bcb0991SDimitry Andric const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
24478bcb0991SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
24488bcb0991SDimitry Andric     const TargetMachine &TM) const {
24498bcb0991SDimitry Andric   report_fatal_error("XCOFF not yet implemented.");
24508bcb0991SDimitry Andric }
24518bcb0991SDimitry Andric 
2452e8d8bef9SDimitry Andric XCOFF::StorageClass
2453e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2454e8d8bef9SDimitry Andric   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2455e8d8bef9SDimitry Andric 
2456e8d8bef9SDimitry Andric   switch (GV->getLinkage()) {
24578bcb0991SDimitry Andric   case GlobalValue::InternalLinkage:
2458480093f4SDimitry Andric   case GlobalValue::PrivateLinkage:
24598bcb0991SDimitry Andric     return XCOFF::C_HIDEXT;
24608bcb0991SDimitry Andric   case GlobalValue::ExternalLinkage:
24618bcb0991SDimitry Andric   case GlobalValue::CommonLinkage:
24625ffd83dbSDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
24638bcb0991SDimitry Andric     return XCOFF::C_EXT;
24648bcb0991SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
24655ffd83dbSDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
24665ffd83dbSDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
24675ffd83dbSDimitry Andric   case GlobalValue::WeakAnyLinkage:
24685ffd83dbSDimitry Andric   case GlobalValue::WeakODRLinkage:
24698bcb0991SDimitry Andric     return XCOFF::C_WEAKEXT;
24705ffd83dbSDimitry Andric   case GlobalValue::AppendingLinkage:
24718bcb0991SDimitry Andric     report_fatal_error(
24725ffd83dbSDimitry Andric         "There is no mapping that implements AppendingLinkage for XCOFF.");
24738bcb0991SDimitry Andric   }
24745ffd83dbSDimitry Andric   llvm_unreachable("Unknown linkage type!");
24755ffd83dbSDimitry Andric }
24765ffd83dbSDimitry Andric 
24775ffd83dbSDimitry Andric MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2478e8d8bef9SDimitry Andric     const GlobalValue *Func, const TargetMachine &TM) const {
2479e8d8bef9SDimitry Andric   assert(
2480e8d8bef9SDimitry Andric       (isa<Function>(Func) ||
2481e8d8bef9SDimitry Andric        (isa<GlobalAlias>(Func) &&
2482e8d8bef9SDimitry Andric         isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) &&
2483e8d8bef9SDimitry Andric       "Func must be a function or an alias which has a function as base "
2484e8d8bef9SDimitry Andric       "object.");
2485e8d8bef9SDimitry Andric 
24865ffd83dbSDimitry Andric   SmallString<128> NameStr;
24875ffd83dbSDimitry Andric   NameStr.push_back('.');
2488e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, Func, TM);
2489e8d8bef9SDimitry Andric 
2490e8d8bef9SDimitry Andric   // When -function-sections is enabled and explicit section is not specified,
2491e8d8bef9SDimitry Andric   // it's not necessary to emit function entry point label any more. We will use
2492e8d8bef9SDimitry Andric   // function entry point csect instead. And for function delcarations, the
2493e8d8bef9SDimitry Andric   // undefined symbols gets treated as csect with XTY_ER property.
2494e8d8bef9SDimitry Andric   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2495e8d8bef9SDimitry Andric        Func->isDeclaration()) &&
2496e8d8bef9SDimitry Andric       isa<Function>(Func)) {
2497e8d8bef9SDimitry Andric     return getContext()
2498fe6060f1SDimitry Andric         .getXCOFFSection(
2499fe6060f1SDimitry Andric             NameStr, SectionKind::getText(),
2500fe6060f1SDimitry Andric             XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
2501fe6060f1SDimitry Andric                                                       ? XCOFF::XTY_ER
2502fe6060f1SDimitry Andric                                                       : XCOFF::XTY_SD))
2503e8d8bef9SDimitry Andric         ->getQualNameSymbol();
2504e8d8bef9SDimitry Andric   }
2505e8d8bef9SDimitry Andric 
25065ffd83dbSDimitry Andric   return getContext().getOrCreateSymbol(NameStr);
25075ffd83dbSDimitry Andric }
25085ffd83dbSDimitry Andric 
25095ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
25105ffd83dbSDimitry Andric     const Function *F, const TargetMachine &TM) const {
25115ffd83dbSDimitry Andric   SmallString<128> NameStr;
25125ffd83dbSDimitry Andric   getNameWithPrefix(NameStr, F, TM);
2513fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2514fe6060f1SDimitry Andric       NameStr, SectionKind::getData(),
2515fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
25165ffd83dbSDimitry Andric }
25175ffd83dbSDimitry Andric 
25185ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2519e8d8bef9SDimitry Andric     const MCSymbol *Sym, const TargetMachine &TM) const {
2520e8d8bef9SDimitry Andric   // Use TE storage-mapping class when large code model is enabled so that
2521e8d8bef9SDimitry Andric   // the chance of needing -bbigtoc is decreased.
25225ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2523fe6060f1SDimitry Andric       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2524fe6060f1SDimitry Andric       XCOFF::CsectProperties(
2525e8d8bef9SDimitry Andric           TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
2526fe6060f1SDimitry Andric           XCOFF::XTY_SD));
2527fe6060f1SDimitry Andric }
2528fe6060f1SDimitry Andric 
2529fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
2530fe6060f1SDimitry Andric //                                  GOFF
2531fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
2532fe6060f1SDimitry Andric TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF()
2533fe6060f1SDimitry Andric     : TargetLoweringObjectFile() {}
2534fe6060f1SDimitry Andric 
2535fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
2536fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2537fe6060f1SDimitry Andric   return SelectSectionForGlobal(GO, Kind, TM);
2538fe6060f1SDimitry Andric }
2539fe6060f1SDimitry Andric 
2540fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
2541fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2542fe6060f1SDimitry Andric   auto *Symbol = TM.getSymbol(GO);
2543fe6060f1SDimitry Andric   if (Kind.isBSS())
2544fe6060f1SDimitry Andric     return getContext().getGOFFSection(Symbol->getName(),
2545fe6060f1SDimitry Andric                                        SectionKind::getBSS());
2546fe6060f1SDimitry Andric 
2547fe6060f1SDimitry Andric   return getContext().getObjectFileInfo()->getTextSection();
25488bcb0991SDimitry Andric }
2549