1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
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/TargetMachine.h"
40 using namespace dwarf;
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
47 TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV,
49 MachineModuleInfo *MMI) const {
50 unsigned Encoding = getPersonalityEncoding();
51 switch (Encoding & 0x70) {
53 report_fatal_error("We do not support this DWARF encoding yet!");
54 case dwarf::DW_EH_PE_absptr:
55 return getSymbol(GV, Mang);
56 case dwarf::DW_EH_PE_pcrel: {
57 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
58 getSymbol(GV, Mang)->getName());
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,
77 SectionKind::getDataRel(),
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);
87 Streamer.EmitSymbolValue(Sym, Size);
90 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
91 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
92 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
94 if (Encoding & dwarf::DW_EH_PE_indirect) {
95 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
97 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang);
99 // Add information about the stub reference to ELFMMI so that the stub
100 // gets emitted by the asmprinter.
101 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
102 if (StubSym.getPointer() == 0) {
103 MCSymbol *Sym = getSymbol(GV, Mang);
104 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
107 return TargetLoweringObjectFile::
108 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
109 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
112 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
117 getELFKindForNamedSection(StringRef Name, SectionKind K) {
118 // N.B.: The defaults used in here are no the same ones used in MC.
119 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
120 // both gas and MC will produce a section with no flags. Given
121 // section(".eh_frame") gcc will produce:
123 // .section .eh_frame,"a",@progbits
124 if (Name.empty() || Name[0] != '.') return K;
126 // Some lame default implementation based on some magic section names.
127 if (Name == ".bss" ||
128 Name.startswith(".bss.") ||
129 Name.startswith(".gnu.linkonce.b.") ||
130 Name.startswith(".llvm.linkonce.b.") ||
132 Name.startswith(".sbss.") ||
133 Name.startswith(".gnu.linkonce.sb.") ||
134 Name.startswith(".llvm.linkonce.sb."))
135 return SectionKind::getBSS();
137 if (Name == ".tdata" ||
138 Name.startswith(".tdata.") ||
139 Name.startswith(".gnu.linkonce.td.") ||
140 Name.startswith(".llvm.linkonce.td."))
141 return SectionKind::getThreadData();
143 if (Name == ".tbss" ||
144 Name.startswith(".tbss.") ||
145 Name.startswith(".gnu.linkonce.tb.") ||
146 Name.startswith(".llvm.linkonce.tb."))
147 return SectionKind::getThreadBSS();
153 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
155 if (Name == ".init_array")
156 return ELF::SHT_INIT_ARRAY;
158 if (Name == ".fini_array")
159 return ELF::SHT_FINI_ARRAY;
161 if (Name == ".preinit_array")
162 return ELF::SHT_PREINIT_ARRAY;
164 if (K.isBSS() || K.isThreadBSS())
165 return ELF::SHT_NOBITS;
167 return ELF::SHT_PROGBITS;
172 getELFSectionFlags(SectionKind K) {
176 Flags |= ELF::SHF_ALLOC;
179 Flags |= ELF::SHF_EXECINSTR;
182 Flags |= ELF::SHF_WRITE;
184 if (K.isThreadLocal())
185 Flags |= ELF::SHF_TLS;
187 // K.isMergeableConst() is left out to honour PR4650
188 if (K.isMergeableCString() || K.isMergeableConst4() ||
189 K.isMergeableConst8() || K.isMergeableConst16())
190 Flags |= ELF::SHF_MERGE;
192 if (K.isMergeableCString())
193 Flags |= ELF::SHF_STRINGS;
199 const MCSection *TargetLoweringObjectFileELF::
200 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
201 Mangler &Mang, const TargetMachine &TM) const {
202 StringRef SectionName = GV->getSection();
204 // Infer section flags from the section name if we can.
205 Kind = getELFKindForNamedSection(SectionName, Kind);
207 return getContext().getELFSection(SectionName,
208 getELFSectionType(SectionName, Kind),
209 getELFSectionFlags(Kind), Kind);
212 /// getSectionPrefixForGlobal - Return the section prefix name used by options
213 /// FunctionsSections and DataSections.
214 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
215 if (Kind.isText()) return ".text.";
216 if (Kind.isReadOnly()) return ".rodata.";
217 if (Kind.isBSS()) return ".bss.";
219 if (Kind.isThreadData()) return ".tdata.";
220 if (Kind.isThreadBSS()) return ".tbss.";
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.";
227 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
228 return ".data.rel.ro.";
232 const MCSection *TargetLoweringObjectFileELF::
233 SelectSectionForGlobal(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;
239 EmitUniquedSection = TM.getFunctionSections();
241 EmitUniquedSection = TM.getDataSections();
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) &&
248 Prefix = getSectionPrefixForGlobal(Kind);
250 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
251 MCSymbol *Sym = getSymbol(GV, Mang);
252 Name.append(Sym->getName().begin(), Sym->getName().end());
253 StringRef Group = "";
254 unsigned Flags = getELFSectionFlags(Kind);
255 if (GV->isWeakForLinker()) {
256 Group = Sym->getName();
257 Flags |= ELF::SHF_GROUP;
260 return getContext().getELFSection(Name.str(),
261 getELFSectionType(Name.str(), Kind),
262 Flags, Kind, 0, Group);
265 if (Kind.isText()) return TextSection;
267 if (Kind.isMergeable1ByteCString() ||
268 Kind.isMergeable2ByteCString() ||
269 Kind.isMergeable4ByteCString()) {
271 // We also need alignment here.
272 // FIXME: this is getting the alignment of the character, not the
273 // alignment of the global!
275 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
277 const char *SizeSpec = ".rodata.str1.";
278 if (Kind.isMergeable2ByteCString())
279 SizeSpec = ".rodata.str2.";
280 else if (Kind.isMergeable4ByteCString())
281 SizeSpec = ".rodata.str4.";
283 assert(Kind.isMergeable1ByteCString() && "unknown string width");
286 std::string Name = SizeSpec + utostr(Align);
287 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
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
304 if (Kind.isReadOnly()) return ReadOnlySection;
306 if (Kind.isThreadData()) return TLSDataSection;
307 if (Kind.isThreadBSS()) return TLSBSSSection;
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;
314 if (Kind.isDataNoRel()) return DataSection;
315 if (Kind.isDataRelLocal()) return DataRelLocalSection;
316 if (Kind.isDataRel()) return DataRelSection;
317 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
319 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
320 return DataRelROSection;
323 /// getSectionForConstant - Given a mergeable constant with the
324 /// specified size and relocation information, return a section that it
325 /// should be placed in.
326 const MCSection *TargetLoweringObjectFileELF::
327 getSectionForConstant(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;
337 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
338 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
339 return DataRelROSection;
343 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
344 // The default scheme is .ctor / .dtor, so we have to invert the priority
346 if (Priority == 65535)
347 return StaticCtorSection;
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());
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());
363 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
364 // The default scheme is .ctor / .dtor, so we have to invert the priority
366 if (Priority == 65535)
367 return StaticDtorSection;
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());
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());
383 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
384 UseInitArray = UseInitArray_;
389 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
392 SectionKind::getDataRel());
394 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
397 SectionKind::getDataRel());
400 //===----------------------------------------------------------------------===//
402 //===----------------------------------------------------------------------===//
404 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
405 /// option string. Returns StringRef() if the option does not specify a library.
406 StringRef TargetLoweringObjectFileMachO::
407 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
408 const char *LibCmd = "-l";
409 if (LinkerOption.startswith(LibCmd))
410 return LinkerOption.substr(strlen(LibCmd));
414 /// emitModuleFlags - Perform code emission for module flags.
415 void TargetLoweringObjectFileMachO::
416 emitModuleFlags(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;
424 for (ArrayRef<Module::ModuleFlagEntry>::iterator
425 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
426 const Module::ModuleFlagEntry &MFE = *i;
428 // Ignore flags with 'Require' behavior.
429 if (MFE.Behavior == Module::Require)
432 StringRef Key = MFE.Key->getString();
433 Value *Val = MFE.Val;
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);
448 // Emit the linker options if present.
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;
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());
460 Streamer.EmitLinkerOptions(StrOptions);
464 // The section is mandatory. If we don't have it, then we don't have GC info.
465 if (SectionVal.empty()) return;
467 StringRef Segment, Section;
468 unsigned TAA = 0, StubSize = 0;
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 + "': " +
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();
490 const MCSection *TargetLoweringObjectFileMachO::
491 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
492 Mangler &Mang, const TargetMachine &TM) const {
493 // Parse the section specifier and create it if valid.
494 StringRef Segment, Section;
495 unsigned TAA = 0, StubSize = 0;
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 + ".");
508 const MCSectionMachO *S =
509 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
511 // If TAA wasn't set by ParseSectionSpecifier() above,
512 // use the value returned by getMachOSection() as a default.
514 TAA = S->getTypeAndAttributes();
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");
529 const MCSection *TargetLoweringObjectFileMachO::
530 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
531 Mangler &Mang, const TargetMachine &TM) const {
533 // Handle thread local data.
534 if (Kind.isThreadBSS()) return TLSBSSSection;
535 if (Kind.isThreadData()) return TLSDataSection;
538 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
540 // If this is weak/linkonce, put this in a coalescable section, either in text
541 // or data depending on if it is writable.
542 if (GV->isWeakForLinker()) {
543 if (Kind.isReadOnly())
544 return ConstTextCoalSection;
545 return DataCoalSection;
548 // FIXME: Alignment check should be handled by section classifier.
549 if (Kind.isMergeable1ByteCString() &&
550 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
551 return CStringSection;
553 // Do not put 16-bit arrays in the UString section if they have an
554 // externally visible label, this runs into issues with certain linker
556 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
557 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
558 return UStringSection;
560 if (Kind.isMergeableConst()) {
561 if (Kind.isMergeableConst4())
562 return FourByteConstantSection;
563 if (Kind.isMergeableConst8())
564 return EightByteConstantSection;
565 if (Kind.isMergeableConst16())
566 return SixteenByteConstantSection;
569 // Otherwise, if it is readonly, but not something we can specially optimize,
570 // just drop it in .const.
571 if (Kind.isReadOnly())
572 return ReadOnlySection;
574 // If this is marked const, put it into a const section. But if the dynamic
575 // linker needs to write to it, put it in the data segment.
576 if (Kind.isReadOnlyWithRel())
577 return ConstDataSection;
579 // Put zero initialized globals with strong external linkage in the
580 // DATA, __common section with the .zerofill directive.
581 if (Kind.isBSSExtern())
582 return DataCommonSection;
584 // Put zero initialized globals with local linkage in __DATA,__bss directive
585 // with the .zerofill directive (aka .lcomm).
586 if (Kind.isBSSLocal())
587 return DataBSSSection;
589 // Otherwise, just drop the variable in the normal data section.
594 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
595 // If this constant requires a relocation, we have to put it in the data
596 // segment, not in the text segment.
597 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
598 return ConstDataSection;
600 if (Kind.isMergeableConst4())
601 return FourByteConstantSection;
602 if (Kind.isMergeableConst8())
603 return EightByteConstantSection;
604 if (Kind.isMergeableConst16())
605 return SixteenByteConstantSection;
606 return ReadOnlySection; // .const
609 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
610 /// not to emit the UsedDirective for some symbols in llvm.used.
611 // FIXME: REMOVE this (rdar://7071300)
612 bool TargetLoweringObjectFileMachO::
613 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler &Mang) const {
614 /// On Darwin, internally linked data beginning with "L" or "l" does not have
615 /// the directive emitted (this occurs in ObjC metadata).
616 if (!GV) return false;
618 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
619 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
620 // FIXME: ObjC metadata is currently emitted as internal symbols that have
621 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
622 // this horrible hack can go away.
623 MCSymbol *Sym = getSymbol(GV, Mang);
624 if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
631 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
632 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
633 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
634 // The mach-o version of this method defaults to returning a stub reference.
636 if (Encoding & DW_EH_PE_indirect) {
637 MachineModuleInfoMachO &MachOMMI =
638 MMI->getObjFileInfo<MachineModuleInfoMachO>();
640 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang);
642 // Add information about the stub reference to MachOMMI so that the stub
643 // gets emitted by the asmprinter.
644 MachineModuleInfoImpl::StubValueTy &StubSym =
645 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
646 MachOMMI.getGVStubEntry(SSym);
647 if (StubSym.getPointer() == 0) {
648 MCSymbol *Sym = getSymbol(GV, Mang);
649 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
652 return TargetLoweringObjectFile::
653 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
654 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
657 return TargetLoweringObjectFile::
658 getTTypeGlobalReference(GV, Encoding, Mang, MMI, Streamer);
661 MCSymbol *TargetLoweringObjectFileMachO::
662 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler &Mang,
663 MachineModuleInfo *MMI) const {
664 // The mach-o version of this method defaults to returning a stub reference.
665 MachineModuleInfoMachO &MachOMMI =
666 MMI->getObjFileInfo<MachineModuleInfoMachO>();
668 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang);
670 // Add information about the stub reference to MachOMMI so that the stub
671 // gets emitted by the asmprinter.
672 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
673 if (StubSym.getPointer() == 0) {
674 MCSymbol *Sym = getSymbol(GV, Mang);
675 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
681 //===----------------------------------------------------------------------===//
683 //===----------------------------------------------------------------------===//
686 getCOFFSectionFlags(SectionKind K) {
691 COFF::IMAGE_SCN_MEM_DISCARDABLE;
694 COFF::IMAGE_SCN_MEM_EXECUTE |
695 COFF::IMAGE_SCN_MEM_READ |
696 COFF::IMAGE_SCN_CNT_CODE;
699 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
700 COFF::IMAGE_SCN_MEM_READ |
701 COFF::IMAGE_SCN_MEM_WRITE;
702 else if (K.isThreadLocal())
704 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
705 COFF::IMAGE_SCN_MEM_READ |
706 COFF::IMAGE_SCN_MEM_WRITE;
707 else if (K.isReadOnly())
709 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
710 COFF::IMAGE_SCN_MEM_READ;
711 else if (K.isWriteable())
713 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
714 COFF::IMAGE_SCN_MEM_READ |
715 COFF::IMAGE_SCN_MEM_WRITE;
720 const MCSection *TargetLoweringObjectFileCOFF::
721 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
722 Mangler &Mang, const TargetMachine &TM) const {
724 unsigned Characteristics = getCOFFSectionFlags(Kind);
725 StringRef Name = GV->getSection();
726 StringRef COMDATSymName = "";
727 if (GV->isWeakForLinker()) {
728 Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
729 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
730 MCSymbol *Sym = getSymbol(GV, Mang);
731 COMDATSymName = Sym->getName();
733 return getContext().getCOFFSection(Name,
740 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
745 if (Kind.isThreadLocal())
747 if (Kind.isWriteable())
753 const MCSection *TargetLoweringObjectFileCOFF::
754 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
755 Mangler &Mang, const TargetMachine &TM) const {
757 // If this global is linkonce/weak and the target handles this by emitting it
758 // into a 'uniqued' section name, create and return the section now.
759 if (GV->isWeakForLinker()) {
760 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
761 unsigned Characteristics = getCOFFSectionFlags(Kind);
763 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
764 MCSymbol *Sym = getSymbol(GV, Mang);
765 return getContext().getCOFFSection(Name, Characteristics,
766 Kind, Sym->getName(),
767 COFF::IMAGE_COMDAT_SELECT_ANY);
773 if (Kind.isThreadLocal())
774 return TLSDataSection;
776 if (Kind.isReadOnly())
777 return ReadOnlySection;
785 StringRef TargetLoweringObjectFileCOFF::
786 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
787 const char *LibCmd = "/DEFAULTLIB:";
788 if (LinkerOption.startswith(LibCmd))
789 return LinkerOption.substr(strlen(LibCmd));
793 void TargetLoweringObjectFileCOFF::
794 emitModuleFlags(MCStreamer &Streamer,
795 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
796 Mangler &Mang, const TargetMachine &TM) const {
797 MDNode *LinkerOptions = 0;
799 // Look for the "Linker Options" flag, since it's the only one we support.
800 for (ArrayRef<Module::ModuleFlagEntry>::iterator
801 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
802 const Module::ModuleFlagEntry &MFE = *i;
803 StringRef Key = MFE.Key->getString();
804 Value *Val = MFE.Val;
805 if (Key == "Linker Options") {
806 LinkerOptions = cast<MDNode>(Val);
813 // Emit the linker options to the linker .drectve section. According to the
814 // spec, this section is a space-separated string containing flags for linker.
815 const MCSection *Sec = getDrectveSection();
816 Streamer.SwitchSection(Sec);
817 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
818 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
819 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
820 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
821 StringRef Op = MDOption->getString();
822 // Lead with a space for consistency with our dllexport implementation.
823 std::string Escaped(" ");
824 if (Op.find(" ") != StringRef::npos) {
825 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
826 // how to escape quotes, but it probably uses this algorithm:
827 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
828 // FIXME: Reuse escaping code from Support/Windows/Program.inc
829 Escaped.push_back('\"');
831 Escaped.push_back('\"');
835 Streamer.EmitBytes(Escaped);