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