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/Module.h" 26 #include "llvm/MC/MCContext.h" 27 #include "llvm/MC/MCExpr.h" 28 #include "llvm/MC/MCSectionCOFF.h" 29 #include "llvm/MC/MCSectionELF.h" 30 #include "llvm/MC/MCSectionMachO.h" 31 #include "llvm/MC/MCStreamer.h" 32 #include "llvm/MC/MCSymbol.h" 33 #include "llvm/Support/Dwarf.h" 34 #include "llvm/Support/ELF.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/Mangler.h" 38 #include "llvm/Target/TargetMachine.h" 39 using namespace llvm; 40 using namespace dwarf; 41 42 //===----------------------------------------------------------------------===// 43 // ELF 44 //===----------------------------------------------------------------------===// 45 46 MCSymbol * 47 TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV, 48 Mangler *Mang, 49 MachineModuleInfo *MMI) const { 50 unsigned Encoding = getPersonalityEncoding(); 51 switch (Encoding & 0x70) { 52 default: 53 report_fatal_error("We do not support this DWARF encoding yet!"); 54 case dwarf::DW_EH_PE_absptr: 55 return Mang->getSymbol(GV); 56 case dwarf::DW_EH_PE_pcrel: { 57 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") + 58 Mang->getSymbol(GV)->getName()); 59 } 60 } 61 } 62 63 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer, 64 const TargetMachine &TM, 65 const MCSymbol *Sym) const { 66 SmallString<64> NameData("DW.ref."); 67 NameData += Sym->getName(); 68 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData); 69 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 70 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 71 StringRef Prefix = ".data."; 72 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end()); 73 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 74 const MCSection *Sec = getContext().getELFSection(NameData, 75 ELF::SHT_PROGBITS, 76 Flags, 77 SectionKind::getDataRel(), 78 0, Label->getName()); 79 unsigned Size = TM.getDataLayout()->getPointerSize(); 80 Streamer.SwitchSection(Sec); 81 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment()); 82 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 83 const MCExpr *E = MCConstantExpr::Create(Size, getContext()); 84 Streamer.EmitELFSize(Label, E); 85 Streamer.EmitLabel(Label); 86 87 Streamer.EmitSymbolValue(Sym, Size); 88 } 89 90 const MCExpr *TargetLoweringObjectFileELF:: 91 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, 92 MachineModuleInfo *MMI, unsigned Encoding, 93 MCStreamer &Streamer) const { 94 95 if (Encoding & dwarf::DW_EH_PE_indirect) { 96 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 97 98 SmallString<128> Name; 99 Mang->getNameWithPrefix(Name, GV, true); 100 Name += ".DW.stub"; 101 102 // Add information about the stub reference to ELFMMI so that the stub 103 // gets emitted by the asmprinter. 104 MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str()); 105 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 106 if (StubSym.getPointer() == 0) { 107 MCSymbol *Sym = Mang->getSymbol(GV); 108 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 109 } 110 111 return TargetLoweringObjectFile:: 112 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 113 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 114 } 115 116 return TargetLoweringObjectFile:: 117 getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer); 118 } 119 120 static SectionKind 121 getELFKindForNamedSection(StringRef Name, SectionKind K) { 122 // N.B.: The defaults used in here are no the same ones used in MC. 123 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 124 // both gas and MC will produce a section with no flags. Given 125 // section(".eh_frame") gcc will produce: 126 // 127 // .section .eh_frame,"a",@progbits 128 if (Name.empty() || Name[0] != '.') return K; 129 130 // Some lame default implementation based on some magic section names. 131 if (Name == ".bss" || 132 Name.startswith(".bss.") || 133 Name.startswith(".gnu.linkonce.b.") || 134 Name.startswith(".llvm.linkonce.b.") || 135 Name == ".sbss" || 136 Name.startswith(".sbss.") || 137 Name.startswith(".gnu.linkonce.sb.") || 138 Name.startswith(".llvm.linkonce.sb.")) 139 return SectionKind::getBSS(); 140 141 if (Name == ".tdata" || 142 Name.startswith(".tdata.") || 143 Name.startswith(".gnu.linkonce.td.") || 144 Name.startswith(".llvm.linkonce.td.")) 145 return SectionKind::getThreadData(); 146 147 if (Name == ".tbss" || 148 Name.startswith(".tbss.") || 149 Name.startswith(".gnu.linkonce.tb.") || 150 Name.startswith(".llvm.linkonce.tb.")) 151 return SectionKind::getThreadBSS(); 152 153 return K; 154 } 155 156 157 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 158 159 if (Name == ".init_array") 160 return ELF::SHT_INIT_ARRAY; 161 162 if (Name == ".fini_array") 163 return ELF::SHT_FINI_ARRAY; 164 165 if (Name == ".preinit_array") 166 return ELF::SHT_PREINIT_ARRAY; 167 168 if (K.isBSS() || K.isThreadBSS()) 169 return ELF::SHT_NOBITS; 170 171 return ELF::SHT_PROGBITS; 172 } 173 174 175 static unsigned 176 getELFSectionFlags(SectionKind K) { 177 unsigned Flags = 0; 178 179 if (!K.isMetadata()) 180 Flags |= ELF::SHF_ALLOC; 181 182 if (K.isText()) 183 Flags |= ELF::SHF_EXECINSTR; 184 185 if (K.isWriteable()) 186 Flags |= ELF::SHF_WRITE; 187 188 if (K.isThreadLocal()) 189 Flags |= ELF::SHF_TLS; 190 191 // K.isMergeableConst() is left out to honour PR4650 192 if (K.isMergeableCString() || K.isMergeableConst4() || 193 K.isMergeableConst8() || K.isMergeableConst16()) 194 Flags |= ELF::SHF_MERGE; 195 196 if (K.isMergeableCString()) 197 Flags |= ELF::SHF_STRINGS; 198 199 return Flags; 200 } 201 202 203 const MCSection *TargetLoweringObjectFileELF:: 204 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 205 Mangler *Mang, const TargetMachine &TM) const { 206 StringRef SectionName = GV->getSection(); 207 208 // Infer section flags from the section name if we can. 209 Kind = getELFKindForNamedSection(SectionName, Kind); 210 211 return getContext().getELFSection(SectionName, 212 getELFSectionType(SectionName, Kind), 213 getELFSectionFlags(Kind), Kind); 214 } 215 216 /// getSectionPrefixForGlobal - Return the section prefix name used by options 217 /// FunctionsSections and DataSections. 218 static const char *getSectionPrefixForGlobal(SectionKind Kind) { 219 if (Kind.isText()) return ".text."; 220 if (Kind.isReadOnly()) return ".rodata."; 221 if (Kind.isBSS()) return ".bss."; 222 223 if (Kind.isThreadData()) return ".tdata."; 224 if (Kind.isThreadBSS()) return ".tbss."; 225 226 if (Kind.isDataNoRel()) return ".data."; 227 if (Kind.isDataRelLocal()) return ".data.rel.local."; 228 if (Kind.isDataRel()) return ".data.rel."; 229 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local."; 230 231 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 232 return ".data.rel.ro."; 233 } 234 235 236 const MCSection *TargetLoweringObjectFileELF:: 237 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 238 Mangler *Mang, const TargetMachine &TM) const { 239 // If we have -ffunction-section or -fdata-section then we should emit the 240 // global value to a uniqued section specifically for it. 241 bool EmitUniquedSection; 242 if (Kind.isText()) 243 EmitUniquedSection = TM.getFunctionSections(); 244 else 245 EmitUniquedSection = TM.getDataSections(); 246 247 // If this global is linkonce/weak and the target handles this by emitting it 248 // into a 'uniqued' section name, create and return the section now. 249 if ((GV->isWeakForLinker() || EmitUniquedSection) && 250 !Kind.isCommon()) { 251 const char *Prefix; 252 Prefix = getSectionPrefixForGlobal(Kind); 253 254 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 255 MCSymbol *Sym = Mang->getSymbol(GV); 256 Name.append(Sym->getName().begin(), Sym->getName().end()); 257 StringRef Group = ""; 258 unsigned Flags = getELFSectionFlags(Kind); 259 if (GV->isWeakForLinker()) { 260 Group = Sym->getName(); 261 Flags |= ELF::SHF_GROUP; 262 } 263 264 return getContext().getELFSection(Name.str(), 265 getELFSectionType(Name.str(), Kind), 266 Flags, Kind, 0, Group); 267 } 268 269 if (Kind.isText()) return TextSection; 270 271 if (Kind.isMergeable1ByteCString() || 272 Kind.isMergeable2ByteCString() || 273 Kind.isMergeable4ByteCString()) { 274 275 // We also need alignment here. 276 // FIXME: this is getting the alignment of the character, not the 277 // alignment of the global! 278 unsigned Align = 279 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)); 280 281 const char *SizeSpec = ".rodata.str1."; 282 if (Kind.isMergeable2ByteCString()) 283 SizeSpec = ".rodata.str2."; 284 else if (Kind.isMergeable4ByteCString()) 285 SizeSpec = ".rodata.str4."; 286 else 287 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 288 289 290 std::string Name = SizeSpec + utostr(Align); 291 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 292 ELF::SHF_ALLOC | 293 ELF::SHF_MERGE | 294 ELF::SHF_STRINGS, 295 Kind); 296 } 297 298 if (Kind.isMergeableConst()) { 299 if (Kind.isMergeableConst4() && MergeableConst4Section) 300 return MergeableConst4Section; 301 if (Kind.isMergeableConst8() && MergeableConst8Section) 302 return MergeableConst8Section; 303 if (Kind.isMergeableConst16() && MergeableConst16Section) 304 return MergeableConst16Section; 305 return ReadOnlySection; // .const 306 } 307 308 if (Kind.isReadOnly()) return ReadOnlySection; 309 310 if (Kind.isThreadData()) return TLSDataSection; 311 if (Kind.isThreadBSS()) return TLSBSSSection; 312 313 // Note: we claim that common symbols are put in BSSSection, but they are 314 // really emitted with the magic .comm directive, which creates a symbol table 315 // entry but not a section. 316 if (Kind.isBSS() || Kind.isCommon()) return BSSSection; 317 318 if (Kind.isDataNoRel()) return DataSection; 319 if (Kind.isDataRelLocal()) return DataRelLocalSection; 320 if (Kind.isDataRel()) return DataRelSection; 321 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 322 323 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 324 return DataRelROSection; 325 } 326 327 /// getSectionForConstant - Given a mergeable constant with the 328 /// specified size and relocation information, return a section that it 329 /// should be placed in. 330 const MCSection *TargetLoweringObjectFileELF:: 331 getSectionForConstant(SectionKind Kind) const { 332 if (Kind.isMergeableConst4() && MergeableConst4Section) 333 return MergeableConst4Section; 334 if (Kind.isMergeableConst8() && MergeableConst8Section) 335 return MergeableConst8Section; 336 if (Kind.isMergeableConst16() && MergeableConst16Section) 337 return MergeableConst16Section; 338 if (Kind.isReadOnly()) 339 return ReadOnlySection; 340 341 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 342 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 343 return DataRelROSection; 344 } 345 346 const MCSection * 347 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const { 348 // The default scheme is .ctor / .dtor, so we have to invert the priority 349 // numbering. 350 if (Priority == 65535) 351 return StaticCtorSection; 352 353 if (UseInitArray) { 354 std::string Name = std::string(".init_array.") + utostr(Priority); 355 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY, 356 ELF::SHF_ALLOC | ELF::SHF_WRITE, 357 SectionKind::getDataRel()); 358 } else { 359 std::string Name = std::string(".ctors.") + utostr(65535 - Priority); 360 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 361 ELF::SHF_ALLOC |ELF::SHF_WRITE, 362 SectionKind::getDataRel()); 363 } 364 } 365 366 const MCSection * 367 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const { 368 // The default scheme is .ctor / .dtor, so we have to invert the priority 369 // numbering. 370 if (Priority == 65535) 371 return StaticDtorSection; 372 373 if (UseInitArray) { 374 std::string Name = std::string(".fini_array.") + utostr(Priority); 375 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY, 376 ELF::SHF_ALLOC | ELF::SHF_WRITE, 377 SectionKind::getDataRel()); 378 } else { 379 std::string Name = std::string(".dtors.") + utostr(65535 - Priority); 380 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 381 ELF::SHF_ALLOC |ELF::SHF_WRITE, 382 SectionKind::getDataRel()); 383 } 384 } 385 386 void 387 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 388 UseInitArray = UseInitArray_; 389 if (!UseInitArray) 390 return; 391 392 StaticCtorSection = 393 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 394 ELF::SHF_WRITE | 395 ELF::SHF_ALLOC, 396 SectionKind::getDataRel()); 397 StaticDtorSection = 398 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 399 ELF::SHF_WRITE | 400 ELF::SHF_ALLOC, 401 SectionKind::getDataRel()); 402 } 403 404 const MCSymbolRefExpr *TargetLoweringObjectFileELF::getDebugThreadLocalSymbol(const MCSymbol *Sym) const { 405 return MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_DTPOFF, getContext()); 406 } 407 408 //===----------------------------------------------------------------------===// 409 // MachO 410 //===----------------------------------------------------------------------===// 411 412 /// emitModuleFlags - Perform code emission for module flags. 413 void TargetLoweringObjectFileMachO:: 414 emitModuleFlags(MCStreamer &Streamer, 415 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 416 Mangler *Mang, const TargetMachine &TM) const { 417 unsigned VersionVal = 0; 418 unsigned ImageInfoFlags = 0; 419 MDNode *LinkerOptions = 0; 420 StringRef SectionVal; 421 422 for (ArrayRef<Module::ModuleFlagEntry>::iterator 423 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 424 const Module::ModuleFlagEntry &MFE = *i; 425 426 // Ignore flags with 'Require' behavior. 427 if (MFE.Behavior == Module::Require) 428 continue; 429 430 StringRef Key = MFE.Key->getString(); 431 Value *Val = MFE.Val; 432 433 if (Key == "Objective-C Image Info Version") { 434 VersionVal = cast<ConstantInt>(Val)->getZExtValue(); 435 } else if (Key == "Objective-C Garbage Collection" || 436 Key == "Objective-C GC Only" || 437 Key == "Objective-C Is Simulated") { 438 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue(); 439 } else if (Key == "Objective-C Image Info Section") { 440 SectionVal = cast<MDString>(Val)->getString(); 441 } else if (Key == "Linker Options") { 442 LinkerOptions = cast<MDNode>(Val); 443 } 444 } 445 446 // Emit the linker options if present. 447 if (LinkerOptions) { 448 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 449 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 450 SmallVector<std::string, 4> StrOptions; 451 452 // Convert to strings. 453 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 454 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 455 StrOptions.push_back(MDOption->getString()); 456 } 457 458 Streamer.EmitLinkerOptions(StrOptions); 459 } 460 } 461 462 // The section is mandatory. If we don't have it, then we don't have GC info. 463 if (SectionVal.empty()) return; 464 465 StringRef Segment, Section; 466 unsigned TAA = 0, StubSize = 0; 467 bool TAAParsed; 468 std::string ErrorCode = 469 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 470 TAA, TAAParsed, StubSize); 471 if (!ErrorCode.empty()) 472 // If invalid, report the error with report_fatal_error. 473 report_fatal_error("Invalid section specifier '" + Section + "': " + 474 ErrorCode + "."); 475 476 // Get the section. 477 const MCSectionMachO *S = 478 getContext().getMachOSection(Segment, Section, TAA, StubSize, 479 SectionKind::getDataNoRel()); 480 Streamer.SwitchSection(S); 481 Streamer.EmitLabel(getContext(). 482 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 483 Streamer.EmitIntValue(VersionVal, 4); 484 Streamer.EmitIntValue(ImageInfoFlags, 4); 485 Streamer.AddBlankLine(); 486 } 487 488 const MCSection *TargetLoweringObjectFileMachO:: 489 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 490 Mangler *Mang, const TargetMachine &TM) const { 491 // Parse the section specifier and create it if valid. 492 StringRef Segment, Section; 493 unsigned TAA = 0, StubSize = 0; 494 bool TAAParsed; 495 std::string ErrorCode = 496 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 497 TAA, TAAParsed, StubSize); 498 if (!ErrorCode.empty()) { 499 // If invalid, report the error with report_fatal_error. 500 report_fatal_error("Global variable '" + GV->getName() + 501 "' has an invalid section specifier '" + 502 GV->getSection() + "': " + ErrorCode + "."); 503 } 504 505 // Get the section. 506 const MCSectionMachO *S = 507 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 508 509 // If TAA wasn't set by ParseSectionSpecifier() above, 510 // use the value returned by getMachOSection() as a default. 511 if (!TAAParsed) 512 TAA = S->getTypeAndAttributes(); 513 514 // Okay, now that we got the section, verify that the TAA & StubSize agree. 515 // If the user declared multiple globals with different section flags, we need 516 // to reject it here. 517 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 518 // If invalid, report the error with report_fatal_error. 519 report_fatal_error("Global variable '" + GV->getName() + 520 "' section type or attributes does not match previous" 521 " section specifier"); 522 } 523 524 return S; 525 } 526 527 const MCSection *TargetLoweringObjectFileMachO:: 528 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 529 Mangler *Mang, const TargetMachine &TM) const { 530 if (Kind.isText()) 531 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 532 533 // If this is weak/linkonce, put this in a coalescable section, either in text 534 // or data depending on if it is writable. 535 if (GV->isWeakForLinker()) { 536 if (Kind.isReadOnly()) 537 return ConstTextCoalSection; 538 return DataCoalSection; 539 } 540 541 // FIXME: Alignment check should be handled by section classifier. 542 if (Kind.isMergeable1ByteCString() && 543 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 544 return CStringSection; 545 546 // Do not put 16-bit arrays in the UString section if they have an 547 // externally visible label, this runs into issues with certain linker 548 // versions. 549 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() && 550 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 551 return UStringSection; 552 553 if (Kind.isMergeableConst()) { 554 if (Kind.isMergeableConst4()) 555 return FourByteConstantSection; 556 if (Kind.isMergeableConst8()) 557 return EightByteConstantSection; 558 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 559 return SixteenByteConstantSection; 560 } 561 562 // Otherwise, if it is readonly, but not something we can specially optimize, 563 // just drop it in .const. 564 if (Kind.isReadOnly()) 565 return ReadOnlySection; 566 567 // If this is marked const, put it into a const section. But if the dynamic 568 // linker needs to write to it, put it in the data segment. 569 if (Kind.isReadOnlyWithRel()) 570 return ConstDataSection; 571 572 // Put zero initialized globals with strong external linkage in the 573 // DATA, __common section with the .zerofill directive. 574 if (Kind.isBSSExtern()) 575 return DataCommonSection; 576 577 // Put zero initialized globals with local linkage in __DATA,__bss directive 578 // with the .zerofill directive (aka .lcomm). 579 if (Kind.isBSSLocal()) 580 return DataBSSSection; 581 582 // Handle thread local data. 583 if (Kind.isThreadBSS()) return TLSBSSSection; 584 if (Kind.isThreadData()) return TLSDataSection; 585 586 // Otherwise, just drop the variable in the normal data section. 587 return DataSection; 588 } 589 590 const MCSection * 591 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const { 592 // If this constant requires a relocation, we have to put it in the data 593 // segment, not in the text segment. 594 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 595 return ConstDataSection; 596 597 if (Kind.isMergeableConst4()) 598 return FourByteConstantSection; 599 if (Kind.isMergeableConst8()) 600 return EightByteConstantSection; 601 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 602 return SixteenByteConstantSection; 603 return ReadOnlySection; // .const 604 } 605 606 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide 607 /// not to emit the UsedDirective for some symbols in llvm.used. 608 // FIXME: REMOVE this (rdar://7071300) 609 bool TargetLoweringObjectFileMachO:: 610 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const { 611 /// On Darwin, internally linked data beginning with "L" or "l" does not have 612 /// the directive emitted (this occurs in ObjC metadata). 613 if (!GV) return false; 614 615 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix. 616 if (GV->hasLocalLinkage() && !isa<Function>(GV)) { 617 // FIXME: ObjC metadata is currently emitted as internal symbols that have 618 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and 619 // this horrible hack can go away. 620 MCSymbol *Sym = Mang->getSymbol(GV); 621 if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l') 622 return false; 623 } 624 625 return true; 626 } 627 628 const MCExpr *TargetLoweringObjectFileMachO:: 629 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, 630 MachineModuleInfo *MMI, unsigned Encoding, 631 MCStreamer &Streamer) const { 632 // The mach-o version of this method defaults to returning a stub reference. 633 634 if (Encoding & DW_EH_PE_indirect) { 635 MachineModuleInfoMachO &MachOMMI = 636 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 637 638 SmallString<128> Name; 639 Mang->getNameWithPrefix(Name, GV, true); 640 Name += "$non_lazy_ptr"; 641 642 // Add information about the stub reference to MachOMMI so that the stub 643 // gets emitted by the asmprinter. 644 MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str()); 645 MachineModuleInfoImpl::StubValueTy &StubSym = 646 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) : 647 MachOMMI.getGVStubEntry(SSym); 648 if (StubSym.getPointer() == 0) { 649 MCSymbol *Sym = Mang->getSymbol(GV); 650 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 651 } 652 653 return TargetLoweringObjectFile:: 654 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 655 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 656 } 657 658 return TargetLoweringObjectFile:: 659 getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer); 660 } 661 662 MCSymbol *TargetLoweringObjectFileMachO:: 663 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang, 664 MachineModuleInfo *MMI) const { 665 // The mach-o version of this method defaults to returning a stub reference. 666 MachineModuleInfoMachO &MachOMMI = 667 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 668 669 SmallString<128> Name; 670 Mang->getNameWithPrefix(Name, GV, true); 671 Name += "$non_lazy_ptr"; 672 673 // Add information about the stub reference to MachOMMI so that the stub 674 // gets emitted by the asmprinter. 675 MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str()); 676 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 677 if (StubSym.getPointer() == 0) { 678 MCSymbol *Sym = Mang->getSymbol(GV); 679 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 680 } 681 682 return SSym; 683 } 684 685 //===----------------------------------------------------------------------===// 686 // COFF 687 //===----------------------------------------------------------------------===// 688 689 static unsigned 690 getCOFFSectionFlags(SectionKind K) { 691 unsigned Flags = 0; 692 693 if (K.isMetadata()) 694 Flags |= 695 COFF::IMAGE_SCN_MEM_DISCARDABLE; 696 else if (K.isText()) 697 Flags |= 698 COFF::IMAGE_SCN_MEM_EXECUTE | 699 COFF::IMAGE_SCN_MEM_READ | 700 COFF::IMAGE_SCN_CNT_CODE; 701 else if (K.isBSS ()) 702 Flags |= 703 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 704 COFF::IMAGE_SCN_MEM_READ | 705 COFF::IMAGE_SCN_MEM_WRITE; 706 else if (K.isThreadLocal()) 707 Flags |= 708 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 709 COFF::IMAGE_SCN_MEM_READ | 710 COFF::IMAGE_SCN_MEM_WRITE; 711 else if (K.isReadOnly()) 712 Flags |= 713 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 714 COFF::IMAGE_SCN_MEM_READ; 715 else if (K.isWriteable()) 716 Flags |= 717 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 718 COFF::IMAGE_SCN_MEM_READ | 719 COFF::IMAGE_SCN_MEM_WRITE; 720 721 return Flags; 722 } 723 724 const MCSection *TargetLoweringObjectFileCOFF:: 725 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 726 Mangler *Mang, const TargetMachine &TM) const { 727 int Selection = 0; 728 unsigned Characteristics = getCOFFSectionFlags(Kind); 729 SmallString<128> Name(GV->getSection().c_str()); 730 if (GV->isWeakForLinker()) { 731 Selection = COFF::IMAGE_COMDAT_SELECT_ANY; 732 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 733 MCSymbol *Sym = Mang->getSymbol(GV); 734 Name.append("$"); 735 Name.append(Sym->getName().begin() + 1, Sym->getName().end()); 736 } 737 return getContext().getCOFFSection(Name, 738 Characteristics, 739 Selection, 740 Kind); 741 } 742 743 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) { 744 if (Kind.isText()) 745 return ".text$"; 746 if (Kind.isBSS ()) 747 return ".bss$"; 748 if (Kind.isThreadLocal()) { 749 // 'LLVM' is just an arbitary string to ensure that the section name gets 750 // sorted in between '.tls$AAA' and '.tls$ZZZ' by the linker. 751 return ".tls$LLVM"; 752 } 753 if (Kind.isWriteable()) 754 return ".data$"; 755 return ".rdata$"; 756 } 757 758 759 const MCSection *TargetLoweringObjectFileCOFF:: 760 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 761 Mangler *Mang, const TargetMachine &TM) const { 762 763 // If this global is linkonce/weak and the target handles this by emitting it 764 // into a 'uniqued' section name, create and return the section now. 765 if (GV->isWeakForLinker()) { 766 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind); 767 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 768 MCSymbol *Sym = Mang->getSymbol(GV); 769 Name.append(Sym->getName().begin() + 1, Sym->getName().end()); 770 771 unsigned Characteristics = getCOFFSectionFlags(Kind); 772 773 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 774 775 return getContext().getCOFFSection(Name.str(), Characteristics, 776 COFF::IMAGE_COMDAT_SELECT_ANY, Kind); 777 } 778 779 if (Kind.isText()) 780 return getTextSection(); 781 782 if (Kind.isThreadLocal()) 783 return getTLSDataSection(); 784 785 return getDataSection(); 786 } 787 788 void TargetLoweringObjectFileCOFF:: 789 emitModuleFlags(MCStreamer &Streamer, 790 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 791 Mangler *Mang, const TargetMachine &TM) const { 792 MDNode *LinkerOptions = 0; 793 794 // Look for the "Linker Options" flag, since it's the only one we support. 795 for (ArrayRef<Module::ModuleFlagEntry>::iterator 796 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 797 const Module::ModuleFlagEntry &MFE = *i; 798 StringRef Key = MFE.Key->getString(); 799 Value *Val = MFE.Val; 800 if (Key == "Linker Options") { 801 LinkerOptions = cast<MDNode>(Val); 802 break; 803 } 804 } 805 if (!LinkerOptions) 806 return; 807 808 // Emit the linker options to the linker .drectve section. According to the 809 // spec, this section is a space-separated string containing flags for linker. 810 const MCSection *Sec = getDrectveSection(); 811 Streamer.SwitchSection(Sec); 812 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 813 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 814 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 815 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 816 StringRef Op = MDOption->getString(); 817 // Lead with a space for consistency with our dllexport implementation. 818 std::string Escaped(" "); 819 if (Op.find(" ") != StringRef::npos) { 820 // The PE-COFF spec says args with spaces must be quoted. It doesn't say 821 // how to escape quotes, but it probably uses this algorithm: 822 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx 823 // FIXME: Reuse escaping code from Support/Windows/Program.inc 824 Escaped.push_back('\"'); 825 Escaped.append(Op); 826 Escaped.push_back('\"'); 827 } else { 828 Escaped.append(Op); 829 } 830 Streamer.EmitBytes(Escaped); 831 } 832 } 833 } 834