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/ErrorHandling.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include "llvm/Target/TargetMachine.h" 58 #include <cassert> 59 #include <string> 60 61 using namespace llvm; 62 using namespace dwarf; 63 64 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 65 StringRef &Section) { 66 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 67 M.getModuleFlagsMetadata(ModuleFlags); 68 69 for (const auto &MFE: ModuleFlags) { 70 // Ignore flags with 'Require' behaviour. 71 if (MFE.Behavior == Module::Require) 72 continue; 73 74 StringRef Key = MFE.Key->getString(); 75 if (Key == "Objective-C Image Info Version") { 76 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 77 } else if (Key == "Objective-C Garbage Collection" || 78 Key == "Objective-C GC Only" || 79 Key == "Objective-C Is Simulated" || 80 Key == "Objective-C Class Properties" || 81 Key == "Objective-C Image Swift Version") { 82 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 83 } else if (Key == "Objective-C Image Info Section") { 84 Section = cast<MDString>(MFE.Val)->getString(); 85 } 86 } 87 } 88 89 //===----------------------------------------------------------------------===// 90 // ELF 91 //===----------------------------------------------------------------------===// 92 93 void TargetLoweringObjectFileELF::emitModuleMetadata( 94 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const { 95 unsigned Version = 0; 96 unsigned Flags = 0; 97 StringRef Section; 98 99 GetObjCImageInfo(M, Version, Flags, Section); 100 if (Section.empty()) 101 return; 102 103 auto &C = getContext(); 104 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 105 Streamer.SwitchSection(S); 106 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 107 Streamer.EmitIntValue(Version, 4); 108 Streamer.EmitIntValue(Flags, 4); 109 Streamer.AddBlankLine(); 110 } 111 112 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 113 const GlobalValue *GV, const TargetMachine &TM, 114 MachineModuleInfo *MMI) const { 115 unsigned Encoding = getPersonalityEncoding(); 116 if ((Encoding & 0x80) == DW_EH_PE_indirect) 117 return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 118 TM.getSymbol(GV)->getName()); 119 if ((Encoding & 0x70) == DW_EH_PE_absptr) 120 return TM.getSymbol(GV); 121 report_fatal_error("We do not support this DWARF encoding yet!"); 122 } 123 124 void TargetLoweringObjectFileELF::emitPersonalityValue( 125 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { 126 SmallString<64> NameData("DW.ref."); 127 NameData += Sym->getName(); 128 MCSymbolELF *Label = 129 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 130 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 131 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 132 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 133 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 134 ELF::SHT_PROGBITS, Flags, 0); 135 unsigned Size = DL.getPointerSize(); 136 Streamer.SwitchSection(Sec); 137 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment()); 138 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 139 const MCExpr *E = MCConstantExpr::create(Size, getContext()); 140 Streamer.emitELFSize(Label, E); 141 Streamer.EmitLabel(Label); 142 143 Streamer.EmitSymbolValue(Sym, Size); 144 } 145 146 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 147 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 148 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 149 if (Encoding & DW_EH_PE_indirect) { 150 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 151 152 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 153 154 // Add information about the stub reference to ELFMMI so that the stub 155 // gets emitted by the asmprinter. 156 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 157 if (!StubSym.getPointer()) { 158 MCSymbol *Sym = TM.getSymbol(GV); 159 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 160 } 161 162 return TargetLoweringObjectFile:: 163 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 164 Encoding & ~DW_EH_PE_indirect, Streamer); 165 } 166 167 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 168 MMI, Streamer); 169 } 170 171 static SectionKind 172 getELFKindForNamedSection(StringRef Name, SectionKind K) { 173 // N.B.: The defaults used in here are no the same ones used in MC. 174 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 175 // both gas and MC will produce a section with no flags. Given 176 // section(".eh_frame") gcc will produce: 177 // 178 // .section .eh_frame,"a",@progbits 179 180 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 181 /*AddSegmentInfo=*/false)) 182 return SectionKind::getMetadata(); 183 184 if (Name.empty() || Name[0] != '.') return K; 185 186 // Some lame default implementation based on some magic section names. 187 if (Name == ".bss" || 188 Name.startswith(".bss.") || 189 Name.startswith(".gnu.linkonce.b.") || 190 Name.startswith(".llvm.linkonce.b.") || 191 Name == ".sbss" || 192 Name.startswith(".sbss.") || 193 Name.startswith(".gnu.linkonce.sb.") || 194 Name.startswith(".llvm.linkonce.sb.")) 195 return SectionKind::getBSS(); 196 197 if (Name == ".tdata" || 198 Name.startswith(".tdata.") || 199 Name.startswith(".gnu.linkonce.td.") || 200 Name.startswith(".llvm.linkonce.td.")) 201 return SectionKind::getThreadData(); 202 203 if (Name == ".tbss" || 204 Name.startswith(".tbss.") || 205 Name.startswith(".gnu.linkonce.tb.") || 206 Name.startswith(".llvm.linkonce.tb.")) 207 return SectionKind::getThreadBSS(); 208 209 return K; 210 } 211 212 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 213 // Use SHT_NOTE for section whose name starts with ".note" to allow 214 // emitting ELF notes from C variable declaration. 215 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 216 if (Name.startswith(".note")) 217 return ELF::SHT_NOTE; 218 219 if (Name == ".init_array") 220 return ELF::SHT_INIT_ARRAY; 221 222 if (Name == ".fini_array") 223 return ELF::SHT_FINI_ARRAY; 224 225 if (Name == ".preinit_array") 226 return ELF::SHT_PREINIT_ARRAY; 227 228 if (K.isBSS() || K.isThreadBSS()) 229 return ELF::SHT_NOBITS; 230 231 return ELF::SHT_PROGBITS; 232 } 233 234 static unsigned getELFSectionFlags(SectionKind K) { 235 unsigned Flags = 0; 236 237 if (!K.isMetadata()) 238 Flags |= ELF::SHF_ALLOC; 239 240 if (K.isText()) 241 Flags |= ELF::SHF_EXECINSTR; 242 243 if (K.isExecuteOnly()) 244 Flags |= ELF::SHF_ARM_PURECODE; 245 246 if (K.isWriteable()) 247 Flags |= ELF::SHF_WRITE; 248 249 if (K.isThreadLocal()) 250 Flags |= ELF::SHF_TLS; 251 252 if (K.isMergeableCString() || K.isMergeableConst()) 253 Flags |= ELF::SHF_MERGE; 254 255 if (K.isMergeableCString()) 256 Flags |= ELF::SHF_STRINGS; 257 258 return Flags; 259 } 260 261 static const Comdat *getELFComdat(const GlobalValue *GV) { 262 const Comdat *C = GV->getComdat(); 263 if (!C) 264 return nullptr; 265 266 if (C->getSelectionKind() != Comdat::Any) 267 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 268 C->getName() + "' cannot be lowered."); 269 270 return C; 271 } 272 273 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO, 274 const TargetMachine &TM) { 275 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 276 if (!MD) 277 return nullptr; 278 279 const MDOperand &Op = MD->getOperand(0); 280 if (!Op.get()) 281 return nullptr; 282 283 auto *VM = dyn_cast<ValueAsMetadata>(Op); 284 if (!VM) 285 report_fatal_error("MD_associated operand is not ValueAsMetadata"); 286 287 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue()); 288 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr; 289 } 290 291 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 292 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 293 StringRef SectionName = GO->getSection(); 294 295 // Check if '#pragma clang section' name is applicable. 296 // Note that pragma directive overrides -ffunction-section, -fdata-section 297 // and so section name is exactly as user specified and not uniqued. 298 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 299 if (GV && GV->hasImplicitSection()) { 300 auto Attrs = GV->getAttributes(); 301 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { 302 SectionName = Attrs.getAttribute("bss-section").getValueAsString(); 303 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { 304 SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); 305 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { 306 SectionName = Attrs.getAttribute("data-section").getValueAsString(); 307 } 308 } 309 const Function *F = dyn_cast<Function>(GO); 310 if (F && F->hasFnAttribute("implicit-section-name")) { 311 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); 312 } 313 314 // Infer section flags from the section name if we can. 315 Kind = getELFKindForNamedSection(SectionName, Kind); 316 317 StringRef Group = ""; 318 unsigned Flags = getELFSectionFlags(Kind); 319 if (const Comdat *C = getELFComdat(GO)) { 320 Group = C->getName(); 321 Flags |= ELF::SHF_GROUP; 322 } 323 324 // A section can have at most one associated section. Put each global with 325 // MD_associated in a unique section. 326 unsigned UniqueID = MCContext::GenericSectionID; 327 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 328 if (AssociatedSymbol) { 329 UniqueID = NextUniqueID++; 330 Flags |= ELF::SHF_LINK_ORDER; 331 } 332 333 MCSectionELF *Section = getContext().getELFSection( 334 SectionName, getELFSectionType(SectionName, Kind), Flags, 335 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol); 336 // Make sure that we did not get some other section with incompatible sh_link. 337 // This should not be possible due to UniqueID code above. 338 assert(Section->getAssociatedSymbol() == AssociatedSymbol); 339 return Section; 340 } 341 342 /// Return the section prefix name used by options FunctionsSections and 343 /// DataSections. 344 static StringRef getSectionPrefixForGlobal(SectionKind Kind) { 345 if (Kind.isText()) 346 return ".text"; 347 if (Kind.isReadOnly()) 348 return ".rodata"; 349 if (Kind.isBSS()) 350 return ".bss"; 351 if (Kind.isThreadData()) 352 return ".tdata"; 353 if (Kind.isThreadBSS()) 354 return ".tbss"; 355 if (Kind.isData()) 356 return ".data"; 357 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 358 return ".data.rel.ro"; 359 } 360 361 static MCSectionELF *selectELFSectionForGlobal( 362 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 363 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 364 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 365 unsigned EntrySize = 0; 366 if (Kind.isMergeableCString()) { 367 if (Kind.isMergeable2ByteCString()) { 368 EntrySize = 2; 369 } else if (Kind.isMergeable4ByteCString()) { 370 EntrySize = 4; 371 } else { 372 EntrySize = 1; 373 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 374 } 375 } else if (Kind.isMergeableConst()) { 376 if (Kind.isMergeableConst4()) { 377 EntrySize = 4; 378 } else if (Kind.isMergeableConst8()) { 379 EntrySize = 8; 380 } else if (Kind.isMergeableConst16()) { 381 EntrySize = 16; 382 } else { 383 assert(Kind.isMergeableConst32() && "unknown data width"); 384 EntrySize = 32; 385 } 386 } 387 388 StringRef Group = ""; 389 if (const Comdat *C = getELFComdat(GO)) { 390 Flags |= ELF::SHF_GROUP; 391 Group = C->getName(); 392 } 393 394 bool UniqueSectionNames = TM.getUniqueSectionNames(); 395 SmallString<128> Name; 396 if (Kind.isMergeableCString()) { 397 // We also need alignment here. 398 // FIXME: this is getting the alignment of the character, not the 399 // alignment of the global! 400 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment( 401 cast<GlobalVariable>(GO)); 402 403 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 404 Name = SizeSpec + utostr(Align); 405 } else if (Kind.isMergeableConst()) { 406 Name = ".rodata.cst"; 407 Name += utostr(EntrySize); 408 } else { 409 Name = getSectionPrefixForGlobal(Kind); 410 } 411 412 if (const auto *F = dyn_cast<Function>(GO)) { 413 const auto &OptionalPrefix = F->getSectionPrefix(); 414 if (OptionalPrefix) 415 Name += *OptionalPrefix; 416 } 417 418 if (EmitUniqueSection && UniqueSectionNames) { 419 Name.push_back('.'); 420 TM.getNameWithPrefix(Name, GO, Mang, true); 421 } 422 unsigned UniqueID = MCContext::GenericSectionID; 423 if (EmitUniqueSection && !UniqueSectionNames) { 424 UniqueID = *NextUniqueID; 425 (*NextUniqueID)++; 426 } 427 // Use 0 as the unique ID for execute-only text 428 if (Kind.isExecuteOnly()) 429 UniqueID = 0; 430 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 431 EntrySize, Group, UniqueID, AssociatedSymbol); 432 } 433 434 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 435 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 436 unsigned Flags = getELFSectionFlags(Kind); 437 438 // If we have -ffunction-section or -fdata-section then we should emit the 439 // global value to a uniqued section specifically for it. 440 bool EmitUniqueSection = false; 441 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 442 if (Kind.isText()) 443 EmitUniqueSection = TM.getFunctionSections(); 444 else 445 EmitUniqueSection = TM.getDataSections(); 446 } 447 EmitUniqueSection |= GO->hasComdat(); 448 449 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 450 if (AssociatedSymbol) { 451 EmitUniqueSection = true; 452 Flags |= ELF::SHF_LINK_ORDER; 453 } 454 455 MCSectionELF *Section = selectELFSectionForGlobal( 456 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, 457 &NextUniqueID, AssociatedSymbol); 458 assert(Section->getAssociatedSymbol() == AssociatedSymbol); 459 return Section; 460 } 461 462 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 463 const Function &F, const TargetMachine &TM) const { 464 // If the function can be removed, produce a unique section so that 465 // the table doesn't prevent the removal. 466 const Comdat *C = F.getComdat(); 467 bool EmitUniqueSection = TM.getFunctionSections() || C; 468 if (!EmitUniqueSection) 469 return ReadOnlySection; 470 471 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 472 getMangler(), TM, EmitUniqueSection, 473 ELF::SHF_ALLOC, &NextUniqueID, 474 /* AssociatedSymbol */ nullptr); 475 } 476 477 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 478 bool UsesLabelDifference, const Function &F) const { 479 // We can always create relative relocations, so use another section 480 // that can be marked non-executable. 481 return false; 482 } 483 484 /// Given a mergeable constant with the specified size and relocation 485 /// information, return a section that it should be placed in. 486 MCSection *TargetLoweringObjectFileELF::getSectionForConstant( 487 const DataLayout &DL, SectionKind Kind, const Constant *C, 488 unsigned &Align) const { 489 if (Kind.isMergeableConst4() && MergeableConst4Section) 490 return MergeableConst4Section; 491 if (Kind.isMergeableConst8() && MergeableConst8Section) 492 return MergeableConst8Section; 493 if (Kind.isMergeableConst16() && MergeableConst16Section) 494 return MergeableConst16Section; 495 if (Kind.isMergeableConst32() && MergeableConst32Section) 496 return MergeableConst32Section; 497 if (Kind.isReadOnly()) 498 return ReadOnlySection; 499 500 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 501 return DataRelROSection; 502 } 503 504 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 505 bool IsCtor, unsigned Priority, 506 const MCSymbol *KeySym) { 507 std::string Name; 508 unsigned Type; 509 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 510 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 511 512 if (KeySym) 513 Flags |= ELF::SHF_GROUP; 514 515 if (UseInitArray) { 516 if (IsCtor) { 517 Type = ELF::SHT_INIT_ARRAY; 518 Name = ".init_array"; 519 } else { 520 Type = ELF::SHT_FINI_ARRAY; 521 Name = ".fini_array"; 522 } 523 if (Priority != 65535) { 524 Name += '.'; 525 Name += utostr(Priority); 526 } 527 } else { 528 // The default scheme is .ctor / .dtor, so we have to invert the priority 529 // numbering. 530 if (IsCtor) 531 Name = ".ctors"; 532 else 533 Name = ".dtors"; 534 if (Priority != 65535) { 535 Name += '.'; 536 Name += utostr(65535 - Priority); 537 } 538 Type = ELF::SHT_PROGBITS; 539 } 540 541 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 542 } 543 544 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 545 unsigned Priority, const MCSymbol *KeySym) const { 546 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 547 KeySym); 548 } 549 550 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 551 unsigned Priority, const MCSymbol *KeySym) const { 552 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 553 KeySym); 554 } 555 556 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 557 const GlobalValue *LHS, const GlobalValue *RHS, 558 const TargetMachine &TM) const { 559 // We may only use a PLT-relative relocation to refer to unnamed_addr 560 // functions. 561 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 562 return nullptr; 563 564 // Basic sanity checks. 565 if (LHS->getType()->getPointerAddressSpace() != 0 || 566 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 567 RHS->isThreadLocal()) 568 return nullptr; 569 570 return MCBinaryExpr::createSub( 571 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 572 getContext()), 573 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 574 } 575 576 void 577 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 578 UseInitArray = UseInitArray_; 579 MCContext &Ctx = getContext(); 580 if (!UseInitArray) { 581 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 582 ELF::SHF_ALLOC | ELF::SHF_WRITE); 583 584 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 585 ELF::SHF_ALLOC | ELF::SHF_WRITE); 586 return; 587 } 588 589 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 590 ELF::SHF_WRITE | ELF::SHF_ALLOC); 591 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 592 ELF::SHF_WRITE | ELF::SHF_ALLOC); 593 } 594 595 //===----------------------------------------------------------------------===// 596 // MachO 597 //===----------------------------------------------------------------------===// 598 599 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 600 : TargetLoweringObjectFile() { 601 SupportIndirectSymViaGOTPCRel = true; 602 } 603 604 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 605 const TargetMachine &TM) { 606 TargetLoweringObjectFile::Initialize(Ctx, TM); 607 if (TM.getRelocationModel() == Reloc::Static) { 608 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 609 SectionKind::getData()); 610 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 611 SectionKind::getData()); 612 } else { 613 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 614 MachO::S_MOD_INIT_FUNC_POINTERS, 615 SectionKind::getData()); 616 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 617 MachO::S_MOD_TERM_FUNC_POINTERS, 618 SectionKind::getData()); 619 } 620 } 621 622 void TargetLoweringObjectFileMachO::emitModuleMetadata( 623 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const { 624 // Emit the linker options if present. 625 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 626 for (const auto &Option : LinkerOptions->operands()) { 627 SmallVector<std::string, 4> StrOptions; 628 for (const auto &Piece : cast<MDNode>(Option)->operands()) 629 StrOptions.push_back(cast<MDString>(Piece)->getString()); 630 Streamer.EmitLinkerOptions(StrOptions); 631 } 632 } 633 634 unsigned VersionVal = 0; 635 unsigned ImageInfoFlags = 0; 636 StringRef SectionVal; 637 638 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 639 640 // The section is mandatory. If we don't have it, then we don't have GC info. 641 if (SectionVal.empty()) 642 return; 643 644 StringRef Segment, Section; 645 unsigned TAA = 0, StubSize = 0; 646 bool TAAParsed; 647 std::string ErrorCode = 648 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 649 TAA, TAAParsed, StubSize); 650 if (!ErrorCode.empty()) 651 // If invalid, report the error with report_fatal_error. 652 report_fatal_error("Invalid section specifier '" + Section + "': " + 653 ErrorCode + "."); 654 655 // Get the section. 656 MCSectionMachO *S = getContext().getMachOSection( 657 Segment, Section, TAA, StubSize, SectionKind::getData()); 658 Streamer.SwitchSection(S); 659 Streamer.EmitLabel(getContext(). 660 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 661 Streamer.EmitIntValue(VersionVal, 4); 662 Streamer.EmitIntValue(ImageInfoFlags, 4); 663 Streamer.AddBlankLine(); 664 } 665 666 static void checkMachOComdat(const GlobalValue *GV) { 667 const Comdat *C = GV->getComdat(); 668 if (!C) 669 return; 670 671 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 672 "' cannot be lowered."); 673 } 674 675 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 676 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 677 // Parse the section specifier and create it if valid. 678 StringRef Segment, Section; 679 unsigned TAA = 0, StubSize = 0; 680 bool TAAParsed; 681 682 checkMachOComdat(GO); 683 684 std::string ErrorCode = 685 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, 686 TAA, TAAParsed, StubSize); 687 if (!ErrorCode.empty()) { 688 // If invalid, report the error with report_fatal_error. 689 report_fatal_error("Global variable '" + GO->getName() + 690 "' has an invalid section specifier '" + 691 GO->getSection() + "': " + ErrorCode + "."); 692 } 693 694 // Get the section. 695 MCSectionMachO *S = 696 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 697 698 // If TAA wasn't set by ParseSectionSpecifier() above, 699 // use the value returned by getMachOSection() as a default. 700 if (!TAAParsed) 701 TAA = S->getTypeAndAttributes(); 702 703 // Okay, now that we got the section, verify that the TAA & StubSize agree. 704 // If the user declared multiple globals with different section flags, we need 705 // to reject it here. 706 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 707 // If invalid, report the error with report_fatal_error. 708 report_fatal_error("Global variable '" + GO->getName() + 709 "' section type or attributes does not match previous" 710 " section specifier"); 711 } 712 713 return S; 714 } 715 716 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 717 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 718 checkMachOComdat(GO); 719 720 // Handle thread local data. 721 if (Kind.isThreadBSS()) return TLSBSSSection; 722 if (Kind.isThreadData()) return TLSDataSection; 723 724 if (Kind.isText()) 725 return GO->isWeakForLinker() ? TextCoalSection : TextSection; 726 727 // If this is weak/linkonce, put this in a coalescable section, either in text 728 // or data depending on if it is writable. 729 if (GO->isWeakForLinker()) { 730 if (Kind.isReadOnly()) 731 return ConstTextCoalSection; 732 return DataCoalSection; 733 } 734 735 // FIXME: Alignment check should be handled by section classifier. 736 if (Kind.isMergeable1ByteCString() && 737 GO->getParent()->getDataLayout().getPreferredAlignment( 738 cast<GlobalVariable>(GO)) < 32) 739 return CStringSection; 740 741 // Do not put 16-bit arrays in the UString section if they have an 742 // externally visible label, this runs into issues with certain linker 743 // versions. 744 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 745 GO->getParent()->getDataLayout().getPreferredAlignment( 746 cast<GlobalVariable>(GO)) < 32) 747 return UStringSection; 748 749 // With MachO only variables whose corresponding symbol starts with 'l' or 750 // 'L' can be merged, so we only try merging GVs with private linkage. 751 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 752 if (Kind.isMergeableConst4()) 753 return FourByteConstantSection; 754 if (Kind.isMergeableConst8()) 755 return EightByteConstantSection; 756 if (Kind.isMergeableConst16()) 757 return SixteenByteConstantSection; 758 } 759 760 // Otherwise, if it is readonly, but not something we can specially optimize, 761 // just drop it in .const. 762 if (Kind.isReadOnly()) 763 return ReadOnlySection; 764 765 // If this is marked const, put it into a const section. But if the dynamic 766 // linker needs to write to it, put it in the data segment. 767 if (Kind.isReadOnlyWithRel()) 768 return ConstDataSection; 769 770 // Put zero initialized globals with strong external linkage in the 771 // DATA, __common section with the .zerofill directive. 772 if (Kind.isBSSExtern()) 773 return DataCommonSection; 774 775 // Put zero initialized globals with local linkage in __DATA,__bss directive 776 // with the .zerofill directive (aka .lcomm). 777 if (Kind.isBSSLocal()) 778 return DataBSSSection; 779 780 // Otherwise, just drop the variable in the normal data section. 781 return DataSection; 782 } 783 784 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 785 const DataLayout &DL, SectionKind Kind, const Constant *C, 786 unsigned &Align) const { 787 // If this constant requires a relocation, we have to put it in the data 788 // segment, not in the text segment. 789 if (Kind.isData() || Kind.isReadOnlyWithRel()) 790 return ConstDataSection; 791 792 if (Kind.isMergeableConst4()) 793 return FourByteConstantSection; 794 if (Kind.isMergeableConst8()) 795 return EightByteConstantSection; 796 if (Kind.isMergeableConst16()) 797 return SixteenByteConstantSection; 798 return ReadOnlySection; // .const 799 } 800 801 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 802 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 803 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 804 // The mach-o version of this method defaults to returning a stub reference. 805 806 if (Encoding & DW_EH_PE_indirect) { 807 MachineModuleInfoMachO &MachOMMI = 808 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 809 810 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 811 812 // Add information about the stub reference to MachOMMI so that the stub 813 // gets emitted by the asmprinter. 814 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 815 if (!StubSym.getPointer()) { 816 MCSymbol *Sym = TM.getSymbol(GV); 817 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 818 } 819 820 return TargetLoweringObjectFile:: 821 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 822 Encoding & ~DW_EH_PE_indirect, Streamer); 823 } 824 825 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 826 MMI, Streamer); 827 } 828 829 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 830 const GlobalValue *GV, const TargetMachine &TM, 831 MachineModuleInfo *MMI) const { 832 // The mach-o version of this method defaults to returning a stub reference. 833 MachineModuleInfoMachO &MachOMMI = 834 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 835 836 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 837 838 // Add information about the stub reference to MachOMMI so that the stub 839 // gets emitted by the asmprinter. 840 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 841 if (!StubSym.getPointer()) { 842 MCSymbol *Sym = TM.getSymbol(GV); 843 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 844 } 845 846 return SSym; 847 } 848 849 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 850 const MCSymbol *Sym, const MCValue &MV, int64_t Offset, 851 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 852 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 853 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 854 // through a non_lazy_ptr stub instead. One advantage is that it allows the 855 // computation of deltas to final external symbols. Example: 856 // 857 // _extgotequiv: 858 // .long _extfoo 859 // 860 // _delta: 861 // .long _extgotequiv-_delta 862 // 863 // is transformed to: 864 // 865 // _delta: 866 // .long L_extfoo$non_lazy_ptr-(_delta+0) 867 // 868 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 869 // L_extfoo$non_lazy_ptr: 870 // .indirect_symbol _extfoo 871 // .long 0 872 // 873 MachineModuleInfoMachO &MachOMMI = 874 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 875 MCContext &Ctx = getContext(); 876 877 // The offset must consider the original displacement from the base symbol 878 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 879 Offset = -MV.getConstant(); 880 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 881 882 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 883 // non_lazy_ptr stubs. 884 SmallString<128> Name; 885 StringRef Suffix = "$non_lazy_ptr"; 886 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 887 Name += Sym->getName(); 888 Name += Suffix; 889 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 890 891 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 892 if (!StubSym.getPointer()) 893 StubSym = MachineModuleInfoImpl:: 894 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */); 895 896 const MCExpr *BSymExpr = 897 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 898 const MCExpr *LHS = 899 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 900 901 if (!Offset) 902 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 903 904 const MCExpr *RHS = 905 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 906 return MCBinaryExpr::createSub(LHS, RHS, Ctx); 907 } 908 909 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 910 const MCSection &Section) { 911 if (!AsmInfo.isSectionAtomizableBySymbols(Section)) 912 return true; 913 914 // If it is not dead stripped, it is safe to use private labels. 915 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section); 916 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) 917 return true; 918 919 return false; 920 } 921 922 void TargetLoweringObjectFileMachO::getNameWithPrefix( 923 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 924 const TargetMachine &TM) const { 925 bool CannotUsePrivateLabel = true; 926 if (auto *GO = GV->getBaseObject()) { 927 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 928 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 929 CannotUsePrivateLabel = 930 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 931 } 932 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 933 } 934 935 //===----------------------------------------------------------------------===// 936 // COFF 937 //===----------------------------------------------------------------------===// 938 939 static unsigned 940 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 941 unsigned Flags = 0; 942 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 943 944 if (K.isMetadata()) 945 Flags |= 946 COFF::IMAGE_SCN_MEM_DISCARDABLE; 947 else if (K.isText()) 948 Flags |= 949 COFF::IMAGE_SCN_MEM_EXECUTE | 950 COFF::IMAGE_SCN_MEM_READ | 951 COFF::IMAGE_SCN_CNT_CODE | 952 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 953 else if (K.isBSS()) 954 Flags |= 955 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 956 COFF::IMAGE_SCN_MEM_READ | 957 COFF::IMAGE_SCN_MEM_WRITE; 958 else if (K.isThreadLocal()) 959 Flags |= 960 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 961 COFF::IMAGE_SCN_MEM_READ | 962 COFF::IMAGE_SCN_MEM_WRITE; 963 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 964 Flags |= 965 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 966 COFF::IMAGE_SCN_MEM_READ; 967 else if (K.isWriteable()) 968 Flags |= 969 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 970 COFF::IMAGE_SCN_MEM_READ | 971 COFF::IMAGE_SCN_MEM_WRITE; 972 973 return Flags; 974 } 975 976 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 977 const Comdat *C = GV->getComdat(); 978 assert(C && "expected GV to have a Comdat!"); 979 980 StringRef ComdatGVName = C->getName(); 981 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 982 if (!ComdatGV) 983 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 984 "' does not exist."); 985 986 if (ComdatGV->getComdat() != C) 987 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 988 "' is not a key for its COMDAT."); 989 990 return ComdatGV; 991 } 992 993 static int getSelectionForCOFF(const GlobalValue *GV) { 994 if (const Comdat *C = GV->getComdat()) { 995 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 996 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 997 ComdatKey = GA->getBaseObject(); 998 if (ComdatKey == GV) { 999 switch (C->getSelectionKind()) { 1000 case Comdat::Any: 1001 return COFF::IMAGE_COMDAT_SELECT_ANY; 1002 case Comdat::ExactMatch: 1003 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1004 case Comdat::Largest: 1005 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1006 case Comdat::NoDuplicates: 1007 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1008 case Comdat::SameSize: 1009 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1010 } 1011 } else { 1012 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1013 } 1014 } 1015 return 0; 1016 } 1017 1018 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1019 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1020 int Selection = 0; 1021 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1022 StringRef Name = GO->getSection(); 1023 StringRef COMDATSymName = ""; 1024 if (GO->hasComdat()) { 1025 Selection = getSelectionForCOFF(GO); 1026 const GlobalValue *ComdatGV; 1027 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1028 ComdatGV = getComdatGVForCOFF(GO); 1029 else 1030 ComdatGV = GO; 1031 1032 if (!ComdatGV->hasPrivateLinkage()) { 1033 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1034 COMDATSymName = Sym->getName(); 1035 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1036 } else { 1037 Selection = 0; 1038 } 1039 } 1040 1041 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1042 Selection); 1043 } 1044 1045 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1046 if (Kind.isText()) 1047 return ".text"; 1048 if (Kind.isBSS()) 1049 return ".bss"; 1050 if (Kind.isThreadLocal()) 1051 return ".tls$"; 1052 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1053 return ".rdata"; 1054 return ".data"; 1055 } 1056 1057 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1058 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1059 // If we have -ffunction-sections then we should emit the global value to a 1060 // uniqued section specifically for it. 1061 bool EmitUniquedSection; 1062 if (Kind.isText()) 1063 EmitUniquedSection = TM.getFunctionSections(); 1064 else 1065 EmitUniquedSection = TM.getDataSections(); 1066 1067 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1068 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 1069 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1070 1071 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1072 int Selection = getSelectionForCOFF(GO); 1073 if (!Selection) 1074 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1075 const GlobalValue *ComdatGV; 1076 if (GO->hasComdat()) 1077 ComdatGV = getComdatGVForCOFF(GO); 1078 else 1079 ComdatGV = GO; 1080 1081 unsigned UniqueID = MCContext::GenericSectionID; 1082 if (EmitUniquedSection) 1083 UniqueID = NextUniqueID++; 1084 1085 if (!ComdatGV->hasPrivateLinkage()) { 1086 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1087 StringRef COMDATSymName = Sym->getName(); 1088 return getContext().getCOFFSection(Name, Characteristics, Kind, 1089 COMDATSymName, Selection, UniqueID); 1090 } else { 1091 SmallString<256> TmpData; 1092 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1093 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 1094 Selection, UniqueID); 1095 } 1096 } 1097 1098 if (Kind.isText()) 1099 return TextSection; 1100 1101 if (Kind.isThreadLocal()) 1102 return TLSDataSection; 1103 1104 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1105 return ReadOnlySection; 1106 1107 // Note: we claim that common symbols are put in BSSSection, but they are 1108 // really emitted with the magic .comm directive, which creates a symbol table 1109 // entry but not a section. 1110 if (Kind.isBSS() || Kind.isCommon()) 1111 return BSSSection; 1112 1113 return DataSection; 1114 } 1115 1116 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 1117 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1118 const TargetMachine &TM) const { 1119 bool CannotUsePrivateLabel = false; 1120 if (GV->hasPrivateLinkage() && 1121 ((isa<Function>(GV) && TM.getFunctionSections()) || 1122 (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1123 CannotUsePrivateLabel = true; 1124 1125 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1126 } 1127 1128 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1129 const Function &F, const TargetMachine &TM) const { 1130 // If the function can be removed, produce a unique section so that 1131 // the table doesn't prevent the removal. 1132 const Comdat *C = F.getComdat(); 1133 bool EmitUniqueSection = TM.getFunctionSections() || C; 1134 if (!EmitUniqueSection) 1135 return ReadOnlySection; 1136 1137 // FIXME: we should produce a symbol for F instead. 1138 if (F.hasPrivateLinkage()) 1139 return ReadOnlySection; 1140 1141 MCSymbol *Sym = TM.getSymbol(&F); 1142 StringRef COMDATSymName = Sym->getName(); 1143 1144 SectionKind Kind = SectionKind::getReadOnly(); 1145 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 1146 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1147 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1148 unsigned UniqueID = NextUniqueID++; 1149 1150 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1151 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 1152 } 1153 1154 void TargetLoweringObjectFileCOFF::emitModuleMetadata( 1155 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const { 1156 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1157 // Emit the linker options to the linker .drectve section. According to the 1158 // spec, this section is a space-separated string containing flags for 1159 // linker. 1160 MCSection *Sec = getDrectveSection(); 1161 Streamer.SwitchSection(Sec); 1162 for (const auto &Option : LinkerOptions->operands()) { 1163 for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1164 // Lead with a space for consistency with our dllexport implementation. 1165 std::string Directive(" "); 1166 Directive.append(cast<MDString>(Piece)->getString()); 1167 Streamer.EmitBytes(Directive); 1168 } 1169 } 1170 } 1171 1172 unsigned Version = 0; 1173 unsigned Flags = 0; 1174 StringRef Section; 1175 1176 GetObjCImageInfo(M, Version, Flags, Section); 1177 if (Section.empty()) 1178 return; 1179 1180 auto &C = getContext(); 1181 auto *S = C.getCOFFSection( 1182 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1183 SectionKind::getReadOnly()); 1184 Streamer.SwitchSection(S); 1185 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1186 Streamer.EmitIntValue(Version, 4); 1187 Streamer.EmitIntValue(Flags, 4); 1188 Streamer.AddBlankLine(); 1189 } 1190 1191 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1192 const TargetMachine &TM) { 1193 TargetLoweringObjectFile::Initialize(Ctx, TM); 1194 const Triple &T = TM.getTargetTriple(); 1195 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1196 StaticCtorSection = 1197 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1198 COFF::IMAGE_SCN_MEM_READ, 1199 SectionKind::getReadOnly()); 1200 StaticDtorSection = 1201 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1202 COFF::IMAGE_SCN_MEM_READ, 1203 SectionKind::getReadOnly()); 1204 } else { 1205 StaticCtorSection = Ctx.getCOFFSection( 1206 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1207 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1208 SectionKind::getData()); 1209 StaticDtorSection = Ctx.getCOFFSection( 1210 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1211 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1212 SectionKind::getData()); 1213 } 1214 } 1215 1216 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1217 unsigned Priority, const MCSymbol *KeySym) const { 1218 return getContext().getAssociativeCOFFSection( 1219 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0); 1220 } 1221 1222 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1223 unsigned Priority, const MCSymbol *KeySym) const { 1224 return getContext().getAssociativeCOFFSection( 1225 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0); 1226 } 1227 1228 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal( 1229 raw_ostream &OS, const GlobalValue *GV) const { 1230 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler()); 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // Wasm 1235 //===----------------------------------------------------------------------===// 1236 1237 static const Comdat *getWasmComdat(const GlobalValue *GV) { 1238 const Comdat *C = GV->getComdat(); 1239 if (!C) 1240 return nullptr; 1241 1242 if (C->getSelectionKind() != Comdat::Any) 1243 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" + 1244 C->getName() + "' cannot be lowered."); 1245 1246 return C; 1247 } 1248 1249 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 1250 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1251 StringRef Name = GO->getSection(); 1252 return getContext().getWasmSection(Name, wasm::WASM_SEC_DATA); 1253 } 1254 1255 static MCSectionWasm *selectWasmSectionForGlobal( 1256 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 1257 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { 1258 StringRef Group = ""; 1259 if (getWasmComdat(GO)) 1260 llvm_unreachable("comdat not yet supported for wasm"); 1261 1262 bool UniqueSectionNames = TM.getUniqueSectionNames(); 1263 SmallString<128> Name = getSectionPrefixForGlobal(Kind); 1264 1265 uint32_t Type = wasm::WASM_SEC_DATA; 1266 if (const auto *F = dyn_cast<Function>(GO)) { 1267 const auto &OptionalPrefix = F->getSectionPrefix(); 1268 if (OptionalPrefix) 1269 Name += *OptionalPrefix; 1270 Type = wasm::WASM_SEC_CODE; 1271 } 1272 1273 if (EmitUniqueSection && UniqueSectionNames) { 1274 Name.push_back('.'); 1275 TM.getNameWithPrefix(Name, GO, Mang, true); 1276 } 1277 unsigned UniqueID = MCContext::GenericSectionID; 1278 if (EmitUniqueSection && !UniqueSectionNames) { 1279 UniqueID = *NextUniqueID; 1280 (*NextUniqueID)++; 1281 } 1282 return Ctx.getWasmSection(Name, Type, Group, UniqueID); 1283 } 1284 1285 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 1286 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1287 1288 if (Kind.isCommon()) 1289 report_fatal_error("mergable sections not supported yet on wasm"); 1290 1291 // If we have -ffunction-section or -fdata-section then we should emit the 1292 // global value to a uniqued section specifically for it. 1293 bool EmitUniqueSection = false; 1294 if (Kind.isText()) 1295 EmitUniqueSection = TM.getFunctionSections(); 1296 else 1297 EmitUniqueSection = TM.getDataSections(); 1298 EmitUniqueSection |= GO->hasComdat(); 1299 1300 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 1301 EmitUniqueSection, &NextUniqueID); 1302 } 1303 1304 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 1305 bool UsesLabelDifference, const Function &F) const { 1306 // We can always create relative relocations, so use another section 1307 // that can be marked non-executable. 1308 return false; 1309 } 1310 1311 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 1312 const GlobalValue *LHS, const GlobalValue *RHS, 1313 const TargetMachine &TM) const { 1314 // We may only use a PLT-relative relocation to refer to unnamed_addr 1315 // functions. 1316 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1317 return nullptr; 1318 1319 // Basic sanity checks. 1320 if (LHS->getType()->getPointerAddressSpace() != 0 || 1321 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1322 RHS->isThreadLocal()) 1323 return nullptr; 1324 1325 return MCBinaryExpr::createSub( 1326 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 1327 getContext()), 1328 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1329 } 1330 1331 void 1332 TargetLoweringObjectFileWasm::InitializeWasm() { 1333 // TODO: Initialize StaticCtorSection and StaticDtorSection. 1334 } 1335