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