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