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