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