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