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