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