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