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