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