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 *selectELFSectionForGlobal( 249 MCContext &Ctx, const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 250 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags) { 251 unsigned EntrySize = 0; 252 if (Kind.isMergeableCString()) { 253 if (Kind.isMergeable2ByteCString()) { 254 EntrySize = 2; 255 } else if (Kind.isMergeable4ByteCString()) { 256 EntrySize = 4; 257 } else { 258 EntrySize = 1; 259 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 260 } 261 } else if (Kind.isMergeableConst()) { 262 if (Kind.isMergeableConst4()) { 263 EntrySize = 4; 264 } else if (Kind.isMergeableConst8()) { 265 EntrySize = 8; 266 } else { 267 assert(Kind.isMergeableConst16() && "unknown data width"); 268 EntrySize = 16; 269 } 270 } 271 272 StringRef Group = ""; 273 if (const Comdat *C = getELFComdat(GV)) { 274 Flags |= ELF::SHF_GROUP; 275 Group = C->getName(); 276 } 277 278 bool UniqueSectionNames = TM.getUniqueSectionNames(); 279 SmallString<128> Name; 280 if (Kind.isMergeableCString()) { 281 // We also need alignment here. 282 // FIXME: this is getting the alignment of the character, not the 283 // alignment of the global! 284 unsigned Align = 285 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)); 286 287 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 288 Name = SizeSpec + utostr(Align); 289 } else if (Kind.isMergeableConst()) { 290 Name = ".rodata.cst"; 291 Name += utostr(EntrySize); 292 } else { 293 Name = getSectionPrefixForGlobal(Kind); 294 } 295 296 if (EmitUniqueSection && UniqueSectionNames) { 297 Name.push_back('.'); 298 TM.getNameWithPrefix(Name, GV, Mang, true); 299 } 300 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 301 EntrySize, Group, 302 EmitUniqueSection && !UniqueSectionNames); 303 } 304 305 const MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 306 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 307 const TargetMachine &TM) const { 308 unsigned Flags = getELFSectionFlags(Kind); 309 310 // If we have -ffunction-section or -fdata-section then we should emit the 311 // global value to a uniqued section specifically for it. 312 bool EmitUniqueSection = false; 313 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 314 if (Kind.isText()) 315 EmitUniqueSection = TM.getFunctionSections(); 316 else 317 EmitUniqueSection = TM.getDataSections(); 318 } 319 EmitUniqueSection |= GV->hasComdat(); 320 321 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM, 322 EmitUniqueSection, Flags); 323 } 324 325 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 326 const Function &F, Mangler &Mang, const TargetMachine &TM) const { 327 // If the function can be removed, produce a unique section so that 328 // the table doesn't prevent the removal. 329 const Comdat *C = F.getComdat(); 330 bool EmitUniqueSection = TM.getFunctionSections() || C; 331 if (!EmitUniqueSection) 332 return ReadOnlySection; 333 334 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 335 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC); 336 } 337 338 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 339 bool UsesLabelDifference, const Function &F) const { 340 // We can always create relative relocations, so use another section 341 // that can be marked non-executable. 342 return false; 343 } 344 345 /// getSectionForConstant - Given a mergeable constant with the 346 /// specified size and relocation information, return a section that it 347 /// should be placed in. 348 const MCSection * 349 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind, 350 const Constant *C) const { 351 if (Kind.isMergeableConst4() && MergeableConst4Section) 352 return MergeableConst4Section; 353 if (Kind.isMergeableConst8() && MergeableConst8Section) 354 return MergeableConst8Section; 355 if (Kind.isMergeableConst16() && MergeableConst16Section) 356 return MergeableConst16Section; 357 if (Kind.isReadOnly()) 358 return ReadOnlySection; 359 360 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 361 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 362 return DataRelROSection; 363 } 364 365 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx, 366 bool UseInitArray, 367 bool IsCtor, 368 unsigned Priority, 369 const MCSymbol *KeySym) { 370 std::string Name; 371 unsigned Type; 372 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 373 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 374 375 if (KeySym) 376 Flags |= ELF::SHF_GROUP; 377 378 if (UseInitArray) { 379 if (IsCtor) { 380 Type = ELF::SHT_INIT_ARRAY; 381 Name = ".init_array"; 382 } else { 383 Type = ELF::SHT_FINI_ARRAY; 384 Name = ".fini_array"; 385 } 386 if (Priority != 65535) { 387 Name += '.'; 388 Name += utostr(Priority); 389 } 390 } else { 391 // The default scheme is .ctor / .dtor, so we have to invert the priority 392 // numbering. 393 if (IsCtor) 394 Name = ".ctors"; 395 else 396 Name = ".dtors"; 397 if (Priority != 65535) { 398 Name += '.'; 399 Name += utostr(65535 - Priority); 400 } 401 Type = ELF::SHT_PROGBITS; 402 } 403 404 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 405 } 406 407 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 408 unsigned Priority, const MCSymbol *KeySym) const { 409 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 410 KeySym); 411 } 412 413 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 414 unsigned Priority, const MCSymbol *KeySym) const { 415 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 416 KeySym); 417 } 418 419 void 420 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 421 UseInitArray = UseInitArray_; 422 if (!UseInitArray) 423 return; 424 425 StaticCtorSection = getContext().getELFSection( 426 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); 427 StaticDtorSection = getContext().getELFSection( 428 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // MachO 433 //===----------------------------------------------------------------------===// 434 435 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 436 : TargetLoweringObjectFile() { 437 SupportIndirectSymViaGOTPCRel = true; 438 } 439 440 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker 441 /// option string. Returns StringRef() if the option does not specify a library. 442 StringRef TargetLoweringObjectFileMachO:: 443 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 444 const char *LibCmd = "-l"; 445 if (LinkerOption.startswith(LibCmd)) 446 return LinkerOption.substr(strlen(LibCmd)); 447 return StringRef(); 448 } 449 450 /// emitModuleFlags - Perform code emission for module flags. 451 void TargetLoweringObjectFileMachO:: 452 emitModuleFlags(MCStreamer &Streamer, 453 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 454 Mangler &Mang, const TargetMachine &TM) const { 455 unsigned VersionVal = 0; 456 unsigned ImageInfoFlags = 0; 457 MDNode *LinkerOptions = nullptr; 458 StringRef SectionVal; 459 460 for (ArrayRef<Module::ModuleFlagEntry>::iterator 461 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 462 const Module::ModuleFlagEntry &MFE = *i; 463 464 // Ignore flags with 'Require' behavior. 465 if (MFE.Behavior == Module::Require) 466 continue; 467 468 StringRef Key = MFE.Key->getString(); 469 Metadata *Val = MFE.Val; 470 471 if (Key == "Objective-C Image Info Version") { 472 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue(); 473 } else if (Key == "Objective-C Garbage Collection" || 474 Key == "Objective-C GC Only" || 475 Key == "Objective-C Is Simulated" || 476 Key == "Objective-C Image Swift Version") { 477 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue(); 478 } else if (Key == "Objective-C Image Info Section") { 479 SectionVal = cast<MDString>(Val)->getString(); 480 } else if (Key == "Linker Options") { 481 LinkerOptions = cast<MDNode>(Val); 482 } 483 } 484 485 // Emit the linker options if present. 486 if (LinkerOptions) { 487 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 488 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 489 SmallVector<std::string, 4> StrOptions; 490 491 // Convert to strings. 492 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 493 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 494 StrOptions.push_back(MDOption->getString()); 495 } 496 497 Streamer.EmitLinkerOptions(StrOptions); 498 } 499 } 500 501 // The section is mandatory. If we don't have it, then we don't have GC info. 502 if (SectionVal.empty()) return; 503 504 StringRef Segment, Section; 505 unsigned TAA = 0, StubSize = 0; 506 bool TAAParsed; 507 std::string ErrorCode = 508 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 509 TAA, TAAParsed, StubSize); 510 if (!ErrorCode.empty()) 511 // If invalid, report the error with report_fatal_error. 512 report_fatal_error("Invalid section specifier '" + Section + "': " + 513 ErrorCode + "."); 514 515 // Get the section. 516 const MCSectionMachO *S = 517 getContext().getMachOSection(Segment, Section, TAA, StubSize, 518 SectionKind::getDataNoRel()); 519 Streamer.SwitchSection(S); 520 Streamer.EmitLabel(getContext(). 521 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 522 Streamer.EmitIntValue(VersionVal, 4); 523 Streamer.EmitIntValue(ImageInfoFlags, 4); 524 Streamer.AddBlankLine(); 525 } 526 527 static void checkMachOComdat(const GlobalValue *GV) { 528 const Comdat *C = GV->getComdat(); 529 if (!C) 530 return; 531 532 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 533 "' cannot be lowered."); 534 } 535 536 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 537 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 538 const TargetMachine &TM) const { 539 // Parse the section specifier and create it if valid. 540 StringRef Segment, Section; 541 unsigned TAA = 0, StubSize = 0; 542 bool TAAParsed; 543 544 checkMachOComdat(GV); 545 546 std::string ErrorCode = 547 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 548 TAA, TAAParsed, StubSize); 549 if (!ErrorCode.empty()) { 550 // If invalid, report the error with report_fatal_error. 551 report_fatal_error("Global variable '" + GV->getName() + 552 "' has an invalid section specifier '" + 553 GV->getSection() + "': " + ErrorCode + "."); 554 } 555 556 // Get the section. 557 const MCSectionMachO *S = 558 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 559 560 // If TAA wasn't set by ParseSectionSpecifier() above, 561 // use the value returned by getMachOSection() as a default. 562 if (!TAAParsed) 563 TAA = S->getTypeAndAttributes(); 564 565 // Okay, now that we got the section, verify that the TAA & StubSize agree. 566 // If the user declared multiple globals with different section flags, we need 567 // to reject it here. 568 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 569 // If invalid, report the error with report_fatal_error. 570 report_fatal_error("Global variable '" + GV->getName() + 571 "' section type or attributes does not match previous" 572 " section specifier"); 573 } 574 575 return S; 576 } 577 578 const MCSection *TargetLoweringObjectFileMachO:: 579 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 580 Mangler &Mang, const TargetMachine &TM) const { 581 checkMachOComdat(GV); 582 583 // Handle thread local data. 584 if (Kind.isThreadBSS()) return TLSBSSSection; 585 if (Kind.isThreadData()) return TLSDataSection; 586 587 if (Kind.isText()) 588 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 589 590 // If this is weak/linkonce, put this in a coalescable section, either in text 591 // or data depending on if it is writable. 592 if (GV->isWeakForLinker()) { 593 if (Kind.isReadOnly()) 594 return ConstTextCoalSection; 595 return DataCoalSection; 596 } 597 598 // FIXME: Alignment check should be handled by section classifier. 599 if (Kind.isMergeable1ByteCString() && 600 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 601 return CStringSection; 602 603 // Do not put 16-bit arrays in the UString section if they have an 604 // externally visible label, this runs into issues with certain linker 605 // versions. 606 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() && 607 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 608 return UStringSection; 609 610 // With MachO only variables whose corresponding symbol starts with 'l' or 611 // 'L' can be merged, so we only try merging GVs with private linkage. 612 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) { 613 if (Kind.isMergeableConst4()) 614 return FourByteConstantSection; 615 if (Kind.isMergeableConst8()) 616 return EightByteConstantSection; 617 if (Kind.isMergeableConst16()) 618 return SixteenByteConstantSection; 619 } 620 621 // Otherwise, if it is readonly, but not something we can specially optimize, 622 // just drop it in .const. 623 if (Kind.isReadOnly()) 624 return ReadOnlySection; 625 626 // If this is marked const, put it into a const section. But if the dynamic 627 // linker needs to write to it, put it in the data segment. 628 if (Kind.isReadOnlyWithRel()) 629 return ConstDataSection; 630 631 // Put zero initialized globals with strong external linkage in the 632 // DATA, __common section with the .zerofill directive. 633 if (Kind.isBSSExtern()) 634 return DataCommonSection; 635 636 // Put zero initialized globals with local linkage in __DATA,__bss directive 637 // with the .zerofill directive (aka .lcomm). 638 if (Kind.isBSSLocal()) 639 return DataBSSSection; 640 641 // Otherwise, just drop the variable in the normal data section. 642 return DataSection; 643 } 644 645 const MCSection * 646 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind, 647 const Constant *C) const { 648 // If this constant requires a relocation, we have to put it in the data 649 // segment, not in the text segment. 650 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 651 return ConstDataSection; 652 653 if (Kind.isMergeableConst4()) 654 return FourByteConstantSection; 655 if (Kind.isMergeableConst8()) 656 return EightByteConstantSection; 657 if (Kind.isMergeableConst16()) 658 return SixteenByteConstantSection; 659 return ReadOnlySection; // .const 660 } 661 662 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 663 const GlobalValue *GV, unsigned Encoding, Mangler &Mang, 664 const TargetMachine &TM, MachineModuleInfo *MMI, 665 MCStreamer &Streamer) const { 666 // The mach-o version of this method defaults to returning a stub reference. 667 668 if (Encoding & DW_EH_PE_indirect) { 669 MachineModuleInfoMachO &MachOMMI = 670 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 671 672 MCSymbol *SSym = 673 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM); 674 675 // Add information about the stub reference to MachOMMI so that the stub 676 // gets emitted by the asmprinter. 677 MachineModuleInfoImpl::StubValueTy &StubSym = 678 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) : 679 MachOMMI.getGVStubEntry(SSym); 680 if (!StubSym.getPointer()) { 681 MCSymbol *Sym = TM.getSymbol(GV, Mang); 682 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 683 } 684 685 return TargetLoweringObjectFile:: 686 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 687 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 688 } 689 690 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang, 691 TM, MMI, Streamer); 692 } 693 694 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 695 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM, 696 MachineModuleInfo *MMI) const { 697 // The mach-o version of this method defaults to returning a stub reference. 698 MachineModuleInfoMachO &MachOMMI = 699 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 700 701 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM); 702 703 // Add information about the stub reference to MachOMMI so that the stub 704 // gets emitted by the asmprinter. 705 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 706 if (!StubSym.getPointer()) { 707 MCSymbol *Sym = TM.getSymbol(GV, Mang); 708 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 709 } 710 711 return SSym; 712 } 713 714 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 715 const MCSymbol *Sym, const MCValue &MV, int64_t Offset, 716 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 717 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation 718 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 719 // through a non_lazy_ptr stub instead. One advantage is that it allows the 720 // computation of deltas to final external symbols. Example: 721 // 722 // _extgotequiv: 723 // .long _extfoo 724 // 725 // _delta: 726 // .long _extgotequiv-_delta 727 // 728 // is transformed to: 729 // 730 // _delta: 731 // .long L_extfoo$non_lazy_ptr-(_delta+0) 732 // 733 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 734 // L_extfoo$non_lazy_ptr: 735 // .indirect_symbol _extfoo 736 // .long 0 737 // 738 MachineModuleInfoMachO &MachOMMI = 739 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 740 MCContext &Ctx = getContext(); 741 742 // The offset must consider the original displacement from the base symbol 743 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 744 Offset = -MV.getConstant(); 745 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 746 747 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 748 // non_lazy_ptr stubs. 749 SmallString<128> Name; 750 StringRef Suffix = "$non_lazy_ptr"; 751 Name += DL->getPrivateGlobalPrefix(); 752 Name += Sym->getName(); 753 Name += Suffix; 754 MCSymbol *Stub = Ctx.GetOrCreateSymbol(Name); 755 756 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 757 if (!StubSym.getPointer()) 758 StubSym = MachineModuleInfoImpl:: 759 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */); 760 761 const MCExpr *BSymExpr = 762 MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 763 const MCExpr *LHS = 764 MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx); 765 766 if (!Offset) 767 return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx); 768 769 const MCExpr *RHS = 770 MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx); 771 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx); 772 } 773 774 //===----------------------------------------------------------------------===// 775 // COFF 776 //===----------------------------------------------------------------------===// 777 778 static unsigned 779 getCOFFSectionFlags(SectionKind K) { 780 unsigned Flags = 0; 781 782 if (K.isMetadata()) 783 Flags |= 784 COFF::IMAGE_SCN_MEM_DISCARDABLE; 785 else if (K.isText()) 786 Flags |= 787 COFF::IMAGE_SCN_MEM_EXECUTE | 788 COFF::IMAGE_SCN_MEM_READ | 789 COFF::IMAGE_SCN_CNT_CODE; 790 else if (K.isBSS()) 791 Flags |= 792 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 793 COFF::IMAGE_SCN_MEM_READ | 794 COFF::IMAGE_SCN_MEM_WRITE; 795 else if (K.isThreadLocal()) 796 Flags |= 797 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 798 COFF::IMAGE_SCN_MEM_READ | 799 COFF::IMAGE_SCN_MEM_WRITE; 800 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 801 Flags |= 802 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 803 COFF::IMAGE_SCN_MEM_READ; 804 else if (K.isWriteable()) 805 Flags |= 806 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 807 COFF::IMAGE_SCN_MEM_READ | 808 COFF::IMAGE_SCN_MEM_WRITE; 809 810 return Flags; 811 } 812 813 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 814 const Comdat *C = GV->getComdat(); 815 assert(C && "expected GV to have a Comdat!"); 816 817 StringRef ComdatGVName = C->getName(); 818 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 819 if (!ComdatGV) 820 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 821 "' does not exist."); 822 823 if (ComdatGV->getComdat() != C) 824 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 825 "' is not a key for its COMDAT."); 826 827 return ComdatGV; 828 } 829 830 static int getSelectionForCOFF(const GlobalValue *GV) { 831 if (const Comdat *C = GV->getComdat()) { 832 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 833 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 834 ComdatKey = GA->getBaseObject(); 835 if (ComdatKey == GV) { 836 switch (C->getSelectionKind()) { 837 case Comdat::Any: 838 return COFF::IMAGE_COMDAT_SELECT_ANY; 839 case Comdat::ExactMatch: 840 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 841 case Comdat::Largest: 842 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 843 case Comdat::NoDuplicates: 844 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 845 case Comdat::SameSize: 846 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 847 } 848 } else { 849 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 850 } 851 } else if (GV->isWeakForLinker()) { 852 return COFF::IMAGE_COMDAT_SELECT_ANY; 853 } 854 return 0; 855 } 856 857 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 858 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 859 const TargetMachine &TM) const { 860 int Selection = 0; 861 unsigned Characteristics = getCOFFSectionFlags(Kind); 862 StringRef Name = GV->getSection(); 863 StringRef COMDATSymName = ""; 864 if (GV->hasComdat()) { 865 Selection = getSelectionForCOFF(GV); 866 const GlobalValue *ComdatGV; 867 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 868 ComdatGV = getComdatGVForCOFF(GV); 869 else 870 ComdatGV = GV; 871 872 if (!ComdatGV->hasPrivateLinkage()) { 873 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 874 COMDATSymName = Sym->getName(); 875 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 876 } else { 877 Selection = 0; 878 } 879 } 880 return getContext().getCOFFSection(Name, 881 Characteristics, 882 Kind, 883 COMDATSymName, 884 Selection); 885 } 886 887 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 888 if (Kind.isText()) 889 return ".text"; 890 if (Kind.isBSS()) 891 return ".bss"; 892 if (Kind.isThreadLocal()) 893 return ".tls$"; 894 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 895 return ".rdata"; 896 return ".data"; 897 } 898 899 900 const MCSection *TargetLoweringObjectFileCOFF:: 901 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 902 Mangler &Mang, const TargetMachine &TM) const { 903 // If we have -ffunction-sections then we should emit the global value to a 904 // uniqued section specifically for it. 905 bool EmitUniquedSection; 906 if (Kind.isText()) 907 EmitUniquedSection = TM.getFunctionSections(); 908 else 909 EmitUniquedSection = TM.getDataSections(); 910 911 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) { 912 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 913 unsigned Characteristics = getCOFFSectionFlags(Kind); 914 915 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 916 int Selection = getSelectionForCOFF(GV); 917 if (!Selection) 918 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 919 const GlobalValue *ComdatGV; 920 if (GV->hasComdat()) 921 ComdatGV = getComdatGVForCOFF(GV); 922 else 923 ComdatGV = GV; 924 925 if (!ComdatGV->hasPrivateLinkage()) { 926 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 927 StringRef COMDATSymName = Sym->getName(); 928 return getContext().getCOFFSection(Name, Characteristics, Kind, 929 COMDATSymName, Selection); 930 } else { 931 SmallString<256> TmpData; 932 getNameWithPrefix(TmpData, GV, true, Mang, TM); 933 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 934 Selection); 935 } 936 } 937 938 if (Kind.isText()) 939 return TextSection; 940 941 if (Kind.isThreadLocal()) 942 return TLSDataSection; 943 944 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 945 return ReadOnlySection; 946 947 // Note: we claim that common symbols are put in BSSSection, but they are 948 // really emitted with the magic .comm directive, which creates a symbol table 949 // entry but not a section. 950 if (Kind.isBSS() || Kind.isCommon()) 951 return BSSSection; 952 953 return DataSection; 954 } 955 956 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 957 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 958 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const { 959 if (GV->hasPrivateLinkage() && 960 ((isa<Function>(GV) && TM.getFunctionSections()) || 961 (isa<GlobalVariable>(GV) && TM.getDataSections()))) { 962 SmallString<256> Tmp; 963 Mang.getNameWithPrefix(Tmp, GV, /*CannotUsePrivateLabel=*/false); 964 if (Tmp.startswith(".L")) 965 OutName.append(Tmp.begin() + 2, Tmp.end()); 966 else if (Tmp.startswith("L")) 967 OutName.append(Tmp.begin() + 1, Tmp.end()); 968 else 969 OutName.append(Tmp.begin(), Tmp.end()); 970 return; 971 } 972 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 973 } 974 975 const MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 976 const Function &F, Mangler &Mang, const TargetMachine &TM) const { 977 // If the function can be removed, produce a unique section so that 978 // the table doesn't prevent the removal. 979 const Comdat *C = F.getComdat(); 980 bool EmitUniqueSection = TM.getFunctionSections() || C; 981 if (!EmitUniqueSection) 982 return ReadOnlySection; 983 984 // FIXME: we should produce a symbol for F instead. 985 if (F.hasPrivateLinkage()) 986 return ReadOnlySection; 987 988 MCSymbol *Sym = TM.getSymbol(&F, Mang); 989 StringRef COMDATSymName = Sym->getName(); 990 991 SectionKind Kind = SectionKind::getReadOnly(); 992 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 993 unsigned Characteristics = getCOFFSectionFlags(Kind); 994 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 995 996 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 997 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE); 998 } 999 1000 StringRef TargetLoweringObjectFileCOFF:: 1001 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 1002 const char *LibCmd = "/DEFAULTLIB:"; 1003 if (LinkerOption.startswith(LibCmd)) 1004 return LinkerOption.substr(strlen(LibCmd)); 1005 return StringRef(); 1006 } 1007 1008 void TargetLoweringObjectFileCOFF:: 1009 emitModuleFlags(MCStreamer &Streamer, 1010 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 1011 Mangler &Mang, const TargetMachine &TM) const { 1012 MDNode *LinkerOptions = nullptr; 1013 1014 // Look for the "Linker Options" flag, since it's the only one we support. 1015 for (ArrayRef<Module::ModuleFlagEntry>::iterator 1016 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 1017 const Module::ModuleFlagEntry &MFE = *i; 1018 StringRef Key = MFE.Key->getString(); 1019 Metadata *Val = MFE.Val; 1020 if (Key == "Linker Options") { 1021 LinkerOptions = cast<MDNode>(Val); 1022 break; 1023 } 1024 } 1025 if (!LinkerOptions) 1026 return; 1027 1028 // Emit the linker options to the linker .drectve section. According to the 1029 // spec, this section is a space-separated string containing flags for linker. 1030 const MCSection *Sec = getDrectveSection(); 1031 Streamer.SwitchSection(Sec); 1032 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 1033 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 1034 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 1035 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 1036 // Lead with a space for consistency with our dllexport implementation. 1037 std::string Directive(" "); 1038 Directive.append(MDOption->getString()); 1039 Streamer.EmitBytes(Directive); 1040 } 1041 } 1042 } 1043 1044 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1045 unsigned Priority, const MCSymbol *KeySym) const { 1046 return getContext().getAssociativeCOFFSection( 1047 cast<MCSectionCOFF>(StaticCtorSection), KeySym); 1048 } 1049 1050 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1051 unsigned Priority, const MCSymbol *KeySym) const { 1052 return getContext().getAssociativeCOFFSection( 1053 cast<MCSectionCOFF>(StaticDtorSection), KeySym); 1054 } 1055