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