10b57cec5SDimitry Andric //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements classes used to handle lowerings specific to common
100b57cec5SDimitry Andric // object file formats.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
180b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
200b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
210b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
220b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
230b57cec5SDimitry Andric #include "llvm/BinaryFormat/MachO.h"
245f7ddb14SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
25af732203SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
265ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
275ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
300b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
310b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
320b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
330b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
345ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
355ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
360b57cec5SDimitry Andric #include "llvm/IR/Function.h"
370b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
380b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
390b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
400b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
410b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
420b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
430b57cec5SDimitry Andric #include "llvm/IR/Module.h"
44af732203SDimitry Andric #include "llvm/IR/PseudoProbe.h"
450b57cec5SDimitry Andric #include "llvm/IR/Type.h"
460b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
470b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
480b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
490b57cec5SDimitry Andric #include "llvm/MC/MCSectionCOFF.h"
500b57cec5SDimitry Andric #include "llvm/MC/MCSectionELF.h"
515f7ddb14SDimitry Andric #include "llvm/MC/MCSectionGOFF.h"
520b57cec5SDimitry Andric #include "llvm/MC/MCSectionMachO.h"
530b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
548bcb0991SDimitry Andric #include "llvm/MC/MCSectionXCOFF.h"
550b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
560b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
570b57cec5SDimitry Andric #include "llvm/MC/MCSymbolELF.h"
580b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
590b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
600b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
610b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
620b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
630b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
645ffd83dbSDimitry Andric #include "llvm/Support/Format.h"
650b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
660b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
670b57cec5SDimitry Andric #include <cassert>
680b57cec5SDimitry Andric #include <string>
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric using namespace llvm;
710b57cec5SDimitry Andric using namespace dwarf;
720b57cec5SDimitry Andric 
GetObjCImageInfo(Module & M,unsigned & Version,unsigned & Flags,StringRef & Section)730b57cec5SDimitry Andric static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
740b57cec5SDimitry Andric                              StringRef &Section) {
750b57cec5SDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
760b57cec5SDimitry Andric   M.getModuleFlagsMetadata(ModuleFlags);
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   for (const auto &MFE: ModuleFlags) {
790b57cec5SDimitry Andric     // Ignore flags with 'Require' behaviour.
800b57cec5SDimitry Andric     if (MFE.Behavior == Module::Require)
810b57cec5SDimitry Andric       continue;
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric     StringRef Key = MFE.Key->getString();
840b57cec5SDimitry Andric     if (Key == "Objective-C Image Info Version") {
850b57cec5SDimitry Andric       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
860b57cec5SDimitry Andric     } else if (Key == "Objective-C Garbage Collection" ||
870b57cec5SDimitry Andric                Key == "Objective-C GC Only" ||
880b57cec5SDimitry Andric                Key == "Objective-C Is Simulated" ||
890b57cec5SDimitry Andric                Key == "Objective-C Class Properties" ||
900b57cec5SDimitry Andric                Key == "Objective-C Image Swift Version") {
910b57cec5SDimitry Andric       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
920b57cec5SDimitry Andric     } else if (Key == "Objective-C Image Info Section") {
930b57cec5SDimitry Andric       Section = cast<MDString>(MFE.Val)->getString();
940b57cec5SDimitry 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     }
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1080b57cec5SDimitry Andric //                                  ELF
1090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1100b57cec5SDimitry Andric 
TargetLoweringObjectFileELF()111af732203SDimitry Andric TargetLoweringObjectFileELF::TargetLoweringObjectFileELF()
112af732203SDimitry Andric     : TargetLoweringObjectFile() {
113af732203SDimitry Andric   SupportDSOLocalEquivalentLowering = true;
114af732203SDimitry Andric }
115af732203SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TgtM)1160b57cec5SDimitry Andric void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
1170b57cec5SDimitry Andric                                              const TargetMachine &TgtM) {
1180b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   CodeModel::Model CM = TgtM.getCodeModel();
1215ffd83dbSDimitry Andric   InitializeELF(TgtM.Options.UseInitArray);
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   switch (TgtM.getTargetTriple().getArch()) {
1240b57cec5SDimitry Andric   case Triple::arm:
1250b57cec5SDimitry Andric   case Triple::armeb:
1260b57cec5SDimitry Andric   case Triple::thumb:
1270b57cec5SDimitry Andric   case Triple::thumbeb:
1280b57cec5SDimitry Andric     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
1290b57cec5SDimitry Andric       break;
1300b57cec5SDimitry Andric     // Fallthrough if not using EHABI
1310b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
1320b57cec5SDimitry Andric   case Triple::ppc:
133af732203SDimitry Andric   case Triple::ppcle:
1340b57cec5SDimitry Andric   case Triple::x86:
1350b57cec5SDimitry Andric     PersonalityEncoding = isPositionIndependent()
1360b57cec5SDimitry Andric                               ? dwarf::DW_EH_PE_indirect |
1370b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_pcrel |
1380b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_sdata4
1390b57cec5SDimitry Andric                               : dwarf::DW_EH_PE_absptr;
1400b57cec5SDimitry Andric     LSDAEncoding = isPositionIndependent()
1410b57cec5SDimitry Andric                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
1420b57cec5SDimitry Andric                        : dwarf::DW_EH_PE_absptr;
1430b57cec5SDimitry Andric     TTypeEncoding = isPositionIndependent()
1440b57cec5SDimitry Andric                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
1450b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata4
1460b57cec5SDimitry Andric                         : dwarf::DW_EH_PE_absptr;
1470b57cec5SDimitry Andric     break;
1480b57cec5SDimitry Andric   case Triple::x86_64:
1490b57cec5SDimitry Andric     if (isPositionIndependent()) {
1500b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
1510b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
1520b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
1530b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
1540b57cec5SDimitry Andric         (CM == CodeModel::Small
1550b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
1560b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
1570b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
1585f7ddb14SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
1590b57cec5SDimitry Andric     } else {
1600b57cec5SDimitry Andric       PersonalityEncoding =
1610b57cec5SDimitry Andric         (CM == CodeModel::Small || CM == CodeModel::Medium)
1620b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
1630b57cec5SDimitry Andric       LSDAEncoding = (CM == CodeModel::Small)
1640b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
1650b57cec5SDimitry Andric       TTypeEncoding = (CM == CodeModel::Small)
1660b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
1670b57cec5SDimitry Andric     }
1680b57cec5SDimitry Andric     break;
1690b57cec5SDimitry Andric   case Triple::hexagon:
1700b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
1710b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
1720b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
1730b57cec5SDimitry Andric     if (isPositionIndependent()) {
1740b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
1750b57cec5SDimitry Andric       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
1760b57cec5SDimitry Andric       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
1770b57cec5SDimitry Andric     }
1780b57cec5SDimitry Andric     break;
1790b57cec5SDimitry Andric   case Triple::aarch64:
1800b57cec5SDimitry Andric   case Triple::aarch64_be:
1818bcb0991SDimitry Andric   case Triple::aarch64_32:
1820b57cec5SDimitry Andric     // The small model guarantees static code/data size < 4GB, but not where it
1830b57cec5SDimitry Andric     // will be in memory. Most of these could end up >2GB away so even a signed
1840b57cec5SDimitry Andric     // pc-relative 32-bit address is insufficient, theoretically.
1850b57cec5SDimitry Andric     if (isPositionIndependent()) {
186af732203SDimitry Andric       // ILP32 uses sdata4 instead of sdata8
187af732203SDimitry Andric       if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
188af732203SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
189af732203SDimitry Andric                               dwarf::DW_EH_PE_sdata4;
190af732203SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
191af732203SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
192af732203SDimitry Andric                         dwarf::DW_EH_PE_sdata4;
193af732203SDimitry Andric       } else {
1940b57cec5SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
1950b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata8;
1960b57cec5SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
1970b57cec5SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
1980b57cec5SDimitry Andric                         dwarf::DW_EH_PE_sdata8;
199af732203SDimitry Andric       }
2000b57cec5SDimitry Andric     } else {
2010b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
2020b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
2030b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
2040b57cec5SDimitry Andric     }
2050b57cec5SDimitry Andric     break;
2060b57cec5SDimitry Andric   case Triple::lanai:
2070b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
2080b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
2090b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
2100b57cec5SDimitry Andric     break;
2110b57cec5SDimitry Andric   case Triple::mips:
2120b57cec5SDimitry Andric   case Triple::mipsel:
2130b57cec5SDimitry Andric   case Triple::mips64:
2140b57cec5SDimitry Andric   case Triple::mips64el:
2150b57cec5SDimitry Andric     // MIPS uses indirect pointer to refer personality functions and types, so
2160b57cec5SDimitry Andric     // that the eh_frame section can be read-only. DW.ref.personality will be
2170b57cec5SDimitry Andric     // generated for relocation.
2180b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
2190b57cec5SDimitry Andric     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
2200b57cec5SDimitry Andric     //        identify N64 from just a triple.
2210b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2220b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
2230b57cec5SDimitry Andric     // We don't support PC-relative LSDA references in GAS so we use the default
2240b57cec5SDimitry Andric     // DW_EH_PE_absptr for those.
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric     // FreeBSD must be explicit about the data size and using pcrel since it's
2270b57cec5SDimitry Andric     // assembler/linker won't do the automatic conversion that the Linux tools
2280b57cec5SDimitry Andric     // do.
2290b57cec5SDimitry Andric     if (TgtM.getTargetTriple().isOSFreeBSD()) {
2300b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2310b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2320b57cec5SDimitry Andric     }
2330b57cec5SDimitry Andric     break;
2340b57cec5SDimitry Andric   case Triple::ppc64:
2350b57cec5SDimitry Andric   case Triple::ppc64le:
2360b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2370b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
2380b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
2390b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2400b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
2410b57cec5SDimitry Andric     break;
2420b57cec5SDimitry Andric   case Triple::sparcel:
2430b57cec5SDimitry Andric   case Triple::sparc:
2440b57cec5SDimitry Andric     if (isPositionIndependent()) {
2450b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2460b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2470b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2480b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2490b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2500b57cec5SDimitry Andric     } else {
2510b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
2520b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
2530b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
2540b57cec5SDimitry Andric     }
2550b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
2560b57cec5SDimitry Andric     break;
2570b57cec5SDimitry Andric   case Triple::riscv32:
2580b57cec5SDimitry Andric   case Triple::riscv64:
2590b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2600b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2610b57cec5SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
2620b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2630b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
2640b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
2650b57cec5SDimitry Andric     break;
2660b57cec5SDimitry Andric   case Triple::sparcv9:
2670b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2680b57cec5SDimitry Andric     if (isPositionIndependent()) {
2690b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2700b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2710b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2720b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2730b57cec5SDimitry Andric     } else {
2740b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
2750b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
2760b57cec5SDimitry Andric     }
2770b57cec5SDimitry Andric     break;
2780b57cec5SDimitry Andric   case Triple::systemz:
2790b57cec5SDimitry Andric     // All currently-defined code models guarantee that 4-byte PC-relative
2800b57cec5SDimitry Andric     // values will be in range.
2810b57cec5SDimitry Andric     if (isPositionIndependent()) {
2820b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2830b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2840b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
2850b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
2860b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
2870b57cec5SDimitry Andric     } else {
2880b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
2890b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
2900b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
2910b57cec5SDimitry Andric     }
2920b57cec5SDimitry Andric     break;
2930b57cec5SDimitry Andric   default:
2940b57cec5SDimitry Andric     break;
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
getModuleMetadata(Module & M)2985f7ddb14SDimitry Andric void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
2995f7ddb14SDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
3005f7ddb14SDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
3015f7ddb14SDimitry Andric   for (GlobalValue *GV : Vec)
3025f7ddb14SDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
3035f7ddb14SDimitry Andric       Used.insert(GO);
3045f7ddb14SDimitry Andric }
3055f7ddb14SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const3060b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
3070b57cec5SDimitry Andric                                                      Module &M) const {
3080b57cec5SDimitry Andric   auto &C = getContext();
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
3110b57cec5SDimitry Andric     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
3120b57cec5SDimitry Andric                               ELF::SHF_EXCLUDE);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     Streamer.SwitchSection(S);
3150b57cec5SDimitry Andric 
316480093f4SDimitry Andric     for (const auto *Operand : LinkerOptions->operands()) {
3170b57cec5SDimitry Andric       if (cast<MDNode>(Operand)->getNumOperands() != 2)
3180b57cec5SDimitry Andric         report_fatal_error("invalid llvm.linker.options");
3190b57cec5SDimitry Andric       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
3205ffd83dbSDimitry Andric         Streamer.emitBytes(cast<MDString>(Option)->getString());
3215ffd83dbSDimitry Andric         Streamer.emitInt8(0);
3220b57cec5SDimitry Andric       }
3230b57cec5SDimitry Andric     }
3240b57cec5SDimitry Andric   }
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
3270b57cec5SDimitry Andric     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
3285f7ddb14SDimitry Andric                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric     Streamer.SwitchSection(S);
3310b57cec5SDimitry Andric 
332480093f4SDimitry Andric     for (const auto *Operand : DependentLibraries->operands()) {
3335ffd83dbSDimitry Andric       Streamer.emitBytes(
3340b57cec5SDimitry Andric           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
3355ffd83dbSDimitry Andric       Streamer.emitInt8(0);
3360b57cec5SDimitry Andric     }
3370b57cec5SDimitry Andric   }
3380b57cec5SDimitry Andric 
339af732203SDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
340af732203SDimitry Andric     // Emit a descriptor for every function including functions that have an
341af732203SDimitry Andric     // available external linkage. We may not want this for imported functions
342af732203SDimitry Andric     // that has code in another thinLTO module but we don't have a good way to
343af732203SDimitry Andric     // tell them apart from inline functions defined in header files. Therefore
344af732203SDimitry Andric     // we put each descriptor in a separate comdat section and rely on the
345af732203SDimitry Andric     // linker to deduplicate.
346af732203SDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
347af732203SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
348af732203SDimitry Andric       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
349af732203SDimitry Andric       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
350af732203SDimitry Andric       auto *Name = cast<MDString>(MD->getOperand(2));
351af732203SDimitry Andric       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
352af732203SDimitry Andric           TM->getFunctionSections() ? Name->getString() : StringRef());
353af732203SDimitry Andric 
354af732203SDimitry Andric       Streamer.SwitchSection(S);
355af732203SDimitry Andric       Streamer.emitInt64(GUID->getZExtValue());
356af732203SDimitry Andric       Streamer.emitInt64(Hash->getZExtValue());
357af732203SDimitry Andric       Streamer.emitULEB128IntValue(Name->getString().size());
358af732203SDimitry Andric       Streamer.emitBytes(Name->getString());
359af732203SDimitry Andric     }
360af732203SDimitry Andric   }
361af732203SDimitry Andric 
3620b57cec5SDimitry Andric   unsigned Version = 0;
3630b57cec5SDimitry Andric   unsigned Flags = 0;
3640b57cec5SDimitry Andric   StringRef Section;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
3670b57cec5SDimitry Andric   if (!Section.empty()) {
3680b57cec5SDimitry Andric     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3690b57cec5SDimitry Andric     Streamer.SwitchSection(S);
3705ffd83dbSDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
3715ffd83dbSDimitry Andric     Streamer.emitInt32(Version);
3725ffd83dbSDimitry Andric     Streamer.emitInt32(Flags);
3730b57cec5SDimitry Andric     Streamer.AddBlankLine();
3740b57cec5SDimitry Andric   }
3750b57cec5SDimitry Andric 
376af732203SDimitry Andric   emitCGProfileMetadata(Streamer, M);
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
getCFIPersonalitySymbol(const GlobalValue * GV,const TargetMachine & TM,MachineModuleInfo * MMI) const3790b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
3800b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
3810b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
3820b57cec5SDimitry Andric   unsigned Encoding = getPersonalityEncoding();
3830b57cec5SDimitry Andric   if ((Encoding & 0x80) == DW_EH_PE_indirect)
3840b57cec5SDimitry Andric     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
3850b57cec5SDimitry Andric                                           TM.getSymbol(GV)->getName());
3860b57cec5SDimitry Andric   if ((Encoding & 0x70) == DW_EH_PE_absptr)
3870b57cec5SDimitry Andric     return TM.getSymbol(GV);
3880b57cec5SDimitry Andric   report_fatal_error("We do not support this DWARF encoding yet!");
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric 
emitPersonalityValue(MCStreamer & Streamer,const DataLayout & DL,const MCSymbol * Sym) const3910b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitPersonalityValue(
3920b57cec5SDimitry Andric     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
3930b57cec5SDimitry Andric   SmallString<64> NameData("DW.ref.");
3940b57cec5SDimitry Andric   NameData += Sym->getName();
3950b57cec5SDimitry Andric   MCSymbolELF *Label =
3960b57cec5SDimitry Andric       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
3975ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
3985ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
3990b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
4000b57cec5SDimitry Andric   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
4010b57cec5SDimitry Andric                                                    ELF::SHT_PROGBITS, Flags, 0);
4020b57cec5SDimitry Andric   unsigned Size = DL.getPointerSize();
4030b57cec5SDimitry Andric   Streamer.SwitchSection(Sec);
4045ffd83dbSDimitry Andric   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
4055ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
4060b57cec5SDimitry Andric   const MCExpr *E = MCConstantExpr::create(Size, getContext());
4070b57cec5SDimitry Andric   Streamer.emitELFSize(Label, E);
4085ffd83dbSDimitry Andric   Streamer.emitLabel(Label);
4090b57cec5SDimitry Andric 
4105ffd83dbSDimitry Andric   Streamer.emitSymbolValue(Sym, Size);
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric 
getTTypeGlobalReference(const GlobalValue * GV,unsigned Encoding,const TargetMachine & TM,MachineModuleInfo * MMI,MCStreamer & Streamer) const4130b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
4140b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
4150b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
4160b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
4170b57cec5SDimitry Andric     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric     // Add information about the stub reference to ELFMMI so that the stub
4220b57cec5SDimitry Andric     // gets emitted by the asmprinter.
4230b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
4240b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
4250b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
4260b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
4270b57cec5SDimitry Andric     }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric     return TargetLoweringObjectFile::
4300b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
4310b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
4350b57cec5SDimitry Andric                                                            MMI, Streamer);
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric 
getELFKindForNamedSection(StringRef Name,SectionKind K)4380b57cec5SDimitry Andric static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
4390b57cec5SDimitry Andric   // N.B.: The defaults used in here are not the same ones used in MC.
4400b57cec5SDimitry Andric   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
4410b57cec5SDimitry Andric   // both gas and MC will produce a section with no flags. Given
4420b57cec5SDimitry Andric   // section(".eh_frame") gcc will produce:
4430b57cec5SDimitry Andric   //
4440b57cec5SDimitry Andric   //   .section   .eh_frame,"a",@progbits
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
4475ffd83dbSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
4485ffd83dbSDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
449af732203SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
450af732203SDimitry Andric       Name == ".llvmbc" || Name == ".llvmcmd")
4510b57cec5SDimitry Andric     return SectionKind::getMetadata();
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   if (Name.empty() || Name[0] != '.') return K;
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // Default implementation based on some magic section names.
4560b57cec5SDimitry Andric   if (Name == ".bss" ||
4570b57cec5SDimitry Andric       Name.startswith(".bss.") ||
4580b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.b.") ||
4590b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.b.") ||
4600b57cec5SDimitry Andric       Name == ".sbss" ||
4610b57cec5SDimitry Andric       Name.startswith(".sbss.") ||
4620b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.sb.") ||
4630b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.sb."))
4640b57cec5SDimitry Andric     return SectionKind::getBSS();
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   if (Name == ".tdata" ||
4670b57cec5SDimitry Andric       Name.startswith(".tdata.") ||
4680b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.td.") ||
4690b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.td."))
4700b57cec5SDimitry Andric     return SectionKind::getThreadData();
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   if (Name == ".tbss" ||
4730b57cec5SDimitry Andric       Name.startswith(".tbss.") ||
4740b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.tb.") ||
4750b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.tb."))
4760b57cec5SDimitry Andric     return SectionKind::getThreadBSS();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   return K;
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
getELFSectionType(StringRef Name,SectionKind K)4810b57cec5SDimitry Andric static unsigned getELFSectionType(StringRef Name, SectionKind K) {
4820b57cec5SDimitry Andric   // Use SHT_NOTE for section whose name starts with ".note" to allow
4830b57cec5SDimitry Andric   // emitting ELF notes from C variable declaration.
4840b57cec5SDimitry Andric   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
4850b57cec5SDimitry Andric   if (Name.startswith(".note"))
4860b57cec5SDimitry Andric     return ELF::SHT_NOTE;
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric   if (Name == ".init_array")
4890b57cec5SDimitry Andric     return ELF::SHT_INIT_ARRAY;
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   if (Name == ".fini_array")
4920b57cec5SDimitry Andric     return ELF::SHT_FINI_ARRAY;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   if (Name == ".preinit_array")
4950b57cec5SDimitry Andric     return ELF::SHT_PREINIT_ARRAY;
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   if (K.isBSS() || K.isThreadBSS())
4980b57cec5SDimitry Andric     return ELF::SHT_NOBITS;
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   return ELF::SHT_PROGBITS;
5010b57cec5SDimitry Andric }
5020b57cec5SDimitry Andric 
getELFSectionFlags(SectionKind K)5030b57cec5SDimitry Andric static unsigned getELFSectionFlags(SectionKind K) {
5040b57cec5SDimitry Andric   unsigned Flags = 0;
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   if (!K.isMetadata())
5070b57cec5SDimitry Andric     Flags |= ELF::SHF_ALLOC;
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   if (K.isText())
5100b57cec5SDimitry Andric     Flags |= ELF::SHF_EXECINSTR;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   if (K.isExecuteOnly())
5130b57cec5SDimitry Andric     Flags |= ELF::SHF_ARM_PURECODE;
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   if (K.isWriteable())
5160b57cec5SDimitry Andric     Flags |= ELF::SHF_WRITE;
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   if (K.isThreadLocal())
5190b57cec5SDimitry Andric     Flags |= ELF::SHF_TLS;
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   if (K.isMergeableCString() || K.isMergeableConst())
5220b57cec5SDimitry Andric     Flags |= ELF::SHF_MERGE;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   if (K.isMergeableCString())
5250b57cec5SDimitry Andric     Flags |= ELF::SHF_STRINGS;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   return Flags;
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
getELFComdat(const GlobalValue * GV)5300b57cec5SDimitry Andric static const Comdat *getELFComdat(const GlobalValue *GV) {
5310b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
5320b57cec5SDimitry Andric   if (!C)
5330b57cec5SDimitry Andric     return nullptr;
5340b57cec5SDimitry Andric 
5355f7ddb14SDimitry Andric   if (C->getSelectionKind() != Comdat::Any &&
5365f7ddb14SDimitry Andric       C->getSelectionKind() != Comdat::NoDeduplicate)
5375f7ddb14SDimitry Andric     report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
5385f7ddb14SDimitry Andric                        "SelectionKind::NoDeduplicate, '" +
5390b57cec5SDimitry Andric                        C->getName() + "' cannot be lowered.");
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   return C;
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
getLinkedToSymbol(const GlobalObject * GO,const TargetMachine & TM)5445ffd83dbSDimitry Andric static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
5450b57cec5SDimitry Andric                                             const TargetMachine &TM) {
5460b57cec5SDimitry Andric   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
5470b57cec5SDimitry Andric   if (!MD)
5480b57cec5SDimitry Andric     return nullptr;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   const MDOperand &Op = MD->getOperand(0);
5510b57cec5SDimitry Andric   if (!Op.get())
5520b57cec5SDimitry Andric     return nullptr;
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   auto *VM = dyn_cast<ValueAsMetadata>(Op);
5550b57cec5SDimitry Andric   if (!VM)
5560b57cec5SDimitry Andric     report_fatal_error("MD_associated operand is not ValueAsMetadata");
5570b57cec5SDimitry Andric 
5588bcb0991SDimitry Andric   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
5598bcb0991SDimitry Andric   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
getEntrySizeForKind(SectionKind Kind)5620b57cec5SDimitry Andric static unsigned getEntrySizeForKind(SectionKind Kind) {
5630b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString())
5640b57cec5SDimitry Andric     return 1;
5650b57cec5SDimitry Andric   else if (Kind.isMergeable2ByteCString())
5660b57cec5SDimitry Andric     return 2;
5670b57cec5SDimitry Andric   else if (Kind.isMergeable4ByteCString())
5680b57cec5SDimitry Andric     return 4;
5690b57cec5SDimitry Andric   else if (Kind.isMergeableConst4())
5700b57cec5SDimitry Andric     return 4;
5710b57cec5SDimitry Andric   else if (Kind.isMergeableConst8())
5720b57cec5SDimitry Andric     return 8;
5730b57cec5SDimitry Andric   else if (Kind.isMergeableConst16())
5740b57cec5SDimitry Andric     return 16;
5750b57cec5SDimitry Andric   else if (Kind.isMergeableConst32())
5760b57cec5SDimitry Andric     return 32;
5770b57cec5SDimitry Andric   else {
5780b57cec5SDimitry Andric     // We shouldn't have mergeable C strings or mergeable constants that we
5790b57cec5SDimitry Andric     // didn't handle above.
5800b57cec5SDimitry Andric     assert(!Kind.isMergeableCString() && "unknown string width");
5810b57cec5SDimitry Andric     assert(!Kind.isMergeableConst() && "unknown data width");
5820b57cec5SDimitry Andric     return 0;
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5865ffd83dbSDimitry Andric /// Return the section prefix name used by options FunctionsSections and
5875ffd83dbSDimitry Andric /// DataSections.
getSectionPrefixForGlobal(SectionKind Kind)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>
getELFSectionNameForGlobal(const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,unsigned EntrySize,bool UniqueSectionName)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()) {
630af732203SDimitry 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)
6395f7ddb14SDimitry Andric     // For distinguishing between .text.${text-section-prefix}. (with trailing
6405f7ddb14SDimitry 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:
LoweringDiagnosticInfo(const Twine & DiagMsg,DiagnosticSeverity Severity=DS_Error)6505ffd83dbSDimitry Andric   LoweringDiagnosticInfo(const Twine &DiagMsg,
6515ffd83dbSDimitry Andric                          DiagnosticSeverity Severity = DS_Error)
6525ffd83dbSDimitry Andric       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
print(DiagnosticPrinter & DP) const6535ffd83dbSDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6545ffd83dbSDimitry Andric };
6555ffd83dbSDimitry Andric }
6565ffd83dbSDimitry Andric 
6575f7ddb14SDimitry Andric /// Calculate an appropriate unique ID for a section, and update Flags,
6585f7ddb14SDimitry Andric /// EntrySize and NextUniqueID where appropriate.
6595f7ddb14SDimitry Andric static unsigned
calcUniqueIDUpdateFlagsAndSize(const GlobalObject * GO,StringRef SectionName,SectionKind Kind,const TargetMachine & TM,MCContext & Ctx,Mangler & Mang,unsigned & Flags,unsigned & EntrySize,unsigned & NextUniqueID,const bool Retain,const bool ForceUnique)6605f7ddb14SDimitry Andric calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
6615f7ddb14SDimitry Andric                                SectionKind Kind, const TargetMachine &TM,
6625f7ddb14SDimitry Andric                                MCContext &Ctx, Mangler &Mang, unsigned &Flags,
6635f7ddb14SDimitry Andric                                unsigned &EntrySize, unsigned &NextUniqueID,
6645f7ddb14SDimitry Andric                                const bool Retain, const bool ForceUnique) {
6655f7ddb14SDimitry Andric   // Increment uniqueID if we are forced to emit a unique section.
6665f7ddb14SDimitry Andric   // This works perfectly fine with section attribute or pragma section as the
6675f7ddb14SDimitry Andric   // sections with the same name are grouped together by the assembler.
6685f7ddb14SDimitry Andric   if (ForceUnique)
6695f7ddb14SDimitry Andric     return NextUniqueID++;
6705f7ddb14SDimitry Andric 
6715f7ddb14SDimitry Andric   // A section can have at most one associated section. Put each global with
6725f7ddb14SDimitry Andric   // MD_associated in a unique section.
6735f7ddb14SDimitry Andric   const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
6745f7ddb14SDimitry Andric   if (Associated) {
6755f7ddb14SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
6765f7ddb14SDimitry Andric     return NextUniqueID++;
6775f7ddb14SDimitry Andric   }
6785f7ddb14SDimitry Andric 
6795f7ddb14SDimitry Andric   if (Retain) {
680*2e2f8eacSDimitry Andric     if ((Ctx.getAsmInfo()->useIntegratedAssembler() ||
681*2e2f8eacSDimitry Andric          Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
682*2e2f8eacSDimitry Andric         !TM.getTargetTriple().isOSSolaris())
6835f7ddb14SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
6845f7ddb14SDimitry Andric     return NextUniqueID++;
6855f7ddb14SDimitry Andric   }
6865f7ddb14SDimitry Andric 
6875f7ddb14SDimitry Andric   // If two symbols with differing sizes end up in the same mergeable section
6885f7ddb14SDimitry Andric   // that section can be assigned an incorrect entry size. To avoid this we
6895f7ddb14SDimitry Andric   // usually put symbols of the same size into distinct mergeable sections with
6905f7ddb14SDimitry Andric   // the same name. Doing so relies on the ",unique ," assembly feature. This
6915f7ddb14SDimitry Andric   // feature is not avalible until bintuils version 2.35
6925f7ddb14SDimitry Andric   // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
6935f7ddb14SDimitry Andric   const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
6945f7ddb14SDimitry Andric                               Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
6955f7ddb14SDimitry Andric   if (!SupportsUnique) {
6965f7ddb14SDimitry Andric     Flags &= ~ELF::SHF_MERGE;
6975f7ddb14SDimitry Andric     EntrySize = 0;
6985f7ddb14SDimitry Andric     return MCContext::GenericSectionID;
6995f7ddb14SDimitry Andric   }
7005f7ddb14SDimitry Andric 
7015f7ddb14SDimitry Andric   const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
7025f7ddb14SDimitry Andric   const bool SeenSectionNameBefore =
7035f7ddb14SDimitry Andric       Ctx.isELFGenericMergeableSection(SectionName);
7045f7ddb14SDimitry Andric   // If this is the first ocurrence of this section name, treat it as the
7055f7ddb14SDimitry Andric   // generic section
7065f7ddb14SDimitry Andric   if (!SymbolMergeable && !SeenSectionNameBefore)
7075f7ddb14SDimitry Andric     return MCContext::GenericSectionID;
7085f7ddb14SDimitry Andric 
7095f7ddb14SDimitry Andric   // Symbols must be placed into sections with compatible entry sizes. Generate
7105f7ddb14SDimitry Andric   // unique sections for symbols that have not been assigned to compatible
7115f7ddb14SDimitry Andric   // sections.
7125f7ddb14SDimitry Andric   const auto PreviousID =
7135f7ddb14SDimitry Andric       Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
7145f7ddb14SDimitry Andric   if (PreviousID)
7155f7ddb14SDimitry Andric     return *PreviousID;
7165f7ddb14SDimitry Andric 
7175f7ddb14SDimitry Andric   // If the user has specified the same section name as would be created
7185f7ddb14SDimitry Andric   // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
7195f7ddb14SDimitry Andric   // to unique the section as the entry size for this symbol will be
7205f7ddb14SDimitry Andric   // compatible with implicitly created sections.
7215f7ddb14SDimitry Andric   SmallString<128> ImplicitSectionNameStem =
7225f7ddb14SDimitry Andric       getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
7235f7ddb14SDimitry Andric   if (SymbolMergeable &&
7245f7ddb14SDimitry Andric       Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
7255f7ddb14SDimitry Andric       SectionName.startswith(ImplicitSectionNameStem))
7265f7ddb14SDimitry Andric     return MCContext::GenericSectionID;
7275f7ddb14SDimitry Andric 
7285f7ddb14SDimitry Andric   // We have seen this section name before, but with different flags or entity
7295f7ddb14SDimitry Andric   // size. Create a new unique ID.
7305f7ddb14SDimitry Andric   return NextUniqueID++;
7315f7ddb14SDimitry Andric }
7325f7ddb14SDimitry Andric 
selectExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM,MCContext & Ctx,Mangler & Mang,unsigned & NextUniqueID,bool Retain,bool ForceUnique)7335f7ddb14SDimitry Andric static MCSection *selectExplicitSectionGlobal(
7345f7ddb14SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
7355f7ddb14SDimitry Andric     MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
7365f7ddb14SDimitry Andric     bool Retain, bool ForceUnique) {
7370b57cec5SDimitry Andric   StringRef SectionName = GO->getSection();
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   // Check if '#pragma clang section' name is applicable.
7400b57cec5SDimitry Andric   // Note that pragma directive overrides -ffunction-section, -fdata-section
7410b57cec5SDimitry Andric   // and so section name is exactly as user specified and not uniqued.
7420b57cec5SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
7430b57cec5SDimitry Andric   if (GV && GV->hasImplicitSection()) {
7440b57cec5SDimitry Andric     auto Attrs = GV->getAttributes();
7450b57cec5SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
7460b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
7470b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
7480b57cec5SDimitry 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();
7510b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
7520b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric   }
7550b57cec5SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
7560b57cec5SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
7570b57cec5SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // Infer section flags from the section name if we can.
7610b57cec5SDimitry Andric   Kind = getELFKindForNamedSection(SectionName, Kind);
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   StringRef Group = "";
7645f7ddb14SDimitry Andric   bool IsComdat = false;
7650b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
7660b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
7670b57cec5SDimitry Andric     Group = C->getName();
7685f7ddb14SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
7690b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
7700b57cec5SDimitry Andric   }
7710b57cec5SDimitry Andric 
7725ffd83dbSDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
7735f7ddb14SDimitry Andric   const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
7745f7ddb14SDimitry Andric       GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
7755f7ddb14SDimitry Andric       Retain, ForceUnique);
7765ffd83dbSDimitry Andric 
7775ffd83dbSDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
7785f7ddb14SDimitry Andric   MCSectionELF *Section = Ctx.getELFSection(
7795f7ddb14SDimitry Andric       SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
7805f7ddb14SDimitry Andric       Group, IsComdat, UniqueID, LinkedToSym);
7810b57cec5SDimitry Andric   // Make sure that we did not get some other section with incompatible sh_link.
7820b57cec5SDimitry Andric   // This should not be possible due to UniqueID code above.
7835ffd83dbSDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym &&
7840b57cec5SDimitry Andric          "Associated symbol mismatch between sections");
7855ffd83dbSDimitry Andric 
7865f7ddb14SDimitry Andric   if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
7875f7ddb14SDimitry Andric         Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
788af732203SDimitry 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?"));
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
8035ffd83dbSDimitry Andric   return Section;
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const8065f7ddb14SDimitry Andric MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
8075f7ddb14SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
8085f7ddb14SDimitry Andric   return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
8095f7ddb14SDimitry Andric                                      NextUniqueID, Used.count(GO),
8105f7ddb14SDimitry Andric                                      /* ForceUnique = */false);
8115f7ddb14SDimitry Andric }
8125f7ddb14SDimitry Andric 
selectELFSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool EmitUniqueSection,unsigned Flags,unsigned * NextUniqueID,const MCSymbolELF * AssociatedSymbol)8130b57cec5SDimitry Andric static MCSectionELF *selectELFSectionForGlobal(
8140b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
8150b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
8160b57cec5SDimitry Andric     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   StringRef Group = "";
8195f7ddb14SDimitry Andric   bool IsComdat = false;
8200b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
8210b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
8220b57cec5SDimitry Andric     Group = C->getName();
8235f7ddb14SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
8240b57cec5SDimitry Andric   }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // Get the section entry size based on the kind.
8270b57cec5SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
8280b57cec5SDimitry Andric 
8295ffd83dbSDimitry Andric   bool UniqueSectionName = false;
8300b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
8310b57cec5SDimitry Andric   if (EmitUniqueSection) {
8320b57cec5SDimitry Andric     if (TM.getUniqueSectionNames()) {
8335ffd83dbSDimitry Andric       UniqueSectionName = true;
8340b57cec5SDimitry Andric     } else {
8350b57cec5SDimitry Andric       UniqueID = *NextUniqueID;
8360b57cec5SDimitry Andric       (*NextUniqueID)++;
8370b57cec5SDimitry Andric     }
8380b57cec5SDimitry Andric   }
8395ffd83dbSDimitry Andric   SmallString<128> Name = getELFSectionNameForGlobal(
8405ffd83dbSDimitry Andric       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
8415ffd83dbSDimitry Andric 
8420b57cec5SDimitry Andric   // Use 0 as the unique ID for execute-only text.
8430b57cec5SDimitry Andric   if (Kind.isExecuteOnly())
8440b57cec5SDimitry Andric     UniqueID = 0;
8450b57cec5SDimitry Andric   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
8465f7ddb14SDimitry Andric                            EntrySize, Group, IsComdat, UniqueID,
8475f7ddb14SDimitry Andric                            AssociatedSymbol);
8485f7ddb14SDimitry Andric }
8495f7ddb14SDimitry Andric 
selectELFSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool Retain,bool EmitUniqueSection,unsigned Flags,unsigned * NextUniqueID)8505f7ddb14SDimitry Andric static MCSection *selectELFSectionForGlobal(
8515f7ddb14SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
8525f7ddb14SDimitry Andric     const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
8535f7ddb14SDimitry Andric     unsigned Flags, unsigned *NextUniqueID) {
8545f7ddb14SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
8555f7ddb14SDimitry Andric   if (LinkedToSym) {
8565f7ddb14SDimitry Andric     EmitUniqueSection = true;
8575f7ddb14SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
8585f7ddb14SDimitry Andric   }
859*2e2f8eacSDimitry Andric   if (Retain &&
860*2e2f8eacSDimitry Andric       (Ctx.getAsmInfo()->useIntegratedAssembler() ||
861*2e2f8eacSDimitry Andric        Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
862*2e2f8eacSDimitry Andric       !TM.getTargetTriple().isOSSolaris()) {
8635f7ddb14SDimitry Andric     EmitUniqueSection = true;
8645f7ddb14SDimitry Andric     Flags |= ELF::SHF_GNU_RETAIN;
8655f7ddb14SDimitry Andric   }
8665f7ddb14SDimitry Andric 
8675f7ddb14SDimitry Andric   MCSectionELF *Section = selectELFSectionForGlobal(
8685f7ddb14SDimitry Andric       Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
8695f7ddb14SDimitry Andric       NextUniqueID, LinkedToSym);
8705f7ddb14SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym);
8715f7ddb14SDimitry Andric   return Section;
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const8740b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
8750b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
8760b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
8790b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
8800b57cec5SDimitry Andric   bool EmitUniqueSection = false;
8810b57cec5SDimitry Andric   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
8820b57cec5SDimitry Andric     if (Kind.isText())
8830b57cec5SDimitry Andric       EmitUniqueSection = TM.getFunctionSections();
8840b57cec5SDimitry Andric     else
8850b57cec5SDimitry Andric       EmitUniqueSection = TM.getDataSections();
8860b57cec5SDimitry Andric   }
8870b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
8885f7ddb14SDimitry Andric   return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
8895f7ddb14SDimitry Andric                                    Used.count(GO), EmitUniqueSection, Flags,
8905f7ddb14SDimitry Andric                                    &NextUniqueID);
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
getUniqueSectionForFunction(const Function & F,const TargetMachine & TM) const8935f7ddb14SDimitry Andric MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
8945f7ddb14SDimitry Andric     const Function &F, const TargetMachine &TM) const {
8955f7ddb14SDimitry Andric   SectionKind Kind = SectionKind::getText();
8965f7ddb14SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
8975f7ddb14SDimitry Andric   // If the function's section names is pre-determined via pragma or a
8985f7ddb14SDimitry Andric   // section attribute, call selectExplicitSectionGlobal.
8995f7ddb14SDimitry Andric   if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
9005f7ddb14SDimitry Andric     return selectExplicitSectionGlobal(
9015f7ddb14SDimitry Andric         &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
9025f7ddb14SDimitry Andric         Used.count(&F), /* ForceUnique = */true);
9035f7ddb14SDimitry Andric   else
9045f7ddb14SDimitry Andric     return selectELFSectionForGlobal(
9055f7ddb14SDimitry Andric         getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
9065f7ddb14SDimitry Andric         /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const9090b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
9100b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
9110b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
9120b57cec5SDimitry Andric   // the table doesn't prevent the removal.
9130b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
9140b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
9150b57cec5SDimitry Andric   if (!EmitUniqueSection)
9160b57cec5SDimitry Andric     return ReadOnlySection;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
9190b57cec5SDimitry Andric                                    getMangler(), TM, EmitUniqueSection,
9200b57cec5SDimitry Andric                                    ELF::SHF_ALLOC, &NextUniqueID,
9210b57cec5SDimitry Andric                                    /* AssociatedSymbol */ nullptr);
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric 
getSectionForLSDA(const Function & F,const MCSymbol & FnSym,const TargetMachine & TM) const9245f7ddb14SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
9255f7ddb14SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
926af732203SDimitry Andric   // If neither COMDAT nor function sections, use the monolithic LSDA section.
927af732203SDimitry Andric   // Re-use this path if LSDASection is null as in the Arm EHABI.
928af732203SDimitry Andric   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
929af732203SDimitry Andric     return LSDASection;
930af732203SDimitry Andric 
931af732203SDimitry Andric   const auto *LSDA = cast<MCSectionELF>(LSDASection);
932af732203SDimitry Andric   unsigned Flags = LSDA->getFlags();
9335f7ddb14SDimitry Andric   const MCSymbolELF *LinkedToSym = nullptr;
934af732203SDimitry Andric   StringRef Group;
9355f7ddb14SDimitry Andric   bool IsComdat = false;
9365f7ddb14SDimitry Andric   if (const Comdat *C = getELFComdat(&F)) {
937af732203SDimitry Andric     Flags |= ELF::SHF_GROUP;
9385f7ddb14SDimitry Andric     Group = C->getName();
9395f7ddb14SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
9405f7ddb14SDimitry Andric   }
9415f7ddb14SDimitry Andric   // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
9425f7ddb14SDimitry Andric   // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
9435f7ddb14SDimitry Andric   if (TM.getFunctionSections() &&
9445f7ddb14SDimitry Andric       (getContext().getAsmInfo()->useIntegratedAssembler() &&
9455f7ddb14SDimitry Andric        getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
9465f7ddb14SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
9475f7ddb14SDimitry Andric     LinkedToSym = cast<MCSymbolELF>(&FnSym);
948af732203SDimitry Andric   }
949af732203SDimitry Andric 
950af732203SDimitry Andric   // Append the function name as the suffix like GCC, assuming
951af732203SDimitry Andric   // -funique-section-names applies to .gcc_except_table sections.
9525f7ddb14SDimitry Andric   return getContext().getELFSection(
9535f7ddb14SDimitry Andric       (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
9545f7ddb14SDimitry Andric                                   : LSDA->getName()),
9555f7ddb14SDimitry Andric       LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
9565f7ddb14SDimitry Andric       LinkedToSym);
957af732203SDimitry Andric }
958af732203SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const9590b57cec5SDimitry Andric bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
9600b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
9610b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
9620b57cec5SDimitry Andric   // that can be marked non-executable.
9630b57cec5SDimitry Andric   return false;
9640b57cec5SDimitry Andric }
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric /// Given a mergeable constant with the specified size and relocation
9670b57cec5SDimitry Andric /// information, return a section that it should be placed in.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const9680b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
9690b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
9705ffd83dbSDimitry Andric     Align &Alignment) const {
9710b57cec5SDimitry Andric   if (Kind.isMergeableConst4() && MergeableConst4Section)
9720b57cec5SDimitry Andric     return MergeableConst4Section;
9730b57cec5SDimitry Andric   if (Kind.isMergeableConst8() && MergeableConst8Section)
9740b57cec5SDimitry Andric     return MergeableConst8Section;
9750b57cec5SDimitry Andric   if (Kind.isMergeableConst16() && MergeableConst16Section)
9760b57cec5SDimitry Andric     return MergeableConst16Section;
9770b57cec5SDimitry Andric   if (Kind.isMergeableConst32() && MergeableConst32Section)
9780b57cec5SDimitry Andric     return MergeableConst32Section;
9790b57cec5SDimitry Andric   if (Kind.isReadOnly())
9800b57cec5SDimitry Andric     return ReadOnlySection;
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
9830b57cec5SDimitry Andric   return DataRelROSection;
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric 
9865ffd83dbSDimitry Andric /// Returns a unique section for the given machine basic block.
getSectionForMachineBasicBlock(const Function & F,const MachineBasicBlock & MBB,const TargetMachine & TM) const9875ffd83dbSDimitry 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 
993af732203SDimitry 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) {
1000af732203SDimitry 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()) {
10085f7ddb14SDimitry 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;
1017af732203SDimitry 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,
10235f7ddb14SDimitry Andric                                     0 /* Entry Size */, GroupName,
10245f7ddb14SDimitry Andric                                     F.hasComdat(), UniqueID, nullptr);
10255ffd83dbSDimitry Andric }
10265ffd83dbSDimitry Andric 
getStaticStructorSection(MCContext & Ctx,bool UseInitArray,bool IsCtor,unsigned Priority,const MCSymbol * KeySym)10270b57cec5SDimitry Andric static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
10280b57cec5SDimitry Andric                                               bool IsCtor, unsigned Priority,
10290b57cec5SDimitry Andric                                               const MCSymbol *KeySym) {
10300b57cec5SDimitry Andric   std::string Name;
10310b57cec5SDimitry Andric   unsigned Type;
10320b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
10335f7ddb14SDimitry Andric   StringRef Comdat = KeySym ? KeySym->getName() : "";
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   if (KeySym)
10360b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   if (UseInitArray) {
10390b57cec5SDimitry Andric     if (IsCtor) {
10400b57cec5SDimitry Andric       Type = ELF::SHT_INIT_ARRAY;
10410b57cec5SDimitry Andric       Name = ".init_array";
10420b57cec5SDimitry Andric     } else {
10430b57cec5SDimitry Andric       Type = ELF::SHT_FINI_ARRAY;
10440b57cec5SDimitry Andric       Name = ".fini_array";
10450b57cec5SDimitry Andric     }
10460b57cec5SDimitry Andric     if (Priority != 65535) {
10470b57cec5SDimitry Andric       Name += '.';
10480b57cec5SDimitry Andric       Name += utostr(Priority);
10490b57cec5SDimitry Andric     }
10500b57cec5SDimitry Andric   } else {
10510b57cec5SDimitry Andric     // The default scheme is .ctor / .dtor, so we have to invert the priority
10520b57cec5SDimitry Andric     // numbering.
10530b57cec5SDimitry Andric     if (IsCtor)
10540b57cec5SDimitry Andric       Name = ".ctors";
10550b57cec5SDimitry Andric     else
10560b57cec5SDimitry Andric       Name = ".dtors";
10570b57cec5SDimitry Andric     if (Priority != 65535)
10580b57cec5SDimitry Andric       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
10590b57cec5SDimitry Andric     Type = ELF::SHT_PROGBITS;
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric 
10625f7ddb14SDimitry Andric   return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const10650b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
10660b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
10670b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
10680b57cec5SDimitry Andric                                   KeySym);
10690b57cec5SDimitry Andric }
10700b57cec5SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const10710b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
10720b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
10730b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
10740b57cec5SDimitry Andric                                   KeySym);
10750b57cec5SDimitry Andric }
10760b57cec5SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const10770b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
10780b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
10790b57cec5SDimitry Andric     const TargetMachine &TM) const {
10800b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
10810b57cec5SDimitry Andric   // functions.
10820b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
10830b57cec5SDimitry Andric     return nullptr;
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric   // Basic sanity checks.
10860b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
10870b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
10880b57cec5SDimitry Andric       RHS->isThreadLocal())
10890b57cec5SDimitry Andric     return nullptr;
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
10920b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
10930b57cec5SDimitry Andric                               getContext()),
10940b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
10950b57cec5SDimitry Andric }
10960b57cec5SDimitry Andric 
lowerDSOLocalEquivalent(const DSOLocalEquivalent * Equiv,const TargetMachine & TM) const1097af732203SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1098af732203SDimitry Andric     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1099af732203SDimitry Andric   assert(supportDSOLocalEquivalentLowering());
1100af732203SDimitry Andric 
1101af732203SDimitry Andric   const auto *GV = Equiv->getGlobalValue();
1102af732203SDimitry Andric 
1103af732203SDimitry Andric   // A PLT entry is not needed for dso_local globals.
1104af732203SDimitry Andric   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1105af732203SDimitry Andric     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1106af732203SDimitry Andric 
1107af732203SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1108af732203SDimitry Andric                                  getContext());
1109af732203SDimitry Andric }
1110af732203SDimitry Andric 
getSectionForCommandLines() const11110b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
11120b57cec5SDimitry Andric   // Use ".GCC.command.line" since this feature is to support clang's
11130b57cec5SDimitry Andric   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
11140b57cec5SDimitry Andric   // same name.
11150b57cec5SDimitry Andric   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
11165f7ddb14SDimitry Andric                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric void
InitializeELF(bool UseInitArray_)11200b57cec5SDimitry Andric TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
11210b57cec5SDimitry Andric   UseInitArray = UseInitArray_;
11220b57cec5SDimitry Andric   MCContext &Ctx = getContext();
11230b57cec5SDimitry Andric   if (!UseInitArray) {
11240b57cec5SDimitry Andric     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
11250b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
11280b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
11290b57cec5SDimitry Andric     return;
11300b57cec5SDimitry Andric   }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
11330b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
11340b57cec5SDimitry Andric   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
11350b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11390b57cec5SDimitry Andric //                                 MachO
11400b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11410b57cec5SDimitry Andric 
TargetLoweringObjectFileMachO()11420b57cec5SDimitry Andric TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
11430b57cec5SDimitry Andric   : TargetLoweringObjectFile() {
11440b57cec5SDimitry Andric   SupportIndirectSymViaGOTPCRel = true;
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TM)11470b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
11480b57cec5SDimitry Andric                                                const TargetMachine &TM) {
11490b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
11500b57cec5SDimitry Andric   if (TM.getRelocationModel() == Reloc::Static) {
11510b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
11520b57cec5SDimitry Andric                                             SectionKind::getData());
11530b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
11540b57cec5SDimitry Andric                                             SectionKind::getData());
11550b57cec5SDimitry Andric   } else {
11560b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
11570b57cec5SDimitry Andric                                             MachO::S_MOD_INIT_FUNC_POINTERS,
11580b57cec5SDimitry Andric                                             SectionKind::getData());
11590b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
11600b57cec5SDimitry Andric                                             MachO::S_MOD_TERM_FUNC_POINTERS,
11610b57cec5SDimitry Andric                                             SectionKind::getData());
11620b57cec5SDimitry Andric   }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   PersonalityEncoding =
11650b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
11660b57cec5SDimitry Andric   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
11670b57cec5SDimitry Andric   TTypeEncoding =
11680b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const11710b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
11720b57cec5SDimitry Andric                                                        Module &M) const {
11730b57cec5SDimitry Andric   // Emit the linker options if present.
11740b57cec5SDimitry Andric   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1175480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
11760b57cec5SDimitry Andric       SmallVector<std::string, 4> StrOptions;
11770b57cec5SDimitry 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);
11800b57cec5SDimitry Andric     }
11810b57cec5SDimitry Andric   }
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric   unsigned VersionVal = 0;
11840b57cec5SDimitry Andric   unsigned ImageInfoFlags = 0;
11850b57cec5SDimitry Andric   StringRef SectionVal;
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // The section is mandatory. If we don't have it, then we don't have GC info.
11900b57cec5SDimitry Andric   if (SectionVal.empty())
11910b57cec5SDimitry Andric     return;
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric   StringRef Segment, Section;
11940b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
11950b57cec5SDimitry Andric   bool TAAParsed;
11965f7ddb14SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
11975f7ddb14SDimitry Andric           SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
11980b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
11995f7ddb14SDimitry Andric     report_fatal_error("Invalid section specifier '" + Section +
12005f7ddb14SDimitry Andric                        "': " + toString(std::move(E)) + ".");
12015f7ddb14SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // Get the section.
12040b57cec5SDimitry Andric   MCSectionMachO *S = getContext().getMachOSection(
12050b57cec5SDimitry Andric       Segment, Section, TAA, StubSize, SectionKind::getData());
12060b57cec5SDimitry Andric   Streamer.SwitchSection(S);
12075ffd83dbSDimitry Andric   Streamer.emitLabel(getContext().
12080b57cec5SDimitry Andric                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
12095ffd83dbSDimitry Andric   Streamer.emitInt32(VersionVal);
12105ffd83dbSDimitry Andric   Streamer.emitInt32(ImageInfoFlags);
12110b57cec5SDimitry Andric   Streamer.AddBlankLine();
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
checkMachOComdat(const GlobalValue * GV)12140b57cec5SDimitry Andric static void checkMachOComdat(const GlobalValue *GV) {
12150b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
12160b57cec5SDimitry Andric   if (!C)
12170b57cec5SDimitry Andric     return;
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
12200b57cec5SDimitry Andric                      "' cannot be lowered.");
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const12230b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
12240b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
12255f7ddb14SDimitry Andric 
12265f7ddb14SDimitry Andric   StringRef SectionName = GO->getSection();
12275f7ddb14SDimitry Andric 
12285f7ddb14SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
12295f7ddb14SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
12305f7ddb14SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
12315f7ddb14SDimitry Andric   }
12325f7ddb14SDimitry Andric 
12330b57cec5SDimitry Andric   // Parse the section specifier and create it if valid.
12340b57cec5SDimitry Andric   StringRef Segment, Section;
12350b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
12360b57cec5SDimitry Andric   bool TAAParsed;
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   checkMachOComdat(GO);
12390b57cec5SDimitry Andric 
12405f7ddb14SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
12415f7ddb14SDimitry Andric           SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
12420b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
12430b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
12440b57cec5SDimitry Andric                        "' has an invalid section specifier '" +
12455f7ddb14SDimitry Andric                        GO->getSection() + "': " + toString(std::move(E)) + ".");
12460b57cec5SDimitry Andric   }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   // Get the section.
12490b57cec5SDimitry Andric   MCSectionMachO *S =
12500b57cec5SDimitry Andric       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   // If TAA wasn't set by ParseSectionSpecifier() above,
12530b57cec5SDimitry Andric   // use the value returned by getMachOSection() as a default.
12540b57cec5SDimitry Andric   if (!TAAParsed)
12550b57cec5SDimitry Andric     TAA = S->getTypeAndAttributes();
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   // Okay, now that we got the section, verify that the TAA & StubSize agree.
12580b57cec5SDimitry Andric   // If the user declared multiple globals with different section flags, we need
12590b57cec5SDimitry Andric   // to reject it here.
12600b57cec5SDimitry Andric   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
12610b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
12620b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
12630b57cec5SDimitry Andric                        "' section type or attributes does not match previous"
12640b57cec5SDimitry Andric                        " section specifier");
12650b57cec5SDimitry Andric   }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   return S;
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const12700b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
12710b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
12720b57cec5SDimitry Andric   checkMachOComdat(GO);
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // Handle thread local data.
12750b57cec5SDimitry Andric   if (Kind.isThreadBSS()) return TLSBSSSection;
12760b57cec5SDimitry Andric   if (Kind.isThreadData()) return TLSDataSection;
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   if (Kind.isText())
12790b57cec5SDimitry Andric     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   // If this is weak/linkonce, put this in a coalescable section, either in text
12820b57cec5SDimitry Andric   // or data depending on if it is writable.
12830b57cec5SDimitry Andric   if (GO->isWeakForLinker()) {
12840b57cec5SDimitry Andric     if (Kind.isReadOnly())
12850b57cec5SDimitry Andric       return ConstTextCoalSection;
12860b57cec5SDimitry Andric     if (Kind.isReadOnlyWithRel())
12870b57cec5SDimitry Andric       return ConstDataCoalSection;
12880b57cec5SDimitry Andric     return DataCoalSection;
12890b57cec5SDimitry Andric   }
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   // FIXME: Alignment check should be handled by section classifier.
12920b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString() &&
12935ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
12945ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
12950b57cec5SDimitry Andric     return CStringSection;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   // Do not put 16-bit arrays in the UString section if they have an
12980b57cec5SDimitry Andric   // externally visible label, this runs into issues with certain linker
12990b57cec5SDimitry Andric   // versions.
13000b57cec5SDimitry Andric   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
13015ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
13025ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
13030b57cec5SDimitry Andric     return UStringSection;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   // With MachO only variables whose corresponding symbol starts with 'l' or
13060b57cec5SDimitry Andric   // 'L' can be merged, so we only try merging GVs with private linkage.
13070b57cec5SDimitry Andric   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
13080b57cec5SDimitry Andric     if (Kind.isMergeableConst4())
13090b57cec5SDimitry Andric       return FourByteConstantSection;
13100b57cec5SDimitry Andric     if (Kind.isMergeableConst8())
13110b57cec5SDimitry Andric       return EightByteConstantSection;
13120b57cec5SDimitry Andric     if (Kind.isMergeableConst16())
13130b57cec5SDimitry Andric       return SixteenByteConstantSection;
13140b57cec5SDimitry Andric   }
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric   // Otherwise, if it is readonly, but not something we can specially optimize,
13170b57cec5SDimitry Andric   // just drop it in .const.
13180b57cec5SDimitry Andric   if (Kind.isReadOnly())
13190b57cec5SDimitry Andric     return ReadOnlySection;
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric   // If this is marked const, put it into a const section.  But if the dynamic
13220b57cec5SDimitry Andric   // linker needs to write to it, put it in the data segment.
13230b57cec5SDimitry Andric   if (Kind.isReadOnlyWithRel())
13240b57cec5SDimitry Andric     return ConstDataSection;
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric   // Put zero initialized globals with strong external linkage in the
13270b57cec5SDimitry Andric   // DATA, __common section with the .zerofill directive.
13280b57cec5SDimitry Andric   if (Kind.isBSSExtern())
13290b57cec5SDimitry Andric     return DataCommonSection;
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   // Put zero initialized globals with local linkage in __DATA,__bss directive
13320b57cec5SDimitry Andric   // with the .zerofill directive (aka .lcomm).
13330b57cec5SDimitry Andric   if (Kind.isBSSLocal())
13340b57cec5SDimitry Andric     return DataBSSSection;
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   // Otherwise, just drop the variable in the normal data section.
13370b57cec5SDimitry Andric   return DataSection;
13380b57cec5SDimitry Andric }
13390b57cec5SDimitry Andric 
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const13400b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
13410b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
13425ffd83dbSDimitry Andric     Align &Alignment) const {
13430b57cec5SDimitry Andric   // If this constant requires a relocation, we have to put it in the data
13440b57cec5SDimitry Andric   // segment, not in the text segment.
13450b57cec5SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel())
13460b57cec5SDimitry Andric     return ConstDataSection;
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   if (Kind.isMergeableConst4())
13490b57cec5SDimitry Andric     return FourByteConstantSection;
13500b57cec5SDimitry Andric   if (Kind.isMergeableConst8())
13510b57cec5SDimitry Andric     return EightByteConstantSection;
13520b57cec5SDimitry Andric   if (Kind.isMergeableConst16())
13530b57cec5SDimitry Andric     return SixteenByteConstantSection;
13540b57cec5SDimitry Andric   return ReadOnlySection;  // .const
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
getTTypeGlobalReference(const GlobalValue * GV,unsigned Encoding,const TargetMachine & TM,MachineModuleInfo * MMI,MCStreamer & Streamer) const13570b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
13580b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
13590b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
13600b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
13630b57cec5SDimitry Andric     MachineModuleInfoMachO &MachOMMI =
13640b57cec5SDimitry Andric       MMI->getObjFileInfo<MachineModuleInfoMachO>();
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric     // Add information about the stub reference to MachOMMI so that the stub
13690b57cec5SDimitry Andric     // gets emitted by the asmprinter.
13700b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
13710b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
13720b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
13730b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
13740b57cec5SDimitry Andric     }
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric     return TargetLoweringObjectFile::
13770b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
13780b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
13790b57cec5SDimitry Andric   }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
13820b57cec5SDimitry Andric                                                            MMI, Streamer);
13830b57cec5SDimitry Andric }
13840b57cec5SDimitry Andric 
getCFIPersonalitySymbol(const GlobalValue * GV,const TargetMachine & TM,MachineModuleInfo * MMI) const13850b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
13860b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
13870b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
13880b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
13890b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
13900b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric   // Add information about the stub reference to MachOMMI so that the stub
13950b57cec5SDimitry Andric   // gets emitted by the asmprinter.
13960b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
13970b57cec5SDimitry Andric   if (!StubSym.getPointer()) {
13980b57cec5SDimitry Andric     MCSymbol *Sym = TM.getSymbol(GV);
13990b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
14000b57cec5SDimitry Andric   }
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric   return SSym;
14030b57cec5SDimitry Andric }
14040b57cec5SDimitry Andric 
getIndirectSymViaGOTPCRel(const GlobalValue * GV,const MCSymbol * Sym,const MCValue & MV,int64_t Offset,MachineModuleInfo * MMI,MCStreamer & Streamer) const14050b57cec5SDimitry 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 {
14080b57cec5SDimitry Andric   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
14090b57cec5SDimitry Andric   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
14100b57cec5SDimitry Andric   // through a non_lazy_ptr stub instead. One advantage is that it allows the
14110b57cec5SDimitry Andric   // computation of deltas to final external symbols. Example:
14120b57cec5SDimitry Andric   //
14130b57cec5SDimitry Andric   //    _extgotequiv:
14140b57cec5SDimitry Andric   //       .long   _extfoo
14150b57cec5SDimitry Andric   //
14160b57cec5SDimitry Andric   //    _delta:
14170b57cec5SDimitry Andric   //       .long   _extgotequiv-_delta
14180b57cec5SDimitry Andric   //
14190b57cec5SDimitry Andric   // is transformed to:
14200b57cec5SDimitry Andric   //
14210b57cec5SDimitry Andric   //    _delta:
14220b57cec5SDimitry Andric   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
14230b57cec5SDimitry Andric   //
14240b57cec5SDimitry Andric   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
14250b57cec5SDimitry Andric   //    L_extfoo$non_lazy_ptr:
14260b57cec5SDimitry Andric   //       .indirect_symbol        _extfoo
14270b57cec5SDimitry Andric   //       .long   0
14280b57cec5SDimitry Andric   //
14290b57cec5SDimitry Andric   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
14300b57cec5SDimitry Andric   // may point to both local (same translation unit) and global (other
14310b57cec5SDimitry Andric   // translation units) symbols. Example:
14320b57cec5SDimitry Andric   //
14330b57cec5SDimitry Andric   // .section __DATA,__pointers,non_lazy_symbol_pointers
14340b57cec5SDimitry Andric   // L1:
14350b57cec5SDimitry Andric   //    .indirect_symbol _myGlobal
14360b57cec5SDimitry Andric   //    .long 0
14370b57cec5SDimitry Andric   // L2:
14380b57cec5SDimitry Andric   //    .indirect_symbol _myLocal
14390b57cec5SDimitry Andric   //    .long _myLocal
14400b57cec5SDimitry Andric   //
14410b57cec5SDimitry Andric   // If the symbol is local, instead of the symbol's index, the assembler
14420b57cec5SDimitry Andric   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
14430b57cec5SDimitry Andric   // Then the linker will notice the constant in the table and will look at the
14440b57cec5SDimitry Andric   // content of the symbol.
14450b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
14460b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
14470b57cec5SDimitry Andric   MCContext &Ctx = getContext();
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // The offset must consider the original displacement from the base symbol
14500b57cec5SDimitry Andric   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
14510b57cec5SDimitry Andric   Offset = -MV.getConstant();
14520b57cec5SDimitry Andric   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
14550b57cec5SDimitry Andric   // non_lazy_ptr stubs.
14560b57cec5SDimitry Andric   SmallString<128> Name;
14570b57cec5SDimitry Andric   StringRef Suffix = "$non_lazy_ptr";
14580b57cec5SDimitry Andric   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
14590b57cec5SDimitry Andric   Name += Sym->getName();
14600b57cec5SDimitry Andric   Name += Suffix;
14610b57cec5SDimitry Andric   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
14648bcb0991SDimitry Andric 
14658bcb0991SDimitry Andric   if (!StubSym.getPointer())
14660b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
14678bcb0991SDimitry Andric                                                  !GV->hasLocalLinkage());
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   const MCExpr *BSymExpr =
14700b57cec5SDimitry Andric     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
14710b57cec5SDimitry Andric   const MCExpr *LHS =
14720b57cec5SDimitry Andric     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   if (!Offset)
14750b57cec5SDimitry Andric     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   const MCExpr *RHS =
14780b57cec5SDimitry Andric     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
14790b57cec5SDimitry Andric   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
canUsePrivateLabel(const MCAsmInfo & AsmInfo,const MCSection & Section)14820b57cec5SDimitry Andric static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
14830b57cec5SDimitry Andric                                const MCSection &Section) {
14840b57cec5SDimitry Andric   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
14850b57cec5SDimitry Andric     return true;
14860b57cec5SDimitry Andric 
14875f7ddb14SDimitry Andric   // FIXME: we should be able to use private labels for sections that can't be
14885f7ddb14SDimitry Andric   // dead-stripped (there's no issue with blocking atomization there), but `ld
14895f7ddb14SDimitry Andric   // -r` sometimes drops the no_dead_strip attribute from sections so for safety
14905f7ddb14SDimitry Andric   // we don't allow it.
14910b57cec5SDimitry Andric   return false;
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,const TargetMachine & TM) const14940b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::getNameWithPrefix(
14950b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
14960b57cec5SDimitry Andric     const TargetMachine &TM) const {
14970b57cec5SDimitry Andric   bool CannotUsePrivateLabel = true;
14980b57cec5SDimitry Andric   if (auto *GO = GV->getBaseObject()) {
14990b57cec5SDimitry Andric     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
15000b57cec5SDimitry Andric     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
15010b57cec5SDimitry Andric     CannotUsePrivateLabel =
15020b57cec5SDimitry Andric         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
15030b57cec5SDimitry Andric   }
15040b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
15050b57cec5SDimitry Andric }
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15080b57cec5SDimitry Andric //                                  COFF
15090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric static unsigned
getCOFFSectionFlags(SectionKind K,const TargetMachine & TM)15120b57cec5SDimitry Andric getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
15130b57cec5SDimitry Andric   unsigned Flags = 0;
15140b57cec5SDimitry Andric   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   if (K.isMetadata())
15170b57cec5SDimitry Andric     Flags |=
15180b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_DISCARDABLE;
15190b57cec5SDimitry Andric   else if (K.isText())
15200b57cec5SDimitry Andric     Flags |=
15210b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_EXECUTE |
15220b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
15230b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_CODE |
15240b57cec5SDimitry Andric       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
15250b57cec5SDimitry Andric   else if (K.isBSS())
15260b57cec5SDimitry Andric     Flags |=
15270b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
15280b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
15290b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
15300b57cec5SDimitry Andric   else if (K.isThreadLocal())
15310b57cec5SDimitry Andric     Flags |=
15320b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
15330b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
15340b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
15350b57cec5SDimitry Andric   else if (K.isReadOnly() || K.isReadOnlyWithRel())
15360b57cec5SDimitry Andric     Flags |=
15370b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
15380b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ;
15390b57cec5SDimitry Andric   else if (K.isWriteable())
15400b57cec5SDimitry Andric     Flags |=
15410b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
15420b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
15430b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   return Flags;
15460b57cec5SDimitry Andric }
15470b57cec5SDimitry Andric 
getComdatGVForCOFF(const GlobalValue * GV)15480b57cec5SDimitry Andric static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
15490b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
15500b57cec5SDimitry Andric   assert(C && "expected GV to have a Comdat!");
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric   StringRef ComdatGVName = C->getName();
15530b57cec5SDimitry Andric   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
15540b57cec5SDimitry Andric   if (!ComdatGV)
15550b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
15560b57cec5SDimitry Andric                        "' does not exist.");
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   if (ComdatGV->getComdat() != C)
15590b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
15600b57cec5SDimitry Andric                        "' is not a key for its COMDAT.");
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   return ComdatGV;
15630b57cec5SDimitry Andric }
15640b57cec5SDimitry Andric 
getSelectionForCOFF(const GlobalValue * GV)15650b57cec5SDimitry Andric static int getSelectionForCOFF(const GlobalValue *GV) {
15660b57cec5SDimitry Andric   if (const Comdat *C = GV->getComdat()) {
15670b57cec5SDimitry Andric     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
15680b57cec5SDimitry Andric     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
15690b57cec5SDimitry Andric       ComdatKey = GA->getBaseObject();
15700b57cec5SDimitry Andric     if (ComdatKey == GV) {
15710b57cec5SDimitry Andric       switch (C->getSelectionKind()) {
15720b57cec5SDimitry Andric       case Comdat::Any:
15730b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_ANY;
15740b57cec5SDimitry Andric       case Comdat::ExactMatch:
15750b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
15760b57cec5SDimitry Andric       case Comdat::Largest:
15770b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
15785f7ddb14SDimitry Andric       case Comdat::NoDeduplicate:
15790b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
15800b57cec5SDimitry Andric       case Comdat::SameSize:
15810b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
15820b57cec5SDimitry Andric       }
15830b57cec5SDimitry Andric     } else {
15840b57cec5SDimitry Andric       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
15850b57cec5SDimitry Andric     }
15860b57cec5SDimitry Andric   }
15870b57cec5SDimitry Andric   return 0;
15880b57cec5SDimitry Andric }
15890b57cec5SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const15900b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
15910b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
15920b57cec5SDimitry Andric   int Selection = 0;
15930b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
15940b57cec5SDimitry Andric   StringRef Name = GO->getSection();
15950b57cec5SDimitry Andric   StringRef COMDATSymName = "";
15960b57cec5SDimitry Andric   if (GO->hasComdat()) {
15970b57cec5SDimitry Andric     Selection = getSelectionForCOFF(GO);
15980b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
15990b57cec5SDimitry Andric     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
16000b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
16010b57cec5SDimitry Andric     else
16020b57cec5SDimitry Andric       ComdatGV = GO;
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
16050b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
16060b57cec5SDimitry Andric       COMDATSymName = Sym->getName();
16070b57cec5SDimitry Andric       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
16080b57cec5SDimitry Andric     } else {
16090b57cec5SDimitry Andric       Selection = 0;
16100b57cec5SDimitry Andric     }
16110b57cec5SDimitry Andric   }
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
16140b57cec5SDimitry Andric                                      Selection);
16150b57cec5SDimitry Andric }
16160b57cec5SDimitry Andric 
getCOFFSectionNameForUniqueGlobal(SectionKind Kind)16170b57cec5SDimitry Andric static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
16180b57cec5SDimitry Andric   if (Kind.isText())
16190b57cec5SDimitry Andric     return ".text";
16200b57cec5SDimitry Andric   if (Kind.isBSS())
16210b57cec5SDimitry Andric     return ".bss";
16220b57cec5SDimitry Andric   if (Kind.isThreadLocal())
16230b57cec5SDimitry Andric     return ".tls$";
16240b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
16250b57cec5SDimitry Andric     return ".rdata";
16260b57cec5SDimitry Andric   return ".data";
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const16290b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
16300b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
16310b57cec5SDimitry Andric   // If we have -ffunction-sections then we should emit the global value to a
16320b57cec5SDimitry Andric   // uniqued section specifically for it.
16330b57cec5SDimitry Andric   bool EmitUniquedSection;
16340b57cec5SDimitry Andric   if (Kind.isText())
16350b57cec5SDimitry Andric     EmitUniquedSection = TM.getFunctionSections();
16360b57cec5SDimitry Andric   else
16370b57cec5SDimitry Andric     EmitUniquedSection = TM.getDataSections();
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
16400b57cec5SDimitry Andric     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
16450b57cec5SDimitry Andric     int Selection = getSelectionForCOFF(GO);
16460b57cec5SDimitry Andric     if (!Selection)
16470b57cec5SDimitry Andric       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
16480b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
16490b57cec5SDimitry Andric     if (GO->hasComdat())
16500b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
16510b57cec5SDimitry Andric     else
16520b57cec5SDimitry Andric       ComdatGV = GO;
16530b57cec5SDimitry Andric 
16540b57cec5SDimitry Andric     unsigned UniqueID = MCContext::GenericSectionID;
16550b57cec5SDimitry Andric     if (EmitUniquedSection)
16560b57cec5SDimitry Andric       UniqueID = NextUniqueID++;
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
16590b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
16600b57cec5SDimitry Andric       StringRef COMDATSymName = Sym->getName();
16610b57cec5SDimitry Andric 
1662af732203SDimitry Andric       if (const auto *F = dyn_cast<Function>(GO))
1663af732203SDimitry Andric         if (Optional<StringRef> Prefix = F->getSectionPrefix())
1664af732203SDimitry Andric           raw_svector_ostream(Name) << '$' << *Prefix;
1665af732203SDimitry Andric 
16660b57cec5SDimitry Andric       // Append "$symbol" to the section name *before* IR-level mangling is
16670b57cec5SDimitry Andric       // applied when targetting mingw. This is what GCC does, and the ld.bfd
16680b57cec5SDimitry Andric       // COFF linker will not properly handle comdats otherwise.
16695f7ddb14SDimitry Andric       if (getContext().getTargetTriple().isWindowsGNUEnvironment())
16700b57cec5SDimitry Andric         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind,
16730b57cec5SDimitry Andric                                          COMDATSymName, Selection, UniqueID);
16740b57cec5SDimitry Andric     } else {
16750b57cec5SDimitry Andric       SmallString<256> TmpData;
16760b57cec5SDimitry Andric       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
16770b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
16780b57cec5SDimitry Andric                                          Selection, UniqueID);
16790b57cec5SDimitry Andric     }
16800b57cec5SDimitry Andric   }
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   if (Kind.isText())
16830b57cec5SDimitry Andric     return TextSection;
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   if (Kind.isThreadLocal())
16860b57cec5SDimitry Andric     return TLSDataSection;
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
16890b57cec5SDimitry Andric     return ReadOnlySection;
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   // Note: we claim that common symbols are put in BSSSection, but they are
16920b57cec5SDimitry Andric   // really emitted with the magic .comm directive, which creates a symbol table
16930b57cec5SDimitry Andric   // entry but not a section.
16940b57cec5SDimitry Andric   if (Kind.isBSS() || Kind.isCommon())
16950b57cec5SDimitry Andric     return BSSSection;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   return DataSection;
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,const TargetMachine & TM) const17000b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::getNameWithPrefix(
17010b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
17020b57cec5SDimitry Andric     const TargetMachine &TM) const {
17030b57cec5SDimitry Andric   bool CannotUsePrivateLabel = false;
17040b57cec5SDimitry Andric   if (GV->hasPrivateLinkage() &&
17050b57cec5SDimitry Andric       ((isa<Function>(GV) && TM.getFunctionSections()) ||
17060b57cec5SDimitry Andric        (isa<GlobalVariable>(GV) && TM.getDataSections())))
17070b57cec5SDimitry Andric     CannotUsePrivateLabel = true;
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const17120b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
17130b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
17140b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
17150b57cec5SDimitry Andric   // the table doesn't prevent the removal.
17160b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
17170b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
17180b57cec5SDimitry Andric   if (!EmitUniqueSection)
17190b57cec5SDimitry Andric     return ReadOnlySection;
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   // FIXME: we should produce a symbol for F instead.
17220b57cec5SDimitry Andric   if (F.hasPrivateLinkage())
17230b57cec5SDimitry Andric     return ReadOnlySection;
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric   MCSymbol *Sym = TM.getSymbol(&F);
17260b57cec5SDimitry Andric   StringRef COMDATSymName = Sym->getName();
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric   SectionKind Kind = SectionKind::getReadOnly();
17290b57cec5SDimitry Andric   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
17300b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
17310b57cec5SDimitry Andric   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
17320b57cec5SDimitry Andric   unsigned UniqueID = NextUniqueID++;
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric   return getContext().getCOFFSection(
17350b57cec5SDimitry Andric       SecName, Characteristics, Kind, COMDATSymName,
17360b57cec5SDimitry Andric       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
17370b57cec5SDimitry Andric }
17380b57cec5SDimitry Andric 
emitModuleMetadata(MCStreamer & Streamer,Module & M) const17390b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
17400b57cec5SDimitry Andric                                                       Module &M) const {
1741af732203SDimitry Andric   emitLinkerDirectives(Streamer, M);
1742af732203SDimitry Andric 
1743af732203SDimitry Andric   unsigned Version = 0;
1744af732203SDimitry Andric   unsigned Flags = 0;
1745af732203SDimitry Andric   StringRef Section;
1746af732203SDimitry Andric 
1747af732203SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
1748af732203SDimitry Andric   if (!Section.empty()) {
1749af732203SDimitry Andric     auto &C = getContext();
1750af732203SDimitry Andric     auto *S = C.getCOFFSection(Section,
1751af732203SDimitry Andric                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1752af732203SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ,
1753af732203SDimitry Andric                                SectionKind::getReadOnly());
1754af732203SDimitry Andric     Streamer.SwitchSection(S);
1755af732203SDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1756af732203SDimitry Andric     Streamer.emitInt32(Version);
1757af732203SDimitry Andric     Streamer.emitInt32(Flags);
1758af732203SDimitry Andric     Streamer.AddBlankLine();
1759af732203SDimitry Andric   }
1760af732203SDimitry Andric 
1761af732203SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1762af732203SDimitry Andric }
1763af732203SDimitry Andric 
emitLinkerDirectives(MCStreamer & Streamer,Module & M) const1764af732203SDimitry Andric void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1765af732203SDimitry Andric     MCStreamer &Streamer, Module &M) const {
17660b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
17670b57cec5SDimitry Andric     // Emit the linker options to the linker .drectve section.  According to the
17680b57cec5SDimitry Andric     // spec, this section is a space-separated string containing flags for
17690b57cec5SDimitry Andric     // linker.
17700b57cec5SDimitry Andric     MCSection *Sec = getDrectveSection();
17710b57cec5SDimitry Andric     Streamer.SwitchSection(Sec);
1772480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
17730b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
17740b57cec5SDimitry Andric         // Lead with a space for consistency with our dllexport implementation.
17750b57cec5SDimitry Andric         std::string Directive(" ");
17765ffd83dbSDimitry Andric         Directive.append(std::string(cast<MDString>(Piece)->getString()));
17775ffd83dbSDimitry Andric         Streamer.emitBytes(Directive);
17780b57cec5SDimitry Andric       }
17790b57cec5SDimitry Andric     }
17800b57cec5SDimitry Andric   }
17810b57cec5SDimitry Andric 
1782af732203SDimitry Andric   // Emit /EXPORT: flags for each exported global as necessary.
1783af732203SDimitry Andric   std::string Flags;
1784af732203SDimitry Andric   for (const GlobalValue &GV : M.global_values()) {
1785af732203SDimitry Andric     raw_string_ostream OS(Flags);
17865f7ddb14SDimitry Andric     emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
17875f7ddb14SDimitry Andric                                  getMangler());
1788af732203SDimitry Andric     OS.flush();
1789af732203SDimitry Andric     if (!Flags.empty()) {
1790af732203SDimitry Andric       Streamer.SwitchSection(getDrectveSection());
1791af732203SDimitry Andric       Streamer.emitBytes(Flags);
1792af732203SDimitry Andric     }
1793af732203SDimitry Andric     Flags.clear();
1794af732203SDimitry Andric   }
17950b57cec5SDimitry Andric 
1796af732203SDimitry Andric   // Emit /INCLUDE: flags for each used global as necessary.
1797af732203SDimitry Andric   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1798af732203SDimitry Andric     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1799af732203SDimitry Andric     assert(isa<ArrayType>(LU->getValueType()) &&
1800af732203SDimitry Andric            "expected llvm.used to be an array type");
1801af732203SDimitry Andric     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1802af732203SDimitry Andric       for (const Value *Op : A->operands()) {
1803af732203SDimitry Andric         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1804af732203SDimitry Andric         // Global symbols with internal or private linkage are not visible to
1805af732203SDimitry Andric         // the linker, and thus would cause an error when the linker tried to
1806af732203SDimitry Andric         // preserve the symbol due to the `/include:` directive.
1807af732203SDimitry Andric         if (GV->hasLocalLinkage())
1808af732203SDimitry Andric           continue;
18090b57cec5SDimitry Andric 
1810af732203SDimitry Andric         raw_string_ostream OS(Flags);
18115f7ddb14SDimitry Andric         emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
18125f7ddb14SDimitry Andric                                    getMangler());
1813af732203SDimitry Andric         OS.flush();
1814af732203SDimitry Andric 
1815af732203SDimitry Andric         if (!Flags.empty()) {
1816af732203SDimitry Andric           Streamer.SwitchSection(getDrectveSection());
1817af732203SDimitry Andric           Streamer.emitBytes(Flags);
1818af732203SDimitry Andric         }
1819af732203SDimitry Andric         Flags.clear();
1820af732203SDimitry Andric       }
1821af732203SDimitry Andric     }
1822af732203SDimitry Andric   }
18230b57cec5SDimitry Andric }
18240b57cec5SDimitry Andric 
Initialize(MCContext & Ctx,const TargetMachine & TM)18250b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
18260b57cec5SDimitry Andric                                               const TargetMachine &TM) {
18270b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1828af732203SDimitry Andric   this->TM = &TM;
18290b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
18300b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
18310b57cec5SDimitry Andric     StaticCtorSection =
18320b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
18330b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
18340b57cec5SDimitry Andric                            SectionKind::getReadOnly());
18350b57cec5SDimitry Andric     StaticDtorSection =
18360b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
18370b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
18380b57cec5SDimitry Andric                            SectionKind::getReadOnly());
18390b57cec5SDimitry Andric   } else {
18400b57cec5SDimitry Andric     StaticCtorSection = Ctx.getCOFFSection(
18410b57cec5SDimitry Andric         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
18420b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
18430b57cec5SDimitry Andric         SectionKind::getData());
18440b57cec5SDimitry Andric     StaticDtorSection = Ctx.getCOFFSection(
18450b57cec5SDimitry Andric         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
18460b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
18470b57cec5SDimitry Andric         SectionKind::getData());
18480b57cec5SDimitry Andric   }
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
getCOFFStaticStructorSection(MCContext & Ctx,const Triple & T,bool IsCtor,unsigned Priority,const MCSymbol * KeySym,MCSectionCOFF * Default)18510b57cec5SDimitry Andric static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
18520b57cec5SDimitry Andric                                                    const Triple &T, bool IsCtor,
18530b57cec5SDimitry Andric                                                    unsigned Priority,
18540b57cec5SDimitry Andric                                                    const MCSymbol *KeySym,
18550b57cec5SDimitry Andric                                                    MCSectionCOFF *Default) {
18560b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
18570b57cec5SDimitry Andric     // If the priority is the default, use .CRT$XCU, possibly associative.
18580b57cec5SDimitry Andric     if (Priority == 65535)
18590b57cec5SDimitry Andric       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric     // Otherwise, we need to compute a new section name. Low priorities should
18620b57cec5SDimitry Andric     // run earlier. The linker will sort sections ASCII-betically, and we need a
18630b57cec5SDimitry Andric     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
18640b57cec5SDimitry Andric     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
18650b57cec5SDimitry Andric     // low priorities need to sort before 'L', since the CRT uses that
18660b57cec5SDimitry Andric     // internally, so we use ".CRT$XCA00001" for them.
18670b57cec5SDimitry Andric     SmallString<24> Name;
18680b57cec5SDimitry Andric     raw_svector_ostream OS(Name);
18698bcb0991SDimitry Andric     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
18708bcb0991SDimitry Andric         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
18710b57cec5SDimitry Andric     MCSectionCOFF *Sec = Ctx.getCOFFSection(
18720b57cec5SDimitry Andric         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
18730b57cec5SDimitry Andric         SectionKind::getReadOnly());
18740b57cec5SDimitry Andric     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   std::string Name = IsCtor ? ".ctors" : ".dtors";
18780b57cec5SDimitry Andric   if (Priority != 65535)
18790b57cec5SDimitry Andric     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   return Ctx.getAssociativeCOFFSection(
18820b57cec5SDimitry Andric       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
18830b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ |
18840b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_WRITE,
18850b57cec5SDimitry Andric                          SectionKind::getData()),
18860b57cec5SDimitry Andric       KeySym, 0);
18870b57cec5SDimitry Andric }
18880b57cec5SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const18890b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
18900b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
18915f7ddb14SDimitry Andric   return getCOFFStaticStructorSection(
18925f7ddb14SDimitry Andric       getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
18930b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticCtorSection));
18940b57cec5SDimitry Andric }
18950b57cec5SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const18960b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
18970b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
18985f7ddb14SDimitry Andric   return getCOFFStaticStructorSection(
18995f7ddb14SDimitry Andric       getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
19000b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticDtorSection));
19010b57cec5SDimitry Andric }
19020b57cec5SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const19030b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
19040b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
19050b57cec5SDimitry Andric     const TargetMachine &TM) const {
19060b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
19070b57cec5SDimitry Andric   if (T.isOSCygMing())
19080b57cec5SDimitry Andric     return nullptr;
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric   // Our symbols should exist in address space zero, cowardly no-op if
19110b57cec5SDimitry Andric   // otherwise.
19120b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
19130b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0)
19140b57cec5SDimitry Andric     return nullptr;
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric   // Both ptrtoint instructions must wrap global objects:
19170b57cec5SDimitry Andric   // - Only global variables are eligible for image relative relocations.
19180b57cec5SDimitry Andric   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
19190b57cec5SDimitry Andric   // We expect __ImageBase to be a global variable without a section, externally
19200b57cec5SDimitry Andric   // defined.
19210b57cec5SDimitry Andric   //
19220b57cec5SDimitry Andric   // It should look something like this: @__ImageBase = external constant i8
19230b57cec5SDimitry Andric   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
19240b57cec5SDimitry Andric       LHS->isThreadLocal() || RHS->isThreadLocal() ||
19250b57cec5SDimitry Andric       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
19260b57cec5SDimitry Andric       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
19270b57cec5SDimitry Andric     return nullptr;
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
19300b57cec5SDimitry Andric                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
19310b57cec5SDimitry Andric                                  getContext());
19320b57cec5SDimitry Andric }
19330b57cec5SDimitry Andric 
APIntToHexString(const APInt & AI)19340b57cec5SDimitry Andric static std::string APIntToHexString(const APInt &AI) {
19350b57cec5SDimitry Andric   unsigned Width = (AI.getBitWidth() / 8) * 2;
19365f7ddb14SDimitry Andric   std::string HexString = toString(AI, 16, /*Signed=*/false);
19375ffd83dbSDimitry Andric   llvm::transform(HexString, HexString.begin(), tolower);
19380b57cec5SDimitry Andric   unsigned Size = HexString.size();
19390b57cec5SDimitry Andric   assert(Width >= Size && "hex string is too large!");
19400b57cec5SDimitry Andric   HexString.insert(HexString.begin(), Width - Size, '0');
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric   return HexString;
19430b57cec5SDimitry Andric }
19440b57cec5SDimitry Andric 
scalarConstantToHexString(const Constant * C)19450b57cec5SDimitry Andric static std::string scalarConstantToHexString(const Constant *C) {
19460b57cec5SDimitry Andric   Type *Ty = C->getType();
19470b57cec5SDimitry Andric   if (isa<UndefValue>(C)) {
19480b57cec5SDimitry Andric     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
19490b57cec5SDimitry Andric   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
19500b57cec5SDimitry Andric     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
19510b57cec5SDimitry Andric   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
19520b57cec5SDimitry Andric     return APIntToHexString(CI->getValue());
19530b57cec5SDimitry Andric   } else {
19540b57cec5SDimitry Andric     unsigned NumElements;
19555ffd83dbSDimitry Andric     if (auto *VTy = dyn_cast<VectorType>(Ty))
19565ffd83dbSDimitry Andric       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
19570b57cec5SDimitry Andric     else
19580b57cec5SDimitry Andric       NumElements = Ty->getArrayNumElements();
19590b57cec5SDimitry Andric     std::string HexString;
19600b57cec5SDimitry Andric     for (int I = NumElements - 1, E = -1; I != E; --I)
19610b57cec5SDimitry Andric       HexString += scalarConstantToHexString(C->getAggregateElement(I));
19620b57cec5SDimitry Andric     return HexString;
19630b57cec5SDimitry Andric   }
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric 
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const19660b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
19670b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
19685ffd83dbSDimitry Andric     Align &Alignment) const {
19690b57cec5SDimitry Andric   if (Kind.isMergeableConst() && C &&
19700b57cec5SDimitry Andric       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
19710b57cec5SDimitry Andric     // This creates comdat sections with the given symbol name, but unless
19720b57cec5SDimitry Andric     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
19730b57cec5SDimitry Andric     // will be created with a null storage class, which makes GNU binutils
19740b57cec5SDimitry Andric     // error out.
19750b57cec5SDimitry Andric     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
19760b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_MEM_READ |
19770b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_LNK_COMDAT;
19780b57cec5SDimitry Andric     std::string COMDATSymName;
19790b57cec5SDimitry Andric     if (Kind.isMergeableConst4()) {
19805ffd83dbSDimitry Andric       if (Alignment <= 4) {
19810b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19825ffd83dbSDimitry Andric         Alignment = Align(4);
19830b57cec5SDimitry Andric       }
19840b57cec5SDimitry Andric     } else if (Kind.isMergeableConst8()) {
19855ffd83dbSDimitry Andric       if (Alignment <= 8) {
19860b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19875ffd83dbSDimitry Andric         Alignment = Align(8);
19880b57cec5SDimitry Andric       }
19890b57cec5SDimitry Andric     } else if (Kind.isMergeableConst16()) {
19900b57cec5SDimitry Andric       // FIXME: These may not be appropriate for non-x86 architectures.
19915ffd83dbSDimitry Andric       if (Alignment <= 16) {
19920b57cec5SDimitry Andric         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
19935ffd83dbSDimitry Andric         Alignment = Align(16);
19940b57cec5SDimitry Andric       }
19950b57cec5SDimitry Andric     } else if (Kind.isMergeableConst32()) {
19965ffd83dbSDimitry Andric       if (Alignment <= 32) {
19970b57cec5SDimitry Andric         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
19985ffd83dbSDimitry Andric         Alignment = Align(32);
19990b57cec5SDimitry Andric       }
20000b57cec5SDimitry Andric     }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric     if (!COMDATSymName.empty())
20030b57cec5SDimitry Andric       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
20040b57cec5SDimitry Andric                                          COMDATSymName,
20050b57cec5SDimitry Andric                                          COFF::IMAGE_COMDAT_SELECT_ANY);
20060b57cec5SDimitry Andric   }
20070b57cec5SDimitry Andric 
20085ffd83dbSDimitry Andric   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
20095ffd83dbSDimitry Andric                                                          Alignment);
20100b57cec5SDimitry Andric }
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20130b57cec5SDimitry Andric //                                  Wasm
20140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20150b57cec5SDimitry Andric 
getWasmComdat(const GlobalValue * GV)20160b57cec5SDimitry Andric static const Comdat *getWasmComdat(const GlobalValue *GV) {
20170b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
20180b57cec5SDimitry Andric   if (!C)
20190b57cec5SDimitry Andric     return nullptr;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   if (C->getSelectionKind() != Comdat::Any)
20220b57cec5SDimitry Andric     report_fatal_error("WebAssembly COMDATs only support "
20230b57cec5SDimitry Andric                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
20240b57cec5SDimitry Andric                        "lowered.");
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric   return C;
20270b57cec5SDimitry Andric }
20280b57cec5SDimitry Andric 
getWasmSectionFlags(SectionKind K)20295f7ddb14SDimitry Andric static unsigned getWasmSectionFlags(SectionKind K) {
20305f7ddb14SDimitry Andric   unsigned Flags = 0;
20315f7ddb14SDimitry Andric 
20325f7ddb14SDimitry Andric   if (K.isThreadLocal())
20335f7ddb14SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_TLS;
20345f7ddb14SDimitry Andric 
20355f7ddb14SDimitry Andric   if (K.isMergeableCString())
20365f7ddb14SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_STRINGS;
20375f7ddb14SDimitry Andric 
20385f7ddb14SDimitry Andric   // TODO(sbc): Add suport for K.isMergeableConst()
20395f7ddb14SDimitry Andric 
20405f7ddb14SDimitry Andric   return Flags;
20415f7ddb14SDimitry Andric }
20425f7ddb14SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const20430b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
20440b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
20450b57cec5SDimitry Andric   // We don't support explict section names for functions in the wasm object
20460b57cec5SDimitry Andric   // format.  Each function has to be in its own unique section.
20470b57cec5SDimitry Andric   if (isa<Function>(GO)) {
20480b57cec5SDimitry Andric     return SelectSectionForGlobal(GO, Kind, TM);
20490b57cec5SDimitry Andric   }
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   StringRef Name = GO->getSection();
20520b57cec5SDimitry 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();
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric   StringRef Group = "";
20620b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
20630b57cec5SDimitry Andric     Group = C->getName();
20640b57cec5SDimitry Andric   }
20650b57cec5SDimitry Andric 
20665f7ddb14SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
20675f7ddb14SDimitry Andric   MCSectionWasm *Section = getContext().getWasmSection(
20685f7ddb14SDimitry Andric       Name, Kind, Flags, Group, MCContext::GenericSectionID);
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   return Section;
20710b57cec5SDimitry Andric }
20720b57cec5SDimitry Andric 
selectWasmSectionForGlobal(MCContext & Ctx,const GlobalObject * GO,SectionKind Kind,Mangler & Mang,const TargetMachine & TM,bool EmitUniqueSection,unsigned * NextUniqueID)20730b57cec5SDimitry Andric static MCSectionWasm *selectWasmSectionForGlobal(
20740b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
20750b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
20760b57cec5SDimitry Andric   StringRef Group = "";
20770b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
20780b57cec5SDimitry Andric     Group = C->getName();
20790b57cec5SDimitry Andric   }
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric   bool UniqueSectionNames = TM.getUniqueSectionNames();
20820b57cec5SDimitry Andric   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
20850b57cec5SDimitry Andric     const auto &OptionalPrefix = F->getSectionPrefix();
20860b57cec5SDimitry Andric     if (OptionalPrefix)
2087af732203SDimitry Andric       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
20880b57cec5SDimitry Andric   }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   if (EmitUniqueSection && UniqueSectionNames) {
20910b57cec5SDimitry Andric     Name.push_back('.');
20920b57cec5SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, true);
20930b57cec5SDimitry Andric   }
20940b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
20950b57cec5SDimitry Andric   if (EmitUniqueSection && !UniqueSectionNames) {
20960b57cec5SDimitry Andric     UniqueID = *NextUniqueID;
20970b57cec5SDimitry Andric     (*NextUniqueID)++;
20980b57cec5SDimitry Andric   }
20990b57cec5SDimitry Andric 
21005f7ddb14SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
21015f7ddb14SDimitry Andric   return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
21020b57cec5SDimitry Andric }
21030b57cec5SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const21040b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
21050b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric   if (Kind.isCommon())
21080b57cec5SDimitry Andric     report_fatal_error("mergable sections not supported yet on wasm");
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
21110b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
21120b57cec5SDimitry Andric   bool EmitUniqueSection = false;
21130b57cec5SDimitry Andric   if (Kind.isText())
21140b57cec5SDimitry Andric     EmitUniqueSection = TM.getFunctionSections();
21150b57cec5SDimitry Andric   else
21160b57cec5SDimitry Andric     EmitUniqueSection = TM.getDataSections();
21170b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
21200b57cec5SDimitry Andric                                     EmitUniqueSection, &NextUniqueID);
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const21230b57cec5SDimitry Andric bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
21240b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
21250b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
21260b57cec5SDimitry Andric   // that can be marked non-executable.
21270b57cec5SDimitry Andric   return false;
21280b57cec5SDimitry Andric }
21290b57cec5SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const21300b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
21310b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
21320b57cec5SDimitry Andric     const TargetMachine &TM) const {
21330b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
21340b57cec5SDimitry Andric   // functions.
21350b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
21360b57cec5SDimitry Andric     return nullptr;
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   // Basic sanity checks.
21390b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
21400b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
21410b57cec5SDimitry Andric       RHS->isThreadLocal())
21420b57cec5SDimitry Andric     return nullptr;
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
21450b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
21460b57cec5SDimitry Andric                               getContext()),
21470b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
21480b57cec5SDimitry Andric }
21490b57cec5SDimitry Andric 
InitializeWasm()21500b57cec5SDimitry Andric void TargetLoweringObjectFileWasm::InitializeWasm() {
21510b57cec5SDimitry Andric   StaticCtorSection =
21520b57cec5SDimitry Andric       getContext().getWasmSection(".init_array", SectionKind::getData());
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
21550b57cec5SDimitry Andric   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
21560b57cec5SDimitry Andric   TTypeEncoding = dwarf::DW_EH_PE_absptr;
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const21590b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
21600b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
21610b57cec5SDimitry Andric   return Priority == UINT16_MAX ?
21620b57cec5SDimitry Andric          StaticCtorSection :
21630b57cec5SDimitry Andric          getContext().getWasmSection(".init_array." + utostr(Priority),
21640b57cec5SDimitry Andric                                      SectionKind::getData());
21650b57cec5SDimitry Andric }
21660b57cec5SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const21670b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
21680b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
21690b57cec5SDimitry Andric   llvm_unreachable("@llvm.global_dtors should have been lowered already");
21700b57cec5SDimitry Andric   return nullptr;
21710b57cec5SDimitry Andric }
21728bcb0991SDimitry Andric 
21738bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
21748bcb0991SDimitry Andric //                                  XCOFF
21758bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
ShouldEmitEHBlock(const MachineFunction * MF)2176af732203SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2177af732203SDimitry Andric     const MachineFunction *MF) {
2178af732203SDimitry Andric   if (!MF->getLandingPads().empty())
2179af732203SDimitry Andric     return true;
2180af732203SDimitry Andric 
2181af732203SDimitry Andric   const Function &F = MF->getFunction();
2182af732203SDimitry Andric   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2183af732203SDimitry Andric     return false;
2184af732203SDimitry Andric 
21855f7ddb14SDimitry Andric   const GlobalValue *Per =
21865f7ddb14SDimitry Andric       dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
21875f7ddb14SDimitry Andric   assert(Per && "Personality routine is not a GlobalValue type.");
2188af732203SDimitry Andric   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2189af732203SDimitry Andric     return false;
2190af732203SDimitry Andric 
2191af732203SDimitry Andric   return true;
2192af732203SDimitry Andric }
2193af732203SDimitry Andric 
ShouldSetSSPCanaryBitInTB(const MachineFunction * MF)21945f7ddb14SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
21955f7ddb14SDimitry Andric     const MachineFunction *MF) {
21965f7ddb14SDimitry Andric   const Function &F = MF->getFunction();
21975f7ddb14SDimitry Andric   if (!F.hasStackProtectorFnAttr())
21985f7ddb14SDimitry Andric     return false;
21995f7ddb14SDimitry Andric   // FIXME: check presence of canary word
22005f7ddb14SDimitry Andric   // There are cases that the stack protectors are not really inserted even if
22015f7ddb14SDimitry Andric   // the attributes are on.
22025f7ddb14SDimitry Andric   return true;
22035f7ddb14SDimitry Andric }
22045f7ddb14SDimitry Andric 
2205af732203SDimitry Andric MCSymbol *
getEHInfoTableSymbol(const MachineFunction * MF)2206af732203SDimitry Andric TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2207af732203SDimitry Andric   return MF->getMMI().getContext().getOrCreateSymbol(
2208af732203SDimitry Andric       "__ehinfo." + Twine(MF->getFunctionNumber()));
2209af732203SDimitry Andric }
2210af732203SDimitry Andric 
22115ffd83dbSDimitry Andric MCSymbol *
getTargetSymbol(const GlobalValue * GV,const TargetMachine & TM) const22125ffd83dbSDimitry 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.
2216af732203SDimitry Andric   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2217af732203SDimitry 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)) {
22235f7ddb14SDimitry Andric     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
22245f7ddb14SDimitry Andric       if (GVar->hasAttribute("toc-data"))
22255f7ddb14SDimitry Andric         return cast<MCSectionXCOFF>(
22265f7ddb14SDimitry Andric                    SectionForGlobal(GVar, SectionKind::getData(), TM))
22275f7ddb14SDimitry Andric             ->getQualNameSymbol();
22285f7ddb14SDimitry 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();
22385f7ddb14SDimitry Andric     if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
22395f7ddb14SDimitry 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 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const22488bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
22498bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2250af732203SDimitry Andric   if (!GO->hasSection())
2251af732203SDimitry Andric     report_fatal_error("#pragma clang section is not yet supported");
2252af732203SDimitry Andric 
2253af732203SDimitry Andric   StringRef SectionName = GO->getSection();
22545f7ddb14SDimitry Andric 
22555f7ddb14SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
22565f7ddb14SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
22575f7ddb14SDimitry Andric     if (GVar->hasAttribute("toc-data"))
22585f7ddb14SDimitry Andric       return getContext().getXCOFFSection(
22595f7ddb14SDimitry Andric           SectionName, Kind,
22605f7ddb14SDimitry Andric           XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
22615f7ddb14SDimitry Andric           /* MultiSymbolsAllowed*/ true);
22625f7ddb14SDimitry Andric 
2263af732203SDimitry Andric   XCOFF::StorageMappingClass MappingClass;
2264af732203SDimitry Andric   if (Kind.isText())
2265af732203SDimitry Andric     MappingClass = XCOFF::XMC_PR;
2266af732203SDimitry Andric   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2267af732203SDimitry Andric     MappingClass = XCOFF::XMC_RW;
2268af732203SDimitry Andric   else if (Kind.isReadOnly())
2269af732203SDimitry Andric     MappingClass = XCOFF::XMC_RO;
2270af732203SDimitry Andric   else
2271af732203SDimitry Andric     report_fatal_error("XCOFF other section types not yet implemented.");
2272af732203SDimitry Andric 
22735f7ddb14SDimitry Andric   return getContext().getXCOFFSection(
22745f7ddb14SDimitry Andric       SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
22755f7ddb14SDimitry Andric       /* MultiSymbolsAllowed*/ true);
22768bcb0991SDimitry Andric }
22778bcb0991SDimitry Andric 
getSectionForExternalReference(const GlobalObject * GO,const TargetMachine & TM) const22785ffd83dbSDimitry 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 
22865f7ddb14SDimitry Andric   XCOFF::StorageMappingClass SMC =
22875f7ddb14SDimitry Andric       isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
22885f7ddb14SDimitry Andric   if (GO->isThreadLocal())
22895f7ddb14SDimitry Andric     SMC = XCOFF::XMC_UL;
22905f7ddb14SDimitry Andric 
22915ffd83dbSDimitry Andric   // Externals go into a csect of type ER.
22925ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
22935f7ddb14SDimitry Andric       Name, SectionKind::getMetadata(),
22945f7ddb14SDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
22955ffd83dbSDimitry Andric }
22965ffd83dbSDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const22978bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
22988bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
22995f7ddb14SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
23005f7ddb14SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
23015f7ddb14SDimitry Andric     if (GVar->hasAttribute("toc-data")) {
23028bcb0991SDimitry Andric       SmallString<128> Name;
23038bcb0991SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23048bcb0991SDimitry Andric       return getContext().getXCOFFSection(
23055f7ddb14SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
23065f7ddb14SDimitry Andric           /* MultiSymbolsAllowed*/ true);
23075f7ddb14SDimitry Andric     }
23085f7ddb14SDimitry Andric 
23095f7ddb14SDimitry Andric   // Common symbols go into a csect with matching name which will get mapped
23105f7ddb14SDimitry Andric   // into the .bss section.
23115f7ddb14SDimitry Andric   // Zero-initialized local TLS symbols go into a csect with matching name which
23125f7ddb14SDimitry Andric   // will get mapped into the .tbss section.
23135f7ddb14SDimitry Andric   if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
23145f7ddb14SDimitry Andric     SmallString<128> Name;
23155f7ddb14SDimitry Andric     getNameWithPrefix(Name, GO, TM);
23165f7ddb14SDimitry Andric     XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
23175f7ddb14SDimitry Andric                                      : Kind.isCommon() ? XCOFF::XMC_RW
23185f7ddb14SDimitry Andric                                                        : XCOFF::XMC_UL;
23195f7ddb14SDimitry Andric     return getContext().getXCOFFSection(
23205f7ddb14SDimitry 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 
2332af732203SDimitry Andric     if (TM.getDataSections())
2333af732203SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2334af732203SDimitry Andric 
2335480093f4SDimitry Andric     return getContext().getXCOFFSection(
23365f7ddb14SDimitry Andric         Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
2337af732203SDimitry Andric         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2338480093f4SDimitry Andric   }
2339480093f4SDimitry Andric 
2340af732203SDimitry Andric   if (Kind.isText()) {
2341af732203SDimitry Andric     if (TM.getFunctionSections()) {
2342af732203SDimitry Andric       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2343af732203SDimitry Andric           ->getRepresentedCsect();
2344af732203SDimitry Andric     }
23458bcb0991SDimitry Andric     return TextSection;
2346af732203SDimitry Andric   }
23478bcb0991SDimitry Andric 
2348af732203SDimitry Andric   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2349af732203SDimitry Andric   // user may want to have read-only data with relocations placed into a
2350af732203SDimitry Andric   // read-only section by the compiler.
2351af732203SDimitry Andric   // For BSS kind, zero initialized data must be emitted to the .data section
2352af732203SDimitry Andric   // because external linkage control sections that get mapped to the .bss
2353af732203SDimitry Andric   // section will be linked as tentative defintions, which is only appropriate
2354af732203SDimitry Andric   // for SectionKind::Common.
2355af732203SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2356af732203SDimitry Andric     if (TM.getDataSections()) {
2357af732203SDimitry Andric       SmallString<128> Name;
2358af732203SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23595f7ddb14SDimitry Andric       return getContext().getXCOFFSection(
23605f7ddb14SDimitry Andric           Name, SectionKind::getData(),
23615f7ddb14SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
2362af732203SDimitry Andric     }
23638bcb0991SDimitry Andric     return DataSection;
2364af732203SDimitry Andric   }
23658bcb0991SDimitry Andric 
2366af732203SDimitry Andric   if (Kind.isReadOnly()) {
2367af732203SDimitry Andric     if (TM.getDataSections()) {
2368af732203SDimitry Andric       SmallString<128> Name;
2369af732203SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23705f7ddb14SDimitry Andric       return getContext().getXCOFFSection(
23715f7ddb14SDimitry Andric           Name, SectionKind::getReadOnly(),
23725f7ddb14SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2373af732203SDimitry Andric     }
2374480093f4SDimitry Andric     return ReadOnlySection;
2375af732203SDimitry Andric   }
2376480093f4SDimitry Andric 
23775f7ddb14SDimitry Andric   // External/weak TLS data and initialized local TLS data are not eligible
23785f7ddb14SDimitry Andric   // to be put into common csect. If data sections are enabled, thread
23795f7ddb14SDimitry Andric   // data are emitted into separate sections. Otherwise, thread data
23805f7ddb14SDimitry Andric   // are emitted into the .tdata section.
23815f7ddb14SDimitry Andric   if (Kind.isThreadLocal()) {
23825f7ddb14SDimitry Andric     if (TM.getDataSections()) {
23835f7ddb14SDimitry Andric       SmallString<128> Name;
23845f7ddb14SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23855f7ddb14SDimitry Andric       return getContext().getXCOFFSection(
23865f7ddb14SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
23875f7ddb14SDimitry Andric     }
23885f7ddb14SDimitry Andric     return TLSDataSection;
23895f7ddb14SDimitry Andric   }
23905f7ddb14SDimitry Andric 
23918bcb0991SDimitry Andric   report_fatal_error("XCOFF other section types not yet implemented.");
23928bcb0991SDimitry Andric }
23938bcb0991SDimitry Andric 
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const2394480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2395480093f4SDimitry Andric     const Function &F, const TargetMachine &TM) const {
2396480093f4SDimitry Andric   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2397af732203SDimitry Andric 
2398af732203SDimitry Andric   if (!TM.getFunctionSections())
2399480093f4SDimitry Andric     return ReadOnlySection;
2400af732203SDimitry Andric 
2401af732203SDimitry Andric   // If the function can be removed, produce a unique section so that
2402af732203SDimitry Andric   // the table doesn't prevent the removal.
2403af732203SDimitry Andric   SmallString<128> NameStr(".rodata.jmp..");
2404af732203SDimitry Andric   getNameWithPrefix(NameStr, &F, TM);
24055f7ddb14SDimitry Andric   return getContext().getXCOFFSection(
24065f7ddb14SDimitry Andric       NameStr, SectionKind::getReadOnly(),
24075f7ddb14SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2408480093f4SDimitry Andric }
2409480093f4SDimitry Andric 
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const24108bcb0991SDimitry 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.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const2417480093f4SDimitry 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 
Initialize(MCContext & Ctx,const TargetMachine & TgtM)24248bcb0991SDimitry Andric void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
24258bcb0991SDimitry Andric                                                const TargetMachine &TgtM) {
24268bcb0991SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2427af732203SDimitry Andric   TTypeEncoding =
2428af732203SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2429af732203SDimitry Andric       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2430af732203SDimitry Andric                                             : dwarf::DW_EH_PE_sdata8);
24318bcb0991SDimitry Andric   PersonalityEncoding = 0;
24328bcb0991SDimitry Andric   LSDAEncoding = 0;
2433af732203SDimitry Andric   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
24348bcb0991SDimitry Andric }
24358bcb0991SDimitry Andric 
getStaticCtorSection(unsigned Priority,const MCSymbol * KeySym) const24368bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
24378bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2438af732203SDimitry Andric   report_fatal_error("no static constructor section on AIX");
24398bcb0991SDimitry Andric }
24408bcb0991SDimitry Andric 
getStaticDtorSection(unsigned Priority,const MCSymbol * KeySym) const24418bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
24428bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2443af732203SDimitry Andric   report_fatal_error("no static destructor section on AIX");
24448bcb0991SDimitry Andric }
24458bcb0991SDimitry Andric 
lowerRelativeReference(const GlobalValue * LHS,const GlobalValue * RHS,const TargetMachine & TM) const24468bcb0991SDimitry 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 
2452af732203SDimitry Andric XCOFF::StorageClass
getStorageClassForGlobal(const GlobalValue * GV)2453af732203SDimitry Andric TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2454af732203SDimitry Andric   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2455af732203SDimitry Andric 
2456af732203SDimitry 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 
getFunctionEntryPointSymbol(const GlobalValue * Func,const TargetMachine & TM) const24775ffd83dbSDimitry Andric MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2478af732203SDimitry Andric     const GlobalValue *Func, const TargetMachine &TM) const {
2479af732203SDimitry Andric   assert(
2480af732203SDimitry Andric       (isa<Function>(Func) ||
2481af732203SDimitry Andric        (isa<GlobalAlias>(Func) &&
2482af732203SDimitry Andric         isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) &&
2483af732203SDimitry Andric       "Func must be a function or an alias which has a function as base "
2484af732203SDimitry Andric       "object.");
2485af732203SDimitry Andric 
24865ffd83dbSDimitry Andric   SmallString<128> NameStr;
24875ffd83dbSDimitry Andric   NameStr.push_back('.');
2488af732203SDimitry Andric   getNameWithPrefix(NameStr, Func, TM);
2489af732203SDimitry Andric 
2490af732203SDimitry Andric   // When -function-sections is enabled and explicit section is not specified,
2491af732203SDimitry Andric   // it's not necessary to emit function entry point label any more. We will use
2492af732203SDimitry Andric   // function entry point csect instead. And for function delcarations, the
2493af732203SDimitry Andric   // undefined symbols gets treated as csect with XTY_ER property.
2494af732203SDimitry Andric   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2495af732203SDimitry Andric        Func->isDeclaration()) &&
2496af732203SDimitry Andric       isa<Function>(Func)) {
2497af732203SDimitry Andric     return getContext()
24985f7ddb14SDimitry Andric         .getXCOFFSection(
24995f7ddb14SDimitry Andric             NameStr, SectionKind::getText(),
25005f7ddb14SDimitry Andric             XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
25015f7ddb14SDimitry Andric                                                       ? XCOFF::XTY_ER
25025f7ddb14SDimitry Andric                                                       : XCOFF::XTY_SD))
2503af732203SDimitry Andric         ->getQualNameSymbol();
2504af732203SDimitry Andric   }
2505af732203SDimitry Andric 
25065ffd83dbSDimitry Andric   return getContext().getOrCreateSymbol(NameStr);
25075ffd83dbSDimitry Andric }
25085ffd83dbSDimitry Andric 
getSectionForFunctionDescriptor(const Function * F,const TargetMachine & TM) const25095ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
25105ffd83dbSDimitry Andric     const Function *F, const TargetMachine &TM) const {
25115ffd83dbSDimitry Andric   SmallString<128> NameStr;
25125ffd83dbSDimitry Andric   getNameWithPrefix(NameStr, F, TM);
25135f7ddb14SDimitry Andric   return getContext().getXCOFFSection(
25145f7ddb14SDimitry Andric       NameStr, SectionKind::getData(),
25155f7ddb14SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
25165ffd83dbSDimitry Andric }
25175ffd83dbSDimitry Andric 
getSectionForTOCEntry(const MCSymbol * Sym,const TargetMachine & TM) const25185ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2519af732203SDimitry Andric     const MCSymbol *Sym, const TargetMachine &TM) const {
2520af732203SDimitry Andric   // Use TE storage-mapping class when large code model is enabled so that
2521af732203SDimitry Andric   // the chance of needing -bbigtoc is decreased.
25225ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
25235f7ddb14SDimitry Andric       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
25245f7ddb14SDimitry Andric       XCOFF::CsectProperties(
2525af732203SDimitry Andric           TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
25265f7ddb14SDimitry Andric           XCOFF::XTY_SD));
25275f7ddb14SDimitry Andric }
25285f7ddb14SDimitry Andric 
25295f7ddb14SDimitry Andric //===----------------------------------------------------------------------===//
25305f7ddb14SDimitry Andric //                                  GOFF
25315f7ddb14SDimitry Andric //===----------------------------------------------------------------------===//
TargetLoweringObjectFileGOFF()25325f7ddb14SDimitry Andric TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF()
25335f7ddb14SDimitry Andric     : TargetLoweringObjectFile() {}
25345f7ddb14SDimitry Andric 
getExplicitSectionGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const25355f7ddb14SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
25365f7ddb14SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
25375f7ddb14SDimitry Andric   return SelectSectionForGlobal(GO, Kind, TM);
25385f7ddb14SDimitry Andric }
25395f7ddb14SDimitry Andric 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const25405f7ddb14SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
25415f7ddb14SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
25425f7ddb14SDimitry Andric   auto *Symbol = TM.getSymbol(GO);
25435f7ddb14SDimitry Andric   if (Kind.isBSS())
25445f7ddb14SDimitry Andric     return getContext().getGOFFSection(Symbol->getName(),
25455f7ddb14SDimitry Andric                                        SectionKind::getBSS());
25465f7ddb14SDimitry Andric 
25475f7ddb14SDimitry Andric   return getContext().getObjectFileInfo()->getTextSection();
25488bcb0991SDimitry Andric }
2549