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/MCContext.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/MC/MCSectionCOFF.h" 30 #include "llvm/MC/MCSectionELF.h" 31 #include "llvm/MC/MCSectionMachO.h" 32 #include "llvm/MC/MCStreamer.h" 33 #include "llvm/MC/MCSymbol.h" 34 #include "llvm/Support/Dwarf.h" 35 #include "llvm/Support/ELF.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetLowering.h" 39 #include "llvm/Target/TargetMachine.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 using namespace llvm; 42 using namespace dwarf; 43 44 //===----------------------------------------------------------------------===// 45 // ELF 46 //===----------------------------------------------------------------------===// 47 48 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM, 50 MachineModuleInfo *MMI) const { 51 unsigned Encoding = getPersonalityEncoding(); 52 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect) 53 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") + 54 TM.getSymbol(GV, Mang)->getName()); 55 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr) 56 return TM.getSymbol(GV, Mang); 57 report_fatal_error("We do not support this DWARF encoding yet!"); 58 } 59 60 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer, 61 const TargetMachine &TM, 62 const MCSymbol *Sym) const { 63 SmallString<64> NameData("DW.ref."); 64 NameData += Sym->getName(); 65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData); 66 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 68 StringRef Prefix = ".data."; 69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end()); 70 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 71 const MCSection *Sec = getContext().getELFSection(NameData, 72 ELF::SHT_PROGBITS, 73 Flags, 74 0, Label->getName()); 75 unsigned Size = TM.getDataLayout()->getPointerSize(); 76 Streamer.SwitchSection(Sec); 77 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment()); 78 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 79 const MCExpr *E = MCConstantExpr::Create(Size, getContext()); 80 Streamer.EmitELFSize(Label, E); 81 Streamer.EmitLabel(Label); 82 83 Streamer.EmitSymbolValue(Sym, Size); 84 } 85 86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang, 88 const TargetMachine &TM, MachineModuleInfo *MMI, 89 MCStreamer &Streamer) const { 90 91 if (Encoding & dwarf::DW_EH_PE_indirect) { 92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 93 94 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM); 95 96 // Add information about the stub reference to ELFMMI so that the stub 97 // gets emitted by the asmprinter. 98 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 99 if (!StubSym.getPointer()) { 100 MCSymbol *Sym = TM.getSymbol(GV, Mang); 101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 102 } 103 104 return TargetLoweringObjectFile:: 105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 107 } 108 109 return TargetLoweringObjectFile:: 110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer); 111 } 112 113 static SectionKind 114 getELFKindForNamedSection(StringRef Name, SectionKind K) { 115 // N.B.: The defaults used in here are no the same ones used in MC. 116 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 117 // both gas and MC will produce a section with no flags. Given 118 // section(".eh_frame") gcc will produce: 119 // 120 // .section .eh_frame,"a",@progbits 121 if (Name.empty() || Name[0] != '.') return K; 122 123 // Some lame default implementation based on some magic section names. 124 if (Name == ".bss" || 125 Name.startswith(".bss.") || 126 Name.startswith(".gnu.linkonce.b.") || 127 Name.startswith(".llvm.linkonce.b.") || 128 Name == ".sbss" || 129 Name.startswith(".sbss.") || 130 Name.startswith(".gnu.linkonce.sb.") || 131 Name.startswith(".llvm.linkonce.sb.")) 132 return SectionKind::getBSS(); 133 134 if (Name == ".tdata" || 135 Name.startswith(".tdata.") || 136 Name.startswith(".gnu.linkonce.td.") || 137 Name.startswith(".llvm.linkonce.td.")) 138 return SectionKind::getThreadData(); 139 140 if (Name == ".tbss" || 141 Name.startswith(".tbss.") || 142 Name.startswith(".gnu.linkonce.tb.") || 143 Name.startswith(".llvm.linkonce.tb.")) 144 return SectionKind::getThreadBSS(); 145 146 return K; 147 } 148 149 150 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 151 152 if (Name == ".init_array") 153 return ELF::SHT_INIT_ARRAY; 154 155 if (Name == ".fini_array") 156 return ELF::SHT_FINI_ARRAY; 157 158 if (Name == ".preinit_array") 159 return ELF::SHT_PREINIT_ARRAY; 160 161 if (K.isBSS() || K.isThreadBSS()) 162 return ELF::SHT_NOBITS; 163 164 return ELF::SHT_PROGBITS; 165 } 166 167 static unsigned getELFSectionFlags(SectionKind K) { 168 unsigned Flags = 0; 169 170 if (!K.isMetadata()) 171 Flags |= ELF::SHF_ALLOC; 172 173 if (K.isText()) 174 Flags |= ELF::SHF_EXECINSTR; 175 176 if (K.isWriteable()) 177 Flags |= ELF::SHF_WRITE; 178 179 if (K.isThreadLocal()) 180 Flags |= ELF::SHF_TLS; 181 182 if (K.isMergeableCString() || K.isMergeableConst()) 183 Flags |= ELF::SHF_MERGE; 184 185 if (K.isMergeableCString()) 186 Flags |= ELF::SHF_STRINGS; 187 188 return Flags; 189 } 190 191 static const Comdat *getELFComdat(const GlobalValue *GV) { 192 const Comdat *C = GV->getComdat(); 193 if (!C) 194 return nullptr; 195 196 if (C->getSelectionKind() != Comdat::Any) 197 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 198 C->getName() + "' cannot be lowered."); 199 200 return C; 201 } 202 203 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 204 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 205 const TargetMachine &TM) const { 206 StringRef SectionName = GV->getSection(); 207 208 // Infer section flags from the section name if we can. 209 Kind = getELFKindForNamedSection(SectionName, Kind); 210 211 StringRef Group = ""; 212 unsigned Flags = getELFSectionFlags(Kind); 213 if (const Comdat *C = getELFComdat(GV)) { 214 Group = C->getName(); 215 Flags |= ELF::SHF_GROUP; 216 } 217 return getContext().getELFSection(SectionName, 218 getELFSectionType(SectionName, Kind), Flags, 219 /*EntrySize=*/0, Group); 220 } 221 222 /// Return the section prefix name used by options FunctionsSections and 223 /// DataSections. 224 static StringRef getSectionPrefixForGlobal(SectionKind Kind) { 225 if (Kind.isText()) 226 return ".text"; 227 if (Kind.isReadOnly()) 228 return ".rodata"; 229 if (Kind.isBSS()) 230 return ".bss"; 231 if (Kind.isThreadData()) 232 return ".tdata"; 233 if (Kind.isThreadBSS()) 234 return ".tbss"; 235 if (Kind.isDataNoRel()) 236 return ".data"; 237 if (Kind.isDataRelLocal()) 238 return ".data.rel.local"; 239 if (Kind.isDataRel()) 240 return ".data.rel"; 241 if (Kind.isReadOnlyWithRelLocal()) 242 return ".data.rel.ro.local"; 243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 244 return ".data.rel.ro"; 245 } 246 247 static const MCSectionELF *selectELFSectionForGlobal( 248 MCContext &Ctx, const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 249 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags) { 250 unsigned EntrySize = 0; 251 if (Kind.isMergeableCString()) { 252 if (Kind.isMergeable2ByteCString()) { 253 EntrySize = 2; 254 } else if (Kind.isMergeable4ByteCString()) { 255 EntrySize = 4; 256 } else { 257 EntrySize = 1; 258 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 259 } 260 } else if (Kind.isMergeableConst()) { 261 if (Kind.isMergeableConst4()) { 262 EntrySize = 4; 263 } else if (Kind.isMergeableConst8()) { 264 EntrySize = 8; 265 } else { 266 assert(Kind.isMergeableConst16() && "unknown data width"); 267 EntrySize = 16; 268 } 269 } 270 271 StringRef Group = ""; 272 if (const Comdat *C = getELFComdat(GV)) { 273 Flags |= ELF::SHF_GROUP; 274 Group = C->getName(); 275 } 276 277 bool UniqueSectionNames = TM.getUniqueSectionNames(); 278 SmallString<128> Name; 279 if (Kind.isMergeableCString()) { 280 // We also need alignment here. 281 // FIXME: this is getting the alignment of the character, not the 282 // alignment of the global! 283 unsigned Align = 284 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)); 285 286 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 287 Name = SizeSpec + utostr(Align); 288 } else if (Kind.isMergeableConst()) { 289 Name = ".rodata.cst"; 290 Name += utostr(EntrySize); 291 } else { 292 Name = getSectionPrefixForGlobal(Kind); 293 } 294 295 if (EmitUniqueSection && UniqueSectionNames) { 296 Name.push_back('.'); 297 TM.getNameWithPrefix(Name, GV, Mang, true); 298 } 299 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 300 EntrySize, Group, 301 EmitUniqueSection && !UniqueSectionNames); 302 } 303 304 const MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 305 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 306 const TargetMachine &TM) const { 307 unsigned Flags = getELFSectionFlags(Kind); 308 309 // If we have -ffunction-section or -fdata-section then we should emit the 310 // global value to a uniqued section specifically for it. 311 bool EmitUniqueSection = false; 312 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 313 if (Kind.isText()) 314 EmitUniqueSection = TM.getFunctionSections(); 315 else 316 EmitUniqueSection = TM.getDataSections(); 317 } 318 EmitUniqueSection |= GV->hasComdat(); 319 320 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM, 321 EmitUniqueSection, Flags); 322 } 323 324 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 325 const Function &F, Mangler &Mang, const TargetMachine &TM) const { 326 // If the function can be removed, produce a unique section so that 327 // the table doesn't prevent the removal. 328 const Comdat *C = F.getComdat(); 329 bool EmitUniqueSection = TM.getFunctionSections() || C; 330 if (!EmitUniqueSection) 331 return ReadOnlySection; 332 333 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 334 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC); 335 } 336 337 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 338 bool UsesLabelDifference, const Function &F) const { 339 // We can always create relative relocations, so use another section 340 // that can be marked non-executable. 341 return false; 342 } 343 344 /// getSectionForConstant - Given a mergeable constant with the 345 /// specified size and relocation information, return a section that it 346 /// should be placed in. 347 const MCSection * 348 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind, 349 const Constant *C) const { 350 if (Kind.isMergeableConst4() && MergeableConst4Section) 351 return MergeableConst4Section; 352 if (Kind.isMergeableConst8() && MergeableConst8Section) 353 return MergeableConst8Section; 354 if (Kind.isMergeableConst16() && MergeableConst16Section) 355 return MergeableConst16Section; 356 if (Kind.isReadOnly()) 357 return ReadOnlySection; 358 359 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 360 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 361 return DataRelROSection; 362 } 363 364 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx, 365 bool UseInitArray, 366 bool IsCtor, 367 unsigned Priority, 368 const MCSymbol *KeySym) { 369 std::string Name; 370 unsigned Type; 371 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 372 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 373 374 if (KeySym) 375 Flags |= ELF::SHF_GROUP; 376 377 if (UseInitArray) { 378 if (IsCtor) { 379 Type = ELF::SHT_INIT_ARRAY; 380 Name = ".init_array"; 381 } else { 382 Type = ELF::SHT_FINI_ARRAY; 383 Name = ".fini_array"; 384 } 385 if (Priority != 65535) { 386 Name += '.'; 387 Name += utostr(Priority); 388 } 389 } else { 390 // The default scheme is .ctor / .dtor, so we have to invert the priority 391 // numbering. 392 if (IsCtor) 393 Name = ".ctors"; 394 else 395 Name = ".dtors"; 396 if (Priority != 65535) { 397 Name += '.'; 398 Name += utostr(65535 - Priority); 399 } 400 Type = ELF::SHT_PROGBITS; 401 } 402 403 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 404 } 405 406 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 407 unsigned Priority, const MCSymbol *KeySym) const { 408 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 409 KeySym); 410 } 411 412 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 413 unsigned Priority, const MCSymbol *KeySym) const { 414 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 415 KeySym); 416 } 417 418 void 419 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 420 UseInitArray = UseInitArray_; 421 if (!UseInitArray) 422 return; 423 424 StaticCtorSection = getContext().getELFSection( 425 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); 426 StaticDtorSection = getContext().getELFSection( 427 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); 428 } 429 430 //===----------------------------------------------------------------------===// 431 // MachO 432 //===----------------------------------------------------------------------===// 433 434 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker 435 /// option string. Returns StringRef() if the option does not specify a library. 436 StringRef TargetLoweringObjectFileMachO:: 437 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 438 const char *LibCmd = "-l"; 439 if (LinkerOption.startswith(LibCmd)) 440 return LinkerOption.substr(strlen(LibCmd)); 441 return StringRef(); 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 const MCSectionMachO *S = 511 getContext().getMachOSection(Segment, Section, TAA, StubSize, 512 SectionKind::getDataNoRel()); 513 Streamer.SwitchSection(S); 514 Streamer.EmitLabel(getContext(). 515 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 516 Streamer.EmitIntValue(VersionVal, 4); 517 Streamer.EmitIntValue(ImageInfoFlags, 4); 518 Streamer.AddBlankLine(); 519 } 520 521 static void checkMachOComdat(const GlobalValue *GV) { 522 const Comdat *C = GV->getComdat(); 523 if (!C) 524 return; 525 526 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 527 "' cannot be lowered."); 528 } 529 530 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 531 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 532 const TargetMachine &TM) const { 533 // Parse the section specifier and create it if valid. 534 StringRef Segment, Section; 535 unsigned TAA = 0, StubSize = 0; 536 bool TAAParsed; 537 538 checkMachOComdat(GV); 539 540 std::string ErrorCode = 541 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 542 TAA, TAAParsed, StubSize); 543 if (!ErrorCode.empty()) { 544 // If invalid, report the error with report_fatal_error. 545 report_fatal_error("Global variable '" + GV->getName() + 546 "' has an invalid section specifier '" + 547 GV->getSection() + "': " + ErrorCode + "."); 548 } 549 550 // Get the section. 551 const MCSectionMachO *S = 552 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 553 554 // If TAA wasn't set by ParseSectionSpecifier() above, 555 // use the value returned by getMachOSection() as a default. 556 if (!TAAParsed) 557 TAA = S->getTypeAndAttributes(); 558 559 // Okay, now that we got the section, verify that the TAA & StubSize agree. 560 // If the user declared multiple globals with different section flags, we need 561 // to reject it here. 562 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 563 // If invalid, report the error with report_fatal_error. 564 report_fatal_error("Global variable '" + GV->getName() + 565 "' section type or attributes does not match previous" 566 " section specifier"); 567 } 568 569 return S; 570 } 571 572 const MCSection *TargetLoweringObjectFileMachO:: 573 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 574 Mangler &Mang, const TargetMachine &TM) const { 575 checkMachOComdat(GV); 576 577 // Handle thread local data. 578 if (Kind.isThreadBSS()) return TLSBSSSection; 579 if (Kind.isThreadData()) return TLSDataSection; 580 581 if (Kind.isText()) 582 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 583 584 // If this is weak/linkonce, put this in a coalescable section, either in text 585 // or data depending on if it is writable. 586 if (GV->isWeakForLinker()) { 587 if (Kind.isReadOnly()) 588 return ConstTextCoalSection; 589 return DataCoalSection; 590 } 591 592 // FIXME: Alignment check should be handled by section classifier. 593 if (Kind.isMergeable1ByteCString() && 594 TM.getDataLayout()->getPreferredAlignment(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 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 602 return UStringSection; 603 604 // With MachO only variables whose corresponding symbol starts with 'l' or 605 // 'L' can be merged, so we only try merging GVs with private linkage. 606 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) { 607 if (Kind.isMergeableConst4()) 608 return FourByteConstantSection; 609 if (Kind.isMergeableConst8()) 610 return EightByteConstantSection; 611 if (Kind.isMergeableConst16()) 612 return SixteenByteConstantSection; 613 } 614 615 // Otherwise, if it is readonly, but not something we can specially optimize, 616 // just drop it in .const. 617 if (Kind.isReadOnly()) 618 return ReadOnlySection; 619 620 // If this is marked const, put it into a const section. But if the dynamic 621 // linker needs to write to it, put it in the data segment. 622 if (Kind.isReadOnlyWithRel()) 623 return ConstDataSection; 624 625 // Put zero initialized globals with strong external linkage in the 626 // DATA, __common section with the .zerofill directive. 627 if (Kind.isBSSExtern()) 628 return DataCommonSection; 629 630 // Put zero initialized globals with local linkage in __DATA,__bss directive 631 // with the .zerofill directive (aka .lcomm). 632 if (Kind.isBSSLocal()) 633 return DataBSSSection; 634 635 // Otherwise, just drop the variable in the normal data section. 636 return DataSection; 637 } 638 639 const MCSection * 640 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind, 641 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.isDataRel() || 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 //===----------------------------------------------------------------------===// 709 // COFF 710 //===----------------------------------------------------------------------===// 711 712 static unsigned 713 getCOFFSectionFlags(SectionKind K) { 714 unsigned Flags = 0; 715 716 if (K.isMetadata()) 717 Flags |= 718 COFF::IMAGE_SCN_MEM_DISCARDABLE; 719 else if (K.isText()) 720 Flags |= 721 COFF::IMAGE_SCN_MEM_EXECUTE | 722 COFF::IMAGE_SCN_MEM_READ | 723 COFF::IMAGE_SCN_CNT_CODE; 724 else if (K.isBSS()) 725 Flags |= 726 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 727 COFF::IMAGE_SCN_MEM_READ | 728 COFF::IMAGE_SCN_MEM_WRITE; 729 else if (K.isThreadLocal()) 730 Flags |= 731 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 732 COFF::IMAGE_SCN_MEM_READ | 733 COFF::IMAGE_SCN_MEM_WRITE; 734 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 735 Flags |= 736 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 737 COFF::IMAGE_SCN_MEM_READ; 738 else if (K.isWriteable()) 739 Flags |= 740 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 741 COFF::IMAGE_SCN_MEM_READ | 742 COFF::IMAGE_SCN_MEM_WRITE; 743 744 return Flags; 745 } 746 747 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 748 const Comdat *C = GV->getComdat(); 749 assert(C && "expected GV to have a Comdat!"); 750 751 StringRef ComdatGVName = C->getName(); 752 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 753 if (!ComdatGV) 754 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 755 "' does not exist."); 756 757 if (ComdatGV->getComdat() != C) 758 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 759 "' is not a key for its COMDAT."); 760 761 return ComdatGV; 762 } 763 764 static int getSelectionForCOFF(const GlobalValue *GV) { 765 if (const Comdat *C = GV->getComdat()) { 766 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 767 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 768 ComdatKey = GA->getBaseObject(); 769 if (ComdatKey == GV) { 770 switch (C->getSelectionKind()) { 771 case Comdat::Any: 772 return COFF::IMAGE_COMDAT_SELECT_ANY; 773 case Comdat::ExactMatch: 774 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 775 case Comdat::Largest: 776 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 777 case Comdat::NoDuplicates: 778 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 779 case Comdat::SameSize: 780 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 781 } 782 } else { 783 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 784 } 785 } else if (GV->isWeakForLinker()) { 786 return COFF::IMAGE_COMDAT_SELECT_ANY; 787 } 788 return 0; 789 } 790 791 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 792 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 793 const TargetMachine &TM) const { 794 int Selection = 0; 795 unsigned Characteristics = getCOFFSectionFlags(Kind); 796 StringRef Name = GV->getSection(); 797 StringRef COMDATSymName = ""; 798 if (GV->hasComdat()) { 799 Selection = getSelectionForCOFF(GV); 800 const GlobalValue *ComdatGV; 801 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 802 ComdatGV = getComdatGVForCOFF(GV); 803 else 804 ComdatGV = GV; 805 806 if (!ComdatGV->hasPrivateLinkage()) { 807 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 808 COMDATSymName = Sym->getName(); 809 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 810 } else { 811 Selection = 0; 812 } 813 } 814 return getContext().getCOFFSection(Name, 815 Characteristics, 816 Kind, 817 COMDATSymName, 818 Selection); 819 } 820 821 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 822 if (Kind.isText()) 823 return ".text"; 824 if (Kind.isBSS()) 825 return ".bss"; 826 if (Kind.isThreadLocal()) 827 return ".tls$"; 828 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 829 return ".rdata"; 830 return ".data"; 831 } 832 833 834 const MCSection *TargetLoweringObjectFileCOFF:: 835 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 836 Mangler &Mang, const TargetMachine &TM) const { 837 // If we have -ffunction-sections then we should emit the global value to a 838 // uniqued section specifically for it. 839 bool EmitUniquedSection; 840 if (Kind.isText()) 841 EmitUniquedSection = TM.getFunctionSections(); 842 else 843 EmitUniquedSection = TM.getDataSections(); 844 845 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) { 846 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 847 unsigned Characteristics = getCOFFSectionFlags(Kind); 848 849 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 850 int Selection = getSelectionForCOFF(GV); 851 if (!Selection) 852 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 853 const GlobalValue *ComdatGV; 854 if (GV->hasComdat()) 855 ComdatGV = getComdatGVForCOFF(GV); 856 else 857 ComdatGV = GV; 858 859 if (!ComdatGV->hasPrivateLinkage()) { 860 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 861 StringRef COMDATSymName = Sym->getName(); 862 return getContext().getCOFFSection(Name, Characteristics, Kind, 863 COMDATSymName, Selection); 864 } 865 } 866 867 if (Kind.isText()) 868 return TextSection; 869 870 if (Kind.isThreadLocal()) 871 return TLSDataSection; 872 873 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 874 return ReadOnlySection; 875 876 // Note: we claim that common symbols are put in BSSSection, but they are 877 // really emitted with the magic .comm directive, which creates a symbol table 878 // entry but not a section. 879 if (Kind.isBSS() || Kind.isCommon()) 880 return BSSSection; 881 882 return DataSection; 883 } 884 885 StringRef TargetLoweringObjectFileCOFF:: 886 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 887 const char *LibCmd = "/DEFAULTLIB:"; 888 if (LinkerOption.startswith(LibCmd)) 889 return LinkerOption.substr(strlen(LibCmd)); 890 return StringRef(); 891 } 892 893 void TargetLoweringObjectFileCOFF:: 894 emitModuleFlags(MCStreamer &Streamer, 895 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 896 Mangler &Mang, const TargetMachine &TM) const { 897 MDNode *LinkerOptions = nullptr; 898 899 // Look for the "Linker Options" flag, since it's the only one we support. 900 for (ArrayRef<Module::ModuleFlagEntry>::iterator 901 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 902 const Module::ModuleFlagEntry &MFE = *i; 903 StringRef Key = MFE.Key->getString(); 904 Metadata *Val = MFE.Val; 905 if (Key == "Linker Options") { 906 LinkerOptions = cast<MDNode>(Val); 907 break; 908 } 909 } 910 if (!LinkerOptions) 911 return; 912 913 // Emit the linker options to the linker .drectve section. According to the 914 // spec, this section is a space-separated string containing flags for linker. 915 const MCSection *Sec = getDrectveSection(); 916 Streamer.SwitchSection(Sec); 917 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 918 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 919 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 920 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 921 // Lead with a space for consistency with our dllexport implementation. 922 std::string Directive(" "); 923 Directive.append(MDOption->getString()); 924 Streamer.EmitBytes(Directive); 925 } 926 } 927 } 928 929 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 930 unsigned Priority, const MCSymbol *KeySym) const { 931 return getContext().getAssociativeCOFFSection( 932 cast<MCSectionCOFF>(StaticCtorSection), KeySym); 933 } 934 935 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 936 unsigned Priority, const MCSymbol *KeySym) const { 937 return getContext().getAssociativeCOFFSection( 938 cast<MCSectionCOFF>(StaticDtorSection), KeySym); 939 } 940