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