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