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