1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements classes used to handle lowerings specific to common 11 // object file formats. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/BinaryFormat/COFF.h" 22 #include "llvm/BinaryFormat/Dwarf.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/BinaryFormat/MachO.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 27 #include "llvm/IR/Comdat.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalAlias.h" 33 #include "llvm/IR/GlobalObject.h" 34 #include "llvm/IR/GlobalValue.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Mangler.h" 37 #include "llvm/IR/Metadata.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/Type.h" 40 #include "llvm/MC/MCAsmInfo.h" 41 #include "llvm/MC/MCContext.h" 42 #include "llvm/MC/MCExpr.h" 43 #include "llvm/MC/MCSectionCOFF.h" 44 #include "llvm/MC/MCSectionELF.h" 45 #include "llvm/MC/MCSectionMachO.h" 46 #include "llvm/MC/MCSectionWasm.h" 47 #include "llvm/MC/MCStreamer.h" 48 #include "llvm/MC/MCSymbol.h" 49 #include "llvm/MC/MCSymbolELF.h" 50 #include "llvm/MC/MCValue.h" 51 #include "llvm/MC/SectionKind.h" 52 #include "llvm/ProfileData/InstrProf.h" 53 #include "llvm/Support/Casting.h" 54 #include "llvm/Support/CodeGen.h" 55 #include "llvm/Support/Format.h" 56 #include "llvm/Support/ErrorHandling.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Target/TargetMachine.h" 59 #include <cassert> 60 #include <string> 61 62 using namespace llvm; 63 using namespace dwarf; 64 65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 66 StringRef &Section) { 67 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 68 M.getModuleFlagsMetadata(ModuleFlags); 69 70 for (const auto &MFE: ModuleFlags) { 71 // Ignore flags with 'Require' behaviour. 72 if (MFE.Behavior == Module::Require) 73 continue; 74 75 StringRef Key = MFE.Key->getString(); 76 if (Key == "Objective-C Image Info Version") { 77 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 78 } else if (Key == "Objective-C Garbage Collection" || 79 Key == "Objective-C GC Only" || 80 Key == "Objective-C Is Simulated" || 81 Key == "Objective-C Class Properties" || 82 Key == "Objective-C Image Swift Version") { 83 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 84 } else if (Key == "Objective-C Image Info Section") { 85 Section = cast<MDString>(MFE.Val)->getString(); 86 } 87 } 88 } 89 90 //===----------------------------------------------------------------------===// 91 // ELF 92 //===----------------------------------------------------------------------===// 93 94 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 95 const TargetMachine &TgtM) { 96 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 97 TM = &TgtM; 98 99 CodeModel::Model CM = TgtM.getCodeModel(); 100 101 switch (TgtM.getTargetTriple().getArch()) { 102 case Triple::arm: 103 case Triple::armeb: 104 case Triple::thumb: 105 case Triple::thumbeb: 106 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) 107 break; 108 // Fallthrough if not using EHABI 109 LLVM_FALLTHROUGH; 110 case Triple::ppc: 111 case Triple::x86: 112 PersonalityEncoding = isPositionIndependent() 113 ? dwarf::DW_EH_PE_indirect | 114 dwarf::DW_EH_PE_pcrel | 115 dwarf::DW_EH_PE_sdata4 116 : dwarf::DW_EH_PE_absptr; 117 LSDAEncoding = isPositionIndependent() 118 ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 119 : dwarf::DW_EH_PE_absptr; 120 TTypeEncoding = isPositionIndependent() 121 ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 122 dwarf::DW_EH_PE_sdata4 123 : dwarf::DW_EH_PE_absptr; 124 break; 125 case Triple::x86_64: 126 if (isPositionIndependent()) { 127 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 128 ((CM == CodeModel::Small || CM == CodeModel::Medium) 129 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 130 LSDAEncoding = dwarf::DW_EH_PE_pcrel | 131 (CM == CodeModel::Small 132 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 133 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 134 ((CM == CodeModel::Small || CM == CodeModel::Medium) 135 ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4); 136 } else { 137 PersonalityEncoding = 138 (CM == CodeModel::Small || CM == CodeModel::Medium) 139 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 140 LSDAEncoding = (CM == CodeModel::Small) 141 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 142 TTypeEncoding = (CM == CodeModel::Small) 143 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 144 } 145 break; 146 case Triple::hexagon: 147 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 148 LSDAEncoding = dwarf::DW_EH_PE_absptr; 149 TTypeEncoding = dwarf::DW_EH_PE_absptr; 150 if (isPositionIndependent()) { 151 PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 152 LSDAEncoding |= dwarf::DW_EH_PE_pcrel; 153 TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 154 } 155 break; 156 case Triple::aarch64: 157 case Triple::aarch64_be: 158 // The small model guarantees static code/data size < 4GB, but not where it 159 // will be in memory. Most of these could end up >2GB away so even a signed 160 // pc-relative 32-bit address is insufficient, theoretically. 161 if (isPositionIndependent()) { 162 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 163 dwarf::DW_EH_PE_sdata8; 164 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; 165 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 166 dwarf::DW_EH_PE_sdata8; 167 } else { 168 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 169 LSDAEncoding = dwarf::DW_EH_PE_absptr; 170 TTypeEncoding = dwarf::DW_EH_PE_absptr; 171 } 172 break; 173 case Triple::lanai: 174 LSDAEncoding = dwarf::DW_EH_PE_absptr; 175 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 176 TTypeEncoding = dwarf::DW_EH_PE_absptr; 177 break; 178 case Triple::mips: 179 case Triple::mipsel: 180 case Triple::mips64: 181 case Triple::mips64el: 182 // MIPS uses indirect pointer to refer personality functions and types, so 183 // that the eh_frame section can be read-only. DW.ref.personality will be 184 // generated for relocation. 185 PersonalityEncoding = dwarf::DW_EH_PE_indirect; 186 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't 187 // identify N64 from just a triple. 188 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 189 dwarf::DW_EH_PE_sdata4; 190 // We don't support PC-relative LSDA references in GAS so we use the default 191 // DW_EH_PE_absptr for those. 192 193 // FreeBSD must be explicit about the data size and using pcrel since it's 194 // assembler/linker won't do the automatic conversion that the Linux tools 195 // do. 196 if (TgtM.getTargetTriple().isOSFreeBSD()) { 197 PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 198 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 199 } 200 break; 201 case Triple::ppc64: 202 case Triple::ppc64le: 203 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 204 dwarf::DW_EH_PE_udata8; 205 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; 206 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 207 dwarf::DW_EH_PE_udata8; 208 break; 209 case Triple::sparcel: 210 case Triple::sparc: 211 if (isPositionIndependent()) { 212 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 213 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 214 dwarf::DW_EH_PE_sdata4; 215 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 216 dwarf::DW_EH_PE_sdata4; 217 } else { 218 LSDAEncoding = dwarf::DW_EH_PE_absptr; 219 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 220 TTypeEncoding = dwarf::DW_EH_PE_absptr; 221 } 222 break; 223 case Triple::sparcv9: 224 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 225 if (isPositionIndependent()) { 226 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 227 dwarf::DW_EH_PE_sdata4; 228 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 229 dwarf::DW_EH_PE_sdata4; 230 } else { 231 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 232 TTypeEncoding = dwarf::DW_EH_PE_absptr; 233 } 234 break; 235 case Triple::systemz: 236 // All currently-defined code models guarantee that 4-byte PC-relative 237 // values will be in range. 238 if (isPositionIndependent()) { 239 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 240 dwarf::DW_EH_PE_sdata4; 241 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 242 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 243 dwarf::DW_EH_PE_sdata4; 244 } else { 245 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 246 LSDAEncoding = dwarf::DW_EH_PE_absptr; 247 TTypeEncoding = dwarf::DW_EH_PE_absptr; 248 } 249 break; 250 default: 251 break; 252 } 253 } 254 255 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, 256 Module &M) const { 257 auto &C = getContext(); 258 259 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 260 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, 261 ELF::SHF_EXCLUDE); 262 263 Streamer.SwitchSection(S); 264 265 for (const auto &Operand : LinkerOptions->operands()) { 266 if (cast<MDNode>(Operand)->getNumOperands() != 2) 267 report_fatal_error("invalid llvm.linker.options"); 268 for (const auto &Option : cast<MDNode>(Operand)->operands()) { 269 Streamer.EmitBytes(cast<MDString>(Option)->getString()); 270 Streamer.EmitIntValue(0, 1); 271 } 272 } 273 } 274 275 unsigned Version = 0; 276 unsigned Flags = 0; 277 StringRef Section; 278 279 GetObjCImageInfo(M, Version, Flags, Section); 280 if (!Section.empty()) { 281 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 282 Streamer.SwitchSection(S); 283 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 284 Streamer.EmitIntValue(Version, 4); 285 Streamer.EmitIntValue(Flags, 4); 286 Streamer.AddBlankLine(); 287 } 288 289 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 290 M.getModuleFlagsMetadata(ModuleFlags); 291 292 MDNode *CFGProfile = nullptr; 293 294 for (const auto &MFE : ModuleFlags) { 295 StringRef Key = MFE.Key->getString(); 296 if (Key == "CG Profile") { 297 CFGProfile = cast<MDNode>(MFE.Val); 298 break; 299 } 300 } 301 302 if (!CFGProfile) 303 return; 304 305 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { 306 if (!MDO) 307 return nullptr; 308 auto V = cast<ValueAsMetadata>(MDO); 309 const Function *F = cast<Function>(V->getValue()); 310 return TM->getSymbol(F); 311 }; 312 313 for (const auto &Edge : CFGProfile->operands()) { 314 MDNode *E = cast<MDNode>(Edge); 315 const MCSymbol *From = GetSym(E->getOperand(0)); 316 const MCSymbol *To = GetSym(E->getOperand(1)); 317 // Skip null functions. This can happen if functions are dead stripped after 318 // the CGProfile pass has been run. 319 if (!From || !To) 320 continue; 321 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2)) 322 ->getValue() 323 ->getUniqueInteger() 324 .getZExtValue(); 325 Streamer.emitCGProfileEntry( 326 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), 327 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); 328 } 329 } 330 331 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 332 const GlobalValue *GV, const TargetMachine &TM, 333 MachineModuleInfo *MMI) const { 334 unsigned Encoding = getPersonalityEncoding(); 335 if ((Encoding & 0x80) == DW_EH_PE_indirect) 336 return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 337 TM.getSymbol(GV)->getName()); 338 if ((Encoding & 0x70) == DW_EH_PE_absptr) 339 return TM.getSymbol(GV); 340 report_fatal_error("We do not support this DWARF encoding yet!"); 341 } 342 343 void TargetLoweringObjectFileELF::emitPersonalityValue( 344 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { 345 SmallString<64> NameData("DW.ref."); 346 NameData += Sym->getName(); 347 MCSymbolELF *Label = 348 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 349 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 350 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 351 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 352 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 353 ELF::SHT_PROGBITS, Flags, 0); 354 unsigned Size = DL.getPointerSize(); 355 Streamer.SwitchSection(Sec); 356 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0)); 357 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 358 const MCExpr *E = MCConstantExpr::create(Size, getContext()); 359 Streamer.emitELFSize(Label, E); 360 Streamer.EmitLabel(Label); 361 362 Streamer.EmitSymbolValue(Sym, Size); 363 } 364 365 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 366 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 367 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 368 if (Encoding & DW_EH_PE_indirect) { 369 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 370 371 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 372 373 // Add information about the stub reference to ELFMMI so that the stub 374 // gets emitted by the asmprinter. 375 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 376 if (!StubSym.getPointer()) { 377 MCSymbol *Sym = TM.getSymbol(GV); 378 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 379 } 380 381 return TargetLoweringObjectFile:: 382 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 383 Encoding & ~DW_EH_PE_indirect, Streamer); 384 } 385 386 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 387 MMI, Streamer); 388 } 389 390 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { 391 // N.B.: The defaults used in here are not the same ones used in MC. 392 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 393 // both gas and MC will produce a section with no flags. Given 394 // section(".eh_frame") gcc will produce: 395 // 396 // .section .eh_frame,"a",@progbits 397 398 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 399 /*AddSegmentInfo=*/false)) 400 return SectionKind::getMetadata(); 401 402 if (Name.empty() || Name[0] != '.') return K; 403 404 // Default implementation based on some magic section names. 405 if (Name == ".bss" || 406 Name.startswith(".bss.") || 407 Name.startswith(".gnu.linkonce.b.") || 408 Name.startswith(".llvm.linkonce.b.") || 409 Name == ".sbss" || 410 Name.startswith(".sbss.") || 411 Name.startswith(".gnu.linkonce.sb.") || 412 Name.startswith(".llvm.linkonce.sb.")) 413 return SectionKind::getBSS(); 414 415 if (Name == ".tdata" || 416 Name.startswith(".tdata.") || 417 Name.startswith(".gnu.linkonce.td.") || 418 Name.startswith(".llvm.linkonce.td.")) 419 return SectionKind::getThreadData(); 420 421 if (Name == ".tbss" || 422 Name.startswith(".tbss.") || 423 Name.startswith(".gnu.linkonce.tb.") || 424 Name.startswith(".llvm.linkonce.tb.")) 425 return SectionKind::getThreadBSS(); 426 427 if (Name.startswith(".debug_")) 428 return SectionKind::getMetadata(); 429 430 return K; 431 } 432 433 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 434 // Use SHT_NOTE for section whose name starts with ".note" to allow 435 // emitting ELF notes from C variable declaration. 436 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 437 if (Name.startswith(".note")) 438 return ELF::SHT_NOTE; 439 440 if (Name == ".init_array") 441 return ELF::SHT_INIT_ARRAY; 442 443 if (Name == ".fini_array") 444 return ELF::SHT_FINI_ARRAY; 445 446 if (Name == ".preinit_array") 447 return ELF::SHT_PREINIT_ARRAY; 448 449 if (K.isBSS() || K.isThreadBSS()) 450 return ELF::SHT_NOBITS; 451 452 return ELF::SHT_PROGBITS; 453 } 454 455 static unsigned getELFSectionFlags(SectionKind K) { 456 unsigned Flags = 0; 457 458 if (!K.isMetadata()) 459 Flags |= ELF::SHF_ALLOC; 460 461 if (K.isText()) 462 Flags |= ELF::SHF_EXECINSTR; 463 464 if (K.isExecuteOnly()) 465 Flags |= ELF::SHF_ARM_PURECODE; 466 467 if (K.isWriteable()) 468 Flags |= ELF::SHF_WRITE; 469 470 if (K.isThreadLocal()) 471 Flags |= ELF::SHF_TLS; 472 473 if (K.isMergeableCString() || K.isMergeableConst()) 474 Flags |= ELF::SHF_MERGE; 475 476 if (K.isMergeableCString()) 477 Flags |= ELF::SHF_STRINGS; 478 479 return Flags; 480 } 481 482 static const Comdat *getELFComdat(const GlobalValue *GV) { 483 const Comdat *C = GV->getComdat(); 484 if (!C) 485 return nullptr; 486 487 if (C->getSelectionKind() != Comdat::Any) 488 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 489 C->getName() + "' cannot be lowered."); 490 491 return C; 492 } 493 494 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO, 495 const TargetMachine &TM) { 496 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 497 if (!MD) 498 return nullptr; 499 500 const MDOperand &Op = MD->getOperand(0); 501 if (!Op.get()) 502 return nullptr; 503 504 auto *VM = dyn_cast<ValueAsMetadata>(Op); 505 if (!VM) 506 report_fatal_error("MD_associated operand is not ValueAsMetadata"); 507 508 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue()); 509 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr; 510 } 511 512 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 513 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 514 StringRef SectionName = GO->getSection(); 515 516 // Check if '#pragma clang section' name is applicable. 517 // Note that pragma directive overrides -ffunction-section, -fdata-section 518 // and so section name is exactly as user specified and not uniqued. 519 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 520 if (GV && GV->hasImplicitSection()) { 521 auto Attrs = GV->getAttributes(); 522 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { 523 SectionName = Attrs.getAttribute("bss-section").getValueAsString(); 524 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { 525 SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); 526 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { 527 SectionName = Attrs.getAttribute("data-section").getValueAsString(); 528 } 529 } 530 const Function *F = dyn_cast<Function>(GO); 531 if (F && F->hasFnAttribute("implicit-section-name")) { 532 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); 533 } 534 535 // Infer section flags from the section name if we can. 536 Kind = getELFKindForNamedSection(SectionName, Kind); 537 538 StringRef Group = ""; 539 unsigned Flags = getELFSectionFlags(Kind); 540 if (const Comdat *C = getELFComdat(GO)) { 541 Group = C->getName(); 542 Flags |= ELF::SHF_GROUP; 543 } 544 545 // A section can have at most one associated section. Put each global with 546 // MD_associated in a unique section. 547 unsigned UniqueID = MCContext::GenericSectionID; 548 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 549 if (AssociatedSymbol) { 550 UniqueID = NextUniqueID++; 551 Flags |= ELF::SHF_LINK_ORDER; 552 } 553 554 MCSectionELF *Section = getContext().getELFSection( 555 SectionName, getELFSectionType(SectionName, Kind), Flags, 556 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol); 557 // Make sure that we did not get some other section with incompatible sh_link. 558 // This should not be possible due to UniqueID code above. 559 assert(Section->getAssociatedSymbol() == AssociatedSymbol && 560 "Associated symbol mismatch between sections"); 561 return Section; 562 } 563 564 /// Return the section prefix name used by options FunctionsSections and 565 /// DataSections. 566 static StringRef getSectionPrefixForGlobal(SectionKind Kind) { 567 if (Kind.isText()) 568 return ".text"; 569 if (Kind.isReadOnly()) 570 return ".rodata"; 571 if (Kind.isBSS()) 572 return ".bss"; 573 if (Kind.isThreadData()) 574 return ".tdata"; 575 if (Kind.isThreadBSS()) 576 return ".tbss"; 577 if (Kind.isData()) 578 return ".data"; 579 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 580 return ".data.rel.ro"; 581 } 582 583 static unsigned getEntrySizeForKind(SectionKind Kind) { 584 if (Kind.isMergeable1ByteCString()) 585 return 1; 586 else if (Kind.isMergeable2ByteCString()) 587 return 2; 588 else if (Kind.isMergeable4ByteCString()) 589 return 4; 590 else if (Kind.isMergeableConst4()) 591 return 4; 592 else if (Kind.isMergeableConst8()) 593 return 8; 594 else if (Kind.isMergeableConst16()) 595 return 16; 596 else if (Kind.isMergeableConst32()) 597 return 32; 598 else { 599 // We shouldn't have mergeable C strings or mergeable constants that we 600 // didn't handle above. 601 assert(!Kind.isMergeableCString() && "unknown string width"); 602 assert(!Kind.isMergeableConst() && "unknown data width"); 603 return 0; 604 } 605 } 606 607 static MCSectionELF *selectELFSectionForGlobal( 608 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 609 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 610 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 611 612 StringRef Group = ""; 613 if (const Comdat *C = getELFComdat(GO)) { 614 Flags |= ELF::SHF_GROUP; 615 Group = C->getName(); 616 } 617 618 // Get the section entry size based on the kind. 619 unsigned EntrySize = getEntrySizeForKind(Kind); 620 621 SmallString<128> Name; 622 if (Kind.isMergeableCString()) { 623 // We also need alignment here. 624 // FIXME: this is getting the alignment of the character, not the 625 // alignment of the global! 626 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment( 627 cast<GlobalVariable>(GO)); 628 629 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 630 Name = SizeSpec + utostr(Align); 631 } else if (Kind.isMergeableConst()) { 632 Name = ".rodata.cst"; 633 Name += utostr(EntrySize); 634 } else { 635 Name = getSectionPrefixForGlobal(Kind); 636 } 637 638 if (const auto *F = dyn_cast<Function>(GO)) { 639 const auto &OptionalPrefix = F->getSectionPrefix(); 640 if (OptionalPrefix) 641 Name += *OptionalPrefix; 642 } 643 644 unsigned UniqueID = MCContext::GenericSectionID; 645 if (EmitUniqueSection) { 646 if (TM.getUniqueSectionNames()) { 647 Name.push_back('.'); 648 TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/); 649 } else { 650 UniqueID = *NextUniqueID; 651 (*NextUniqueID)++; 652 } 653 } 654 // Use 0 as the unique ID for execute-only text. 655 if (Kind.isExecuteOnly()) 656 UniqueID = 0; 657 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 658 EntrySize, Group, UniqueID, AssociatedSymbol); 659 } 660 661 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 662 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 663 unsigned Flags = getELFSectionFlags(Kind); 664 665 // If we have -ffunction-section or -fdata-section then we should emit the 666 // global value to a uniqued section specifically for it. 667 bool EmitUniqueSection = false; 668 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 669 if (Kind.isText()) 670 EmitUniqueSection = TM.getFunctionSections(); 671 else 672 EmitUniqueSection = TM.getDataSections(); 673 } 674 EmitUniqueSection |= GO->hasComdat(); 675 676 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 677 if (AssociatedSymbol) { 678 EmitUniqueSection = true; 679 Flags |= ELF::SHF_LINK_ORDER; 680 } 681 682 MCSectionELF *Section = selectELFSectionForGlobal( 683 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, 684 &NextUniqueID, AssociatedSymbol); 685 assert(Section->getAssociatedSymbol() == AssociatedSymbol); 686 return Section; 687 } 688 689 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 690 const Function &F, const TargetMachine &TM) const { 691 // If the function can be removed, produce a unique section so that 692 // the table doesn't prevent the removal. 693 const Comdat *C = F.getComdat(); 694 bool EmitUniqueSection = TM.getFunctionSections() || C; 695 if (!EmitUniqueSection) 696 return ReadOnlySection; 697 698 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 699 getMangler(), TM, EmitUniqueSection, 700 ELF::SHF_ALLOC, &NextUniqueID, 701 /* AssociatedSymbol */ nullptr); 702 } 703 704 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 705 bool UsesLabelDifference, const Function &F) const { 706 // We can always create relative relocations, so use another section 707 // that can be marked non-executable. 708 return false; 709 } 710 711 /// Given a mergeable constant with the specified size and relocation 712 /// information, return a section that it should be placed in. 713 MCSection *TargetLoweringObjectFileELF::getSectionForConstant( 714 const DataLayout &DL, SectionKind Kind, const Constant *C, 715 unsigned &Align) const { 716 if (Kind.isMergeableConst4() && MergeableConst4Section) 717 return MergeableConst4Section; 718 if (Kind.isMergeableConst8() && MergeableConst8Section) 719 return MergeableConst8Section; 720 if (Kind.isMergeableConst16() && MergeableConst16Section) 721 return MergeableConst16Section; 722 if (Kind.isMergeableConst32() && MergeableConst32Section) 723 return MergeableConst32Section; 724 if (Kind.isReadOnly()) 725 return ReadOnlySection; 726 727 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 728 return DataRelROSection; 729 } 730 731 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 732 bool IsCtor, unsigned Priority, 733 const MCSymbol *KeySym) { 734 std::string Name; 735 unsigned Type; 736 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 737 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 738 739 if (KeySym) 740 Flags |= ELF::SHF_GROUP; 741 742 if (UseInitArray) { 743 if (IsCtor) { 744 Type = ELF::SHT_INIT_ARRAY; 745 Name = ".init_array"; 746 } else { 747 Type = ELF::SHT_FINI_ARRAY; 748 Name = ".fini_array"; 749 } 750 if (Priority != 65535) { 751 Name += '.'; 752 Name += utostr(Priority); 753 } 754 } else { 755 // The default scheme is .ctor / .dtor, so we have to invert the priority 756 // numbering. 757 if (IsCtor) 758 Name = ".ctors"; 759 else 760 Name = ".dtors"; 761 if (Priority != 65535) 762 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 763 Type = ELF::SHT_PROGBITS; 764 } 765 766 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 767 } 768 769 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 770 unsigned Priority, const MCSymbol *KeySym) const { 771 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 772 KeySym); 773 } 774 775 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 776 unsigned Priority, const MCSymbol *KeySym) const { 777 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 778 KeySym); 779 } 780 781 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 782 const GlobalValue *LHS, const GlobalValue *RHS, 783 const TargetMachine &TM) const { 784 // We may only use a PLT-relative relocation to refer to unnamed_addr 785 // functions. 786 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 787 return nullptr; 788 789 // Basic sanity checks. 790 if (LHS->getType()->getPointerAddressSpace() != 0 || 791 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 792 RHS->isThreadLocal()) 793 return nullptr; 794 795 return MCBinaryExpr::createSub( 796 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 797 getContext()), 798 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 799 } 800 801 void 802 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 803 UseInitArray = UseInitArray_; 804 MCContext &Ctx = getContext(); 805 if (!UseInitArray) { 806 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 807 ELF::SHF_ALLOC | ELF::SHF_WRITE); 808 809 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 810 ELF::SHF_ALLOC | ELF::SHF_WRITE); 811 return; 812 } 813 814 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 815 ELF::SHF_WRITE | ELF::SHF_ALLOC); 816 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 817 ELF::SHF_WRITE | ELF::SHF_ALLOC); 818 } 819 820 //===----------------------------------------------------------------------===// 821 // MachO 822 //===----------------------------------------------------------------------===// 823 824 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 825 : TargetLoweringObjectFile() { 826 SupportIndirectSymViaGOTPCRel = true; 827 } 828 829 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 830 const TargetMachine &TM) { 831 TargetLoweringObjectFile::Initialize(Ctx, TM); 832 if (TM.getRelocationModel() == Reloc::Static) { 833 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 834 SectionKind::getData()); 835 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 836 SectionKind::getData()); 837 } else { 838 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 839 MachO::S_MOD_INIT_FUNC_POINTERS, 840 SectionKind::getData()); 841 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 842 MachO::S_MOD_TERM_FUNC_POINTERS, 843 SectionKind::getData()); 844 } 845 846 PersonalityEncoding = 847 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 848 LSDAEncoding = dwarf::DW_EH_PE_pcrel; 849 TTypeEncoding = 850 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 851 } 852 853 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, 854 Module &M) const { 855 // Emit the linker options if present. 856 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 857 for (const auto &Option : LinkerOptions->operands()) { 858 SmallVector<std::string, 4> StrOptions; 859 for (const auto &Piece : cast<MDNode>(Option)->operands()) 860 StrOptions.push_back(cast<MDString>(Piece)->getString()); 861 Streamer.EmitLinkerOptions(StrOptions); 862 } 863 } 864 865 unsigned VersionVal = 0; 866 unsigned ImageInfoFlags = 0; 867 StringRef SectionVal; 868 869 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 870 871 // The section is mandatory. If we don't have it, then we don't have GC info. 872 if (SectionVal.empty()) 873 return; 874 875 StringRef Segment, Section; 876 unsigned TAA = 0, StubSize = 0; 877 bool TAAParsed; 878 std::string ErrorCode = 879 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 880 TAA, TAAParsed, StubSize); 881 if (!ErrorCode.empty()) 882 // If invalid, report the error with report_fatal_error. 883 report_fatal_error("Invalid section specifier '" + Section + "': " + 884 ErrorCode + "."); 885 886 // Get the section. 887 MCSectionMachO *S = getContext().getMachOSection( 888 Segment, Section, TAA, StubSize, SectionKind::getData()); 889 Streamer.SwitchSection(S); 890 Streamer.EmitLabel(getContext(). 891 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 892 Streamer.EmitIntValue(VersionVal, 4); 893 Streamer.EmitIntValue(ImageInfoFlags, 4); 894 Streamer.AddBlankLine(); 895 } 896 897 static void checkMachOComdat(const GlobalValue *GV) { 898 const Comdat *C = GV->getComdat(); 899 if (!C) 900 return; 901 902 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 903 "' cannot be lowered."); 904 } 905 906 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 907 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 908 // Parse the section specifier and create it if valid. 909 StringRef Segment, Section; 910 unsigned TAA = 0, StubSize = 0; 911 bool TAAParsed; 912 913 checkMachOComdat(GO); 914 915 std::string ErrorCode = 916 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, 917 TAA, TAAParsed, StubSize); 918 if (!ErrorCode.empty()) { 919 // If invalid, report the error with report_fatal_error. 920 report_fatal_error("Global variable '" + GO->getName() + 921 "' has an invalid section specifier '" + 922 GO->getSection() + "': " + ErrorCode + "."); 923 } 924 925 // Get the section. 926 MCSectionMachO *S = 927 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 928 929 // If TAA wasn't set by ParseSectionSpecifier() above, 930 // use the value returned by getMachOSection() as a default. 931 if (!TAAParsed) 932 TAA = S->getTypeAndAttributes(); 933 934 // Okay, now that we got the section, verify that the TAA & StubSize agree. 935 // If the user declared multiple globals with different section flags, we need 936 // to reject it here. 937 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 938 // If invalid, report the error with report_fatal_error. 939 report_fatal_error("Global variable '" + GO->getName() + 940 "' section type or attributes does not match previous" 941 " section specifier"); 942 } 943 944 return S; 945 } 946 947 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 948 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 949 checkMachOComdat(GO); 950 951 // Handle thread local data. 952 if (Kind.isThreadBSS()) return TLSBSSSection; 953 if (Kind.isThreadData()) return TLSDataSection; 954 955 if (Kind.isText()) 956 return GO->isWeakForLinker() ? TextCoalSection : TextSection; 957 958 // If this is weak/linkonce, put this in a coalescable section, either in text 959 // or data depending on if it is writable. 960 if (GO->isWeakForLinker()) { 961 if (Kind.isReadOnly()) 962 return ConstTextCoalSection; 963 if (Kind.isReadOnlyWithRel()) 964 return ConstDataCoalSection; 965 return DataCoalSection; 966 } 967 968 // FIXME: Alignment check should be handled by section classifier. 969 if (Kind.isMergeable1ByteCString() && 970 GO->getParent()->getDataLayout().getPreferredAlignment( 971 cast<GlobalVariable>(GO)) < 32) 972 return CStringSection; 973 974 // Do not put 16-bit arrays in the UString section if they have an 975 // externally visible label, this runs into issues with certain linker 976 // versions. 977 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 978 GO->getParent()->getDataLayout().getPreferredAlignment( 979 cast<GlobalVariable>(GO)) < 32) 980 return UStringSection; 981 982 // With MachO only variables whose corresponding symbol starts with 'l' or 983 // 'L' can be merged, so we only try merging GVs with private linkage. 984 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 985 if (Kind.isMergeableConst4()) 986 return FourByteConstantSection; 987 if (Kind.isMergeableConst8()) 988 return EightByteConstantSection; 989 if (Kind.isMergeableConst16()) 990 return SixteenByteConstantSection; 991 } 992 993 // Otherwise, if it is readonly, but not something we can specially optimize, 994 // just drop it in .const. 995 if (Kind.isReadOnly()) 996 return ReadOnlySection; 997 998 // If this is marked const, put it into a const section. But if the dynamic 999 // linker needs to write to it, put it in the data segment. 1000 if (Kind.isReadOnlyWithRel()) 1001 return ConstDataSection; 1002 1003 // Put zero initialized globals with strong external linkage in the 1004 // DATA, __common section with the .zerofill directive. 1005 if (Kind.isBSSExtern()) 1006 return DataCommonSection; 1007 1008 // Put zero initialized globals with local linkage in __DATA,__bss directive 1009 // with the .zerofill directive (aka .lcomm). 1010 if (Kind.isBSSLocal()) 1011 return DataBSSSection; 1012 1013 // Otherwise, just drop the variable in the normal data section. 1014 return DataSection; 1015 } 1016 1017 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 1018 const DataLayout &DL, SectionKind Kind, const Constant *C, 1019 unsigned &Align) const { 1020 // If this constant requires a relocation, we have to put it in the data 1021 // segment, not in the text segment. 1022 if (Kind.isData() || Kind.isReadOnlyWithRel()) 1023 return ConstDataSection; 1024 1025 if (Kind.isMergeableConst4()) 1026 return FourByteConstantSection; 1027 if (Kind.isMergeableConst8()) 1028 return EightByteConstantSection; 1029 if (Kind.isMergeableConst16()) 1030 return SixteenByteConstantSection; 1031 return ReadOnlySection; // .const 1032 } 1033 1034 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 1035 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 1036 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1037 // The mach-o version of this method defaults to returning a stub reference. 1038 1039 if (Encoding & DW_EH_PE_indirect) { 1040 MachineModuleInfoMachO &MachOMMI = 1041 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1042 1043 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1044 1045 // Add information about the stub reference to MachOMMI so that the stub 1046 // gets emitted by the asmprinter. 1047 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1048 if (!StubSym.getPointer()) { 1049 MCSymbol *Sym = TM.getSymbol(GV); 1050 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1051 } 1052 1053 return TargetLoweringObjectFile:: 1054 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 1055 Encoding & ~DW_EH_PE_indirect, Streamer); 1056 } 1057 1058 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 1059 MMI, Streamer); 1060 } 1061 1062 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 1063 const GlobalValue *GV, const TargetMachine &TM, 1064 MachineModuleInfo *MMI) const { 1065 // The mach-o version of this method defaults to returning a stub reference. 1066 MachineModuleInfoMachO &MachOMMI = 1067 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1068 1069 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1070 1071 // Add information about the stub reference to MachOMMI so that the stub 1072 // gets emitted by the asmprinter. 1073 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1074 if (!StubSym.getPointer()) { 1075 MCSymbol *Sym = TM.getSymbol(GV); 1076 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1077 } 1078 1079 return SSym; 1080 } 1081 1082 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 1083 const MCSymbol *Sym, const MCValue &MV, int64_t Offset, 1084 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1085 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 1086 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 1087 // through a non_lazy_ptr stub instead. One advantage is that it allows the 1088 // computation of deltas to final external symbols. Example: 1089 // 1090 // _extgotequiv: 1091 // .long _extfoo 1092 // 1093 // _delta: 1094 // .long _extgotequiv-_delta 1095 // 1096 // is transformed to: 1097 // 1098 // _delta: 1099 // .long L_extfoo$non_lazy_ptr-(_delta+0) 1100 // 1101 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 1102 // L_extfoo$non_lazy_ptr: 1103 // .indirect_symbol _extfoo 1104 // .long 0 1105 // 1106 MachineModuleInfoMachO &MachOMMI = 1107 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1108 MCContext &Ctx = getContext(); 1109 1110 // The offset must consider the original displacement from the base symbol 1111 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 1112 Offset = -MV.getConstant(); 1113 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 1114 1115 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 1116 // non_lazy_ptr stubs. 1117 SmallString<128> Name; 1118 StringRef Suffix = "$non_lazy_ptr"; 1119 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 1120 Name += Sym->getName(); 1121 Name += Suffix; 1122 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 1123 1124 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 1125 if (!StubSym.getPointer()) 1126 StubSym = MachineModuleInfoImpl:: 1127 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */); 1128 1129 const MCExpr *BSymExpr = 1130 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 1131 const MCExpr *LHS = 1132 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 1133 1134 if (!Offset) 1135 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 1136 1137 const MCExpr *RHS = 1138 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 1139 return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1140 } 1141 1142 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 1143 const MCSection &Section) { 1144 if (!AsmInfo.isSectionAtomizableBySymbols(Section)) 1145 return true; 1146 1147 // If it is not dead stripped, it is safe to use private labels. 1148 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section); 1149 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) 1150 return true; 1151 1152 return false; 1153 } 1154 1155 void TargetLoweringObjectFileMachO::getNameWithPrefix( 1156 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1157 const TargetMachine &TM) const { 1158 bool CannotUsePrivateLabel = true; 1159 if (auto *GO = GV->getBaseObject()) { 1160 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 1161 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 1162 CannotUsePrivateLabel = 1163 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 1164 } 1165 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1166 } 1167 1168 //===----------------------------------------------------------------------===// 1169 // COFF 1170 //===----------------------------------------------------------------------===// 1171 1172 static unsigned 1173 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 1174 unsigned Flags = 0; 1175 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 1176 1177 if (K.isMetadata()) 1178 Flags |= 1179 COFF::IMAGE_SCN_MEM_DISCARDABLE; 1180 else if (K.isText()) 1181 Flags |= 1182 COFF::IMAGE_SCN_MEM_EXECUTE | 1183 COFF::IMAGE_SCN_MEM_READ | 1184 COFF::IMAGE_SCN_CNT_CODE | 1185 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 1186 else if (K.isBSS()) 1187 Flags |= 1188 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 1189 COFF::IMAGE_SCN_MEM_READ | 1190 COFF::IMAGE_SCN_MEM_WRITE; 1191 else if (K.isThreadLocal()) 1192 Flags |= 1193 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1194 COFF::IMAGE_SCN_MEM_READ | 1195 COFF::IMAGE_SCN_MEM_WRITE; 1196 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 1197 Flags |= 1198 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1199 COFF::IMAGE_SCN_MEM_READ; 1200 else if (K.isWriteable()) 1201 Flags |= 1202 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1203 COFF::IMAGE_SCN_MEM_READ | 1204 COFF::IMAGE_SCN_MEM_WRITE; 1205 1206 return Flags; 1207 } 1208 1209 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 1210 const Comdat *C = GV->getComdat(); 1211 assert(C && "expected GV to have a Comdat!"); 1212 1213 StringRef ComdatGVName = C->getName(); 1214 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 1215 if (!ComdatGV) 1216 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1217 "' does not exist."); 1218 1219 if (ComdatGV->getComdat() != C) 1220 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1221 "' is not a key for its COMDAT."); 1222 1223 return ComdatGV; 1224 } 1225 1226 static int getSelectionForCOFF(const GlobalValue *GV) { 1227 if (const Comdat *C = GV->getComdat()) { 1228 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 1229 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 1230 ComdatKey = GA->getBaseObject(); 1231 if (ComdatKey == GV) { 1232 switch (C->getSelectionKind()) { 1233 case Comdat::Any: 1234 return COFF::IMAGE_COMDAT_SELECT_ANY; 1235 case Comdat::ExactMatch: 1236 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1237 case Comdat::Largest: 1238 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1239 case Comdat::NoDuplicates: 1240 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1241 case Comdat::SameSize: 1242 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1243 } 1244 } else { 1245 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1246 } 1247 } 1248 return 0; 1249 } 1250 1251 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1252 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1253 int Selection = 0; 1254 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1255 StringRef Name = GO->getSection(); 1256 StringRef COMDATSymName = ""; 1257 if (GO->hasComdat()) { 1258 Selection = getSelectionForCOFF(GO); 1259 const GlobalValue *ComdatGV; 1260 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1261 ComdatGV = getComdatGVForCOFF(GO); 1262 else 1263 ComdatGV = GO; 1264 1265 if (!ComdatGV->hasPrivateLinkage()) { 1266 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1267 COMDATSymName = Sym->getName(); 1268 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1269 } else { 1270 Selection = 0; 1271 } 1272 } 1273 1274 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1275 Selection); 1276 } 1277 1278 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1279 if (Kind.isText()) 1280 return ".text"; 1281 if (Kind.isBSS()) 1282 return ".bss"; 1283 if (Kind.isThreadLocal()) 1284 return ".tls$"; 1285 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1286 return ".rdata"; 1287 return ".data"; 1288 } 1289 1290 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1291 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1292 // If we have -ffunction-sections then we should emit the global value to a 1293 // uniqued section specifically for it. 1294 bool EmitUniquedSection; 1295 if (Kind.isText()) 1296 EmitUniquedSection = TM.getFunctionSections(); 1297 else 1298 EmitUniquedSection = TM.getDataSections(); 1299 1300 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1301 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); 1302 1303 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1304 1305 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1306 int Selection = getSelectionForCOFF(GO); 1307 if (!Selection) 1308 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1309 const GlobalValue *ComdatGV; 1310 if (GO->hasComdat()) 1311 ComdatGV = getComdatGVForCOFF(GO); 1312 else 1313 ComdatGV = GO; 1314 1315 unsigned UniqueID = MCContext::GenericSectionID; 1316 if (EmitUniquedSection) 1317 UniqueID = NextUniqueID++; 1318 1319 if (!ComdatGV->hasPrivateLinkage()) { 1320 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1321 StringRef COMDATSymName = Sym->getName(); 1322 1323 // Append "$symbol" to the section name when targetting mingw. The ld.bfd 1324 // COFF linker will not properly handle comdats otherwise. 1325 if (getTargetTriple().isWindowsGNUEnvironment()) 1326 raw_svector_ostream(Name) << '$' << COMDATSymName; 1327 1328 return getContext().getCOFFSection(Name, Characteristics, Kind, 1329 COMDATSymName, Selection, UniqueID); 1330 } else { 1331 SmallString<256> TmpData; 1332 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1333 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 1334 Selection, UniqueID); 1335 } 1336 } 1337 1338 if (Kind.isText()) 1339 return TextSection; 1340 1341 if (Kind.isThreadLocal()) 1342 return TLSDataSection; 1343 1344 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1345 return ReadOnlySection; 1346 1347 // Note: we claim that common symbols are put in BSSSection, but they are 1348 // really emitted with the magic .comm directive, which creates a symbol table 1349 // entry but not a section. 1350 if (Kind.isBSS() || Kind.isCommon()) 1351 return BSSSection; 1352 1353 return DataSection; 1354 } 1355 1356 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 1357 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1358 const TargetMachine &TM) const { 1359 bool CannotUsePrivateLabel = false; 1360 if (GV->hasPrivateLinkage() && 1361 ((isa<Function>(GV) && TM.getFunctionSections()) || 1362 (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1363 CannotUsePrivateLabel = true; 1364 1365 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1366 } 1367 1368 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1369 const Function &F, const TargetMachine &TM) const { 1370 // If the function can be removed, produce a unique section so that 1371 // the table doesn't prevent the removal. 1372 const Comdat *C = F.getComdat(); 1373 bool EmitUniqueSection = TM.getFunctionSections() || C; 1374 if (!EmitUniqueSection) 1375 return ReadOnlySection; 1376 1377 // FIXME: we should produce a symbol for F instead. 1378 if (F.hasPrivateLinkage()) 1379 return ReadOnlySection; 1380 1381 MCSymbol *Sym = TM.getSymbol(&F); 1382 StringRef COMDATSymName = Sym->getName(); 1383 1384 SectionKind Kind = SectionKind::getReadOnly(); 1385 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); 1386 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1387 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1388 unsigned UniqueID = NextUniqueID++; 1389 1390 return getContext().getCOFFSection( 1391 SecName, Characteristics, Kind, COMDATSymName, 1392 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 1393 } 1394 1395 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, 1396 Module &M) const { 1397 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1398 // Emit the linker options to the linker .drectve section. According to the 1399 // spec, this section is a space-separated string containing flags for 1400 // linker. 1401 MCSection *Sec = getDrectveSection(); 1402 Streamer.SwitchSection(Sec); 1403 for (const auto &Option : LinkerOptions->operands()) { 1404 for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1405 // Lead with a space for consistency with our dllexport implementation. 1406 std::string Directive(" "); 1407 Directive.append(cast<MDString>(Piece)->getString()); 1408 Streamer.EmitBytes(Directive); 1409 } 1410 } 1411 } 1412 1413 unsigned Version = 0; 1414 unsigned Flags = 0; 1415 StringRef Section; 1416 1417 GetObjCImageInfo(M, Version, Flags, Section); 1418 if (Section.empty()) 1419 return; 1420 1421 auto &C = getContext(); 1422 auto *S = C.getCOFFSection( 1423 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1424 SectionKind::getReadOnly()); 1425 Streamer.SwitchSection(S); 1426 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1427 Streamer.EmitIntValue(Version, 4); 1428 Streamer.EmitIntValue(Flags, 4); 1429 Streamer.AddBlankLine(); 1430 } 1431 1432 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1433 const TargetMachine &TM) { 1434 TargetLoweringObjectFile::Initialize(Ctx, TM); 1435 const Triple &T = TM.getTargetTriple(); 1436 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1437 StaticCtorSection = 1438 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1439 COFF::IMAGE_SCN_MEM_READ, 1440 SectionKind::getReadOnly()); 1441 StaticDtorSection = 1442 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1443 COFF::IMAGE_SCN_MEM_READ, 1444 SectionKind::getReadOnly()); 1445 } else { 1446 StaticCtorSection = Ctx.getCOFFSection( 1447 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1448 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1449 SectionKind::getData()); 1450 StaticDtorSection = Ctx.getCOFFSection( 1451 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1452 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1453 SectionKind::getData()); 1454 } 1455 } 1456 1457 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, 1458 const Triple &T, bool IsCtor, 1459 unsigned Priority, 1460 const MCSymbol *KeySym, 1461 MCSectionCOFF *Default) { 1462 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) 1463 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); 1464 1465 std::string Name = IsCtor ? ".ctors" : ".dtors"; 1466 if (Priority != 65535) 1467 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1468 1469 return Ctx.getAssociativeCOFFSection( 1470 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1471 COFF::IMAGE_SCN_MEM_READ | 1472 COFF::IMAGE_SCN_MEM_WRITE, 1473 SectionKind::getData()), 1474 KeySym, 0); 1475 } 1476 1477 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1478 unsigned Priority, const MCSymbol *KeySym) const { 1479 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true, 1480 Priority, KeySym, 1481 cast<MCSectionCOFF>(StaticCtorSection)); 1482 } 1483 1484 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1485 unsigned Priority, const MCSymbol *KeySym) const { 1486 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false, 1487 Priority, KeySym, 1488 cast<MCSectionCOFF>(StaticDtorSection)); 1489 } 1490 1491 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal( 1492 raw_ostream &OS, const GlobalValue *GV) const { 1493 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler()); 1494 } 1495 1496 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed( 1497 raw_ostream &OS, const GlobalValue *GV) const { 1498 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler()); 1499 } 1500 1501 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( 1502 const GlobalValue *LHS, const GlobalValue *RHS, 1503 const TargetMachine &TM) const { 1504 const Triple &T = TM.getTargetTriple(); 1505 if (!T.isKnownWindowsMSVCEnvironment() && 1506 !T.isWindowsItaniumEnvironment() && 1507 !T.isWindowsCoreCLREnvironment()) 1508 return nullptr; 1509 1510 // Our symbols should exist in address space zero, cowardly no-op if 1511 // otherwise. 1512 if (LHS->getType()->getPointerAddressSpace() != 0 || 1513 RHS->getType()->getPointerAddressSpace() != 0) 1514 return nullptr; 1515 1516 // Both ptrtoint instructions must wrap global objects: 1517 // - Only global variables are eligible for image relative relocations. 1518 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. 1519 // We expect __ImageBase to be a global variable without a section, externally 1520 // defined. 1521 // 1522 // It should look something like this: @__ImageBase = external constant i8 1523 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) || 1524 LHS->isThreadLocal() || RHS->isThreadLocal() || 1525 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || 1526 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection()) 1527 return nullptr; 1528 1529 return MCSymbolRefExpr::create(TM.getSymbol(LHS), 1530 MCSymbolRefExpr::VK_COFF_IMGREL32, 1531 getContext()); 1532 } 1533 1534 static std::string APIntToHexString(const APInt &AI) { 1535 unsigned Width = (AI.getBitWidth() / 8) * 2; 1536 std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true); 1537 unsigned Size = HexString.size(); 1538 assert(Width >= Size && "hex string is too large!"); 1539 HexString.insert(HexString.begin(), Width - Size, '0'); 1540 1541 return HexString; 1542 } 1543 1544 static std::string scalarConstantToHexString(const Constant *C) { 1545 Type *Ty = C->getType(); 1546 if (isa<UndefValue>(C)) { 1547 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits())); 1548 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) { 1549 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); 1550 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) { 1551 return APIntToHexString(CI->getValue()); 1552 } else { 1553 unsigned NumElements; 1554 if (isa<VectorType>(Ty)) 1555 NumElements = Ty->getVectorNumElements(); 1556 else 1557 NumElements = Ty->getArrayNumElements(); 1558 std::string HexString; 1559 for (int I = NumElements - 1, E = -1; I != E; --I) 1560 HexString += scalarConstantToHexString(C->getAggregateElement(I)); 1561 return HexString; 1562 } 1563 } 1564 1565 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( 1566 const DataLayout &DL, SectionKind Kind, const Constant *C, 1567 unsigned &Align) const { 1568 if (Kind.isMergeableConst() && C && 1569 getContext().getAsmInfo()->hasCOFFComdatConstants()) { 1570 // This creates comdat sections with the given symbol name, but unless 1571 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol 1572 // will be created with a null storage class, which makes GNU binutils 1573 // error out. 1574 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1575 COFF::IMAGE_SCN_MEM_READ | 1576 COFF::IMAGE_SCN_LNK_COMDAT; 1577 std::string COMDATSymName; 1578 if (Kind.isMergeableConst4()) { 1579 if (Align <= 4) { 1580 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1581 Align = 4; 1582 } 1583 } else if (Kind.isMergeableConst8()) { 1584 if (Align <= 8) { 1585 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1586 Align = 8; 1587 } 1588 } else if (Kind.isMergeableConst16()) { 1589 // FIXME: These may not be appropriate for non-x86 architectures. 1590 if (Align <= 16) { 1591 COMDATSymName = "__xmm@" + scalarConstantToHexString(C); 1592 Align = 16; 1593 } 1594 } else if (Kind.isMergeableConst32()) { 1595 if (Align <= 32) { 1596 COMDATSymName = "__ymm@" + scalarConstantToHexString(C); 1597 Align = 32; 1598 } 1599 } 1600 1601 if (!COMDATSymName.empty()) 1602 return getContext().getCOFFSection(".rdata", Characteristics, Kind, 1603 COMDATSymName, 1604 COFF::IMAGE_COMDAT_SELECT_ANY); 1605 } 1606 1607 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align); 1608 } 1609 1610 1611 //===----------------------------------------------------------------------===// 1612 // Wasm 1613 //===----------------------------------------------------------------------===// 1614 1615 static const Comdat *getWasmComdat(const GlobalValue *GV) { 1616 const Comdat *C = GV->getComdat(); 1617 if (!C) 1618 return nullptr; 1619 1620 if (C->getSelectionKind() != Comdat::Any) 1621 report_fatal_error("WebAssembly COMDATs only support " 1622 "SelectionKind::Any, '" + C->getName() + "' cannot be " 1623 "lowered."); 1624 1625 return C; 1626 } 1627 1628 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) { 1629 // If we're told we have function data, then use that. 1630 if (K.isText()) 1631 return SectionKind::getText(); 1632 1633 // Otherwise, ignore whatever section type the generic impl detected and use 1634 // a plain data section. 1635 return SectionKind::getData(); 1636 } 1637 1638 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 1639 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1640 // We don't support explict section names for functions in the wasm object 1641 // format. Each function has to be in its own unique section. 1642 if (isa<Function>(GO)) { 1643 return SelectSectionForGlobal(GO, Kind, TM); 1644 } 1645 1646 StringRef Name = GO->getSection(); 1647 1648 Kind = getWasmKindForNamedSection(Name, Kind); 1649 1650 StringRef Group = ""; 1651 if (const Comdat *C = getWasmComdat(GO)) { 1652 Group = C->getName(); 1653 } 1654 1655 return getContext().getWasmSection(Name, Kind, Group, 1656 MCContext::GenericSectionID); 1657 } 1658 1659 static MCSectionWasm *selectWasmSectionForGlobal( 1660 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 1661 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { 1662 StringRef Group = ""; 1663 if (const Comdat *C = getWasmComdat(GO)) { 1664 Group = C->getName(); 1665 } 1666 1667 bool UniqueSectionNames = TM.getUniqueSectionNames(); 1668 SmallString<128> Name = getSectionPrefixForGlobal(Kind); 1669 1670 if (const auto *F = dyn_cast<Function>(GO)) { 1671 const auto &OptionalPrefix = F->getSectionPrefix(); 1672 if (OptionalPrefix) 1673 Name += *OptionalPrefix; 1674 } 1675 1676 if (EmitUniqueSection && UniqueSectionNames) { 1677 Name.push_back('.'); 1678 TM.getNameWithPrefix(Name, GO, Mang, true); 1679 } 1680 unsigned UniqueID = MCContext::GenericSectionID; 1681 if (EmitUniqueSection && !UniqueSectionNames) { 1682 UniqueID = *NextUniqueID; 1683 (*NextUniqueID)++; 1684 } 1685 return Ctx.getWasmSection(Name, Kind, Group, UniqueID); 1686 } 1687 1688 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 1689 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1690 1691 if (Kind.isCommon()) 1692 report_fatal_error("mergable sections not supported yet on wasm"); 1693 1694 // If we have -ffunction-section or -fdata-section then we should emit the 1695 // global value to a uniqued section specifically for it. 1696 bool EmitUniqueSection = false; 1697 if (Kind.isText()) 1698 EmitUniqueSection = TM.getFunctionSections(); 1699 else 1700 EmitUniqueSection = TM.getDataSections(); 1701 EmitUniqueSection |= GO->hasComdat(); 1702 1703 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 1704 EmitUniqueSection, &NextUniqueID); 1705 } 1706 1707 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 1708 bool UsesLabelDifference, const Function &F) const { 1709 // We can always create relative relocations, so use another section 1710 // that can be marked non-executable. 1711 return false; 1712 } 1713 1714 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 1715 const GlobalValue *LHS, const GlobalValue *RHS, 1716 const TargetMachine &TM) const { 1717 // We may only use a PLT-relative relocation to refer to unnamed_addr 1718 // functions. 1719 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1720 return nullptr; 1721 1722 // Basic sanity checks. 1723 if (LHS->getType()->getPointerAddressSpace() != 0 || 1724 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1725 RHS->isThreadLocal()) 1726 return nullptr; 1727 1728 return MCBinaryExpr::createSub( 1729 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 1730 getContext()), 1731 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1732 } 1733 1734 void TargetLoweringObjectFileWasm::InitializeWasm() { 1735 StaticCtorSection = 1736 getContext().getWasmSection(".init_array", SectionKind::getData()); 1737 } 1738 1739 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( 1740 unsigned Priority, const MCSymbol *KeySym) const { 1741 return Priority == UINT16_MAX ? 1742 StaticCtorSection : 1743 getContext().getWasmSection(".init_array." + utostr(Priority), 1744 SectionKind::getData()); 1745 } 1746 1747 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( 1748 unsigned Priority, const MCSymbol *KeySym) const { 1749 llvm_unreachable("@llvm.global_dtors should have been lowered already"); 1750 return nullptr; 1751 } 1752