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