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