1 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/Target/TargetAsmInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
40 StaticCtorSection = 0;
41 StaticDtorSection = 0;
45 DwarfAbbrevSection = 0;
48 DwarfFrameSection = 0;
49 DwarfPubNamesSection = 0;
50 DwarfPubTypesSection = 0;
51 DwarfDebugInlineSection = 0;
54 DwarfARangesSection = 0;
55 DwarfRangesSection = 0;
56 DwarfMacroInfoSection = 0;
59 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
62 static bool isSuitableForBSS(const GlobalVariable *GV) {
63 Constant *C = GV->getInitializer();
65 // Must have zero initializer.
66 if (!C->isNullValue())
69 // Leave constant zeros in readonly constant sections, so they can be shared.
73 // If the global has an explicit section specified, don't put it in BSS.
74 if (!GV->getSection().empty())
77 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
81 // Otherwise, put it in BSS!
85 /// IsNullTerminatedString - Return true if the specified constant (which is
86 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
87 /// nul value and contains no other nuls in it.
88 static bool IsNullTerminatedString(const Constant *C) {
89 const ArrayType *ATy = cast<ArrayType>(C->getType());
91 // First check: is we have constant array of i8 terminated with zero
92 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
93 if (ATy->getNumElements() == 0) return false;
96 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
97 if (Null == 0 || Null->getZExtValue() != 0)
98 return false; // Not null terminated.
100 // Verify that the null doesn't occur anywhere else in the string.
101 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
102 // Reject constantexpr elements etc.
103 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
104 CVA->getOperand(i) == Null)
109 // Another possibility: [1 x i8] zeroinitializer
110 if (isa<ConstantAggregateZero>(C))
111 return ATy->getNumElements() == 1;
116 /// getKindForGlobal - This is a top-level target-independent classifier for
117 /// a global variable. Given an global variable and information from TM, it
118 /// classifies the global in a variety of ways that make various target
119 /// implementations simpler. The target implementation is free to ignore this
120 /// extra info of course.
121 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
122 const TargetMachine &TM){
123 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
124 "Can only be used for global definitions");
126 Reloc::Model ReloModel = TM.getRelocationModel();
128 // Early exit - functions should be always in text sections.
129 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
131 return SectionKind::getText();
133 // Handle thread-local data first.
134 if (GVar->isThreadLocal()) {
135 if (isSuitableForBSS(GVar))
136 return SectionKind::getThreadBSS();
137 return SectionKind::getThreadData();
140 // Variable can be easily put to BSS section.
141 if (isSuitableForBSS(GVar))
142 return SectionKind::getBSS();
144 Constant *C = GVar->getInitializer();
146 // If the global is marked constant, we can put it into a mergable section,
147 // a mergable string section, or general .data if it contains relocations.
148 if (GVar->isConstant()) {
149 // If the initializer for the global contains something that requires a
150 // relocation, then we may have to drop this into a wriable data section
151 // even though it is marked const.
152 switch (C->getRelocationInfo()) {
153 default: llvm_unreachable("unknown relocation info kind");
154 case Constant::NoRelocation:
155 // If initializer is a null-terminated string, put it in a "cstring"
156 // section of the right width.
157 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
158 if (const IntegerType *ITy =
159 dyn_cast<IntegerType>(ATy->getElementType())) {
160 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
161 ITy->getBitWidth() == 32) &&
162 IsNullTerminatedString(C)) {
163 if (ITy->getBitWidth() == 8)
164 return SectionKind::getMergeable1ByteCString();
165 if (ITy->getBitWidth() == 16)
166 return SectionKind::getMergeable2ByteCString();
168 assert(ITy->getBitWidth() == 32 && "Unknown width");
169 return SectionKind::getMergeable4ByteCString();
174 // Otherwise, just drop it into a mergable constant section. If we have
175 // a section for this size, use it, otherwise use the arbitrary sized
177 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
178 case 4: return SectionKind::getMergeableConst4();
179 case 8: return SectionKind::getMergeableConst8();
180 case 16: return SectionKind::getMergeableConst16();
181 default: return SectionKind::getMergeableConst();
184 case Constant::LocalRelocation:
185 // In static relocation model, the linker will resolve all addresses, so
186 // the relocation entries will actually be constants by the time the app
187 // starts up. However, we can't put this into a mergable section, because
188 // the linker doesn't take relocations into consideration when it tries to
189 // merge entries in the section.
190 if (ReloModel == Reloc::Static)
191 return SectionKind::getReadOnly();
193 // Otherwise, the dynamic linker needs to fix it up, put it in the
194 // writable data.rel.local section.
195 return SectionKind::getReadOnlyWithRelLocal();
197 case Constant::GlobalRelocations:
198 // In static relocation model, the linker will resolve all addresses, so
199 // the relocation entries will actually be constants by the time the app
200 // starts up. However, we can't put this into a mergable section, because
201 // the linker doesn't take relocations into consideration when it tries to
202 // merge entries in the section.
203 if (ReloModel == Reloc::Static)
204 return SectionKind::getReadOnly();
206 // Otherwise, the dynamic linker needs to fix it up, put it in the
207 // writable data.rel section.
208 return SectionKind::getReadOnlyWithRel();
212 // Okay, this isn't a constant. If the initializer for the global is going
213 // to require a runtime relocation by the dynamic linker, put it into a more
214 // specific section to improve startup time of the app. This coalesces these
215 // globals together onto fewer pages, improving the locality of the dynamic
217 if (ReloModel == Reloc::Static)
218 return SectionKind::getDataNoRel();
220 switch (C->getRelocationInfo()) {
221 default: llvm_unreachable("unknown relocation info kind");
222 case Constant::NoRelocation:
223 return SectionKind::getDataNoRel();
224 case Constant::LocalRelocation:
225 return SectionKind::getDataRelLocal();
226 case Constant::GlobalRelocations:
227 return SectionKind::getDataRel();
231 /// SectionForGlobal - This method computes the appropriate section to emit
232 /// the specified global variable or function definition. This should not
233 /// be passed external (or available externally) globals.
234 const MCSection *TargetLoweringObjectFile::
235 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
236 const TargetMachine &TM) const {
237 // Select section name.
238 if (GV->hasSection())
239 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
242 // Use default section depending on the 'type' of global
243 return SelectSectionForGlobal(GV, Kind, Mang, TM);
247 // Lame default implementation. Calculate the section name for global.
249 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
252 const TargetMachine &TM) const{
253 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
256 return getTextSection();
258 if (Kind.isBSS() && BSSSection != 0)
261 if (Kind.isReadOnly() && ReadOnlySection != 0)
262 return ReadOnlySection;
264 return getDataSection();
267 /// getSectionForConstant - Given a mergable constant with the
268 /// specified size and relocation information, return a section that it
269 /// should be placed in.
271 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
272 if (Kind.isReadOnly() && ReadOnlySection != 0)
273 return ReadOnlySection;
280 //===----------------------------------------------------------------------===//
282 //===----------------------------------------------------------------------===//
283 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
285 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
286 // If we have the section uniquing map, free it.
287 delete (ELFUniqueMapTy*)UniquingMap;
290 const MCSection *TargetLoweringObjectFileELF::
291 getELFSection(const char *Name, bool isDirective, SectionKind Kind) const {
292 // Create the map if it doesn't already exist.
293 if (UniquingMap == 0)
294 UniquingMap = new ELFUniqueMapTy();
295 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
297 // Do the lookup, if we have a hit, return it.
298 const MCSectionELF *&Entry = Map[Name];
299 if (Entry) return Entry;
301 return Entry = MCSectionELF::Create(Name, isDirective, Kind, getContext());
304 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
305 const TargetMachine &TM) {
306 TargetLoweringObjectFile::Initialize(Ctx, TM);
308 BSSSection = getELFSection("\t.bss", true, SectionKind::getBSS());
310 // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
311 // FIXME: Does .section .bss work everywhere??
312 // FIXME2: this should just be handle by the section printer. We should get
313 // away from syntactic view of the sections and MCSection should just be a
315 BSSSection = getELFSection("\t.bss", false, SectionKind::getBSS());
318 TextSection = getELFSection("\t.text", true, SectionKind::getText());
319 DataSection = getELFSection("\t.data", true, SectionKind::getDataRel());
321 getELFSection("\t.rodata", false, SectionKind::getReadOnly());
323 getELFSection("\t.tdata", false, SectionKind::getThreadData());
325 TLSBSSSection = getELFSection("\t.tbss", false,
326 SectionKind::getThreadBSS());
328 DataRelSection = getELFSection("\t.data.rel", false,
329 SectionKind::getDataRel());
330 DataRelLocalSection = getELFSection("\t.data.rel.local", false,
331 SectionKind::getDataRelLocal());
332 DataRelROSection = getELFSection("\t.data.rel.ro", false,
333 SectionKind::getReadOnlyWithRel());
334 DataRelROLocalSection =
335 getELFSection("\t.data.rel.ro.local", false,
336 SectionKind::getReadOnlyWithRelLocal());
338 MergeableConst4Section = getELFSection(".rodata.cst4", false,
339 SectionKind::getMergeableConst4());
340 MergeableConst8Section = getELFSection(".rodata.cst8", false,
341 SectionKind::getMergeableConst8());
342 MergeableConst16Section = getELFSection(".rodata.cst16", false,
343 SectionKind::getMergeableConst16());
346 getELFSection(".ctors", false, SectionKind::getDataRel());
348 getELFSection(".dtors", false, SectionKind::getDataRel());
350 // Exception Handling Sections.
352 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
353 // it contains relocatable pointers. In PIC mode, this is probably a big
354 // runtime hit for C++ apps. Either the contents of the LSDA need to be
355 // adjusted or this should be a data section.
357 getELFSection(".gcc_except_table", false, SectionKind::getReadOnly());
359 getELFSection(".eh_frame", false, SectionKind::getDataRel());
361 // Debug Info Sections.
363 getELFSection(".debug_abbrev", false, SectionKind::getMetadata());
365 getELFSection(".debug_info", false, SectionKind::getMetadata());
367 getELFSection(".debug_line", false, SectionKind::getMetadata());
369 getELFSection(".debug_frame", false, SectionKind::getMetadata());
370 DwarfPubNamesSection =
371 getELFSection(".debug_pubnames", false, SectionKind::getMetadata());
372 DwarfPubTypesSection =
373 getELFSection(".debug_pubtypes", false, SectionKind::getMetadata());
375 getELFSection(".debug_str", false, SectionKind::getMetadata());
377 getELFSection(".debug_loc", false, SectionKind::getMetadata());
378 DwarfARangesSection =
379 getELFSection(".debug_aranges", false, SectionKind::getMetadata());
381 getELFSection(".debug_ranges", false, SectionKind::getMetadata());
382 DwarfMacroInfoSection =
383 getELFSection(".debug_macinfo", false, SectionKind::getMetadata());
388 getELFKindForNamedSection(const char *Name, SectionKind K) {
389 if (Name[0] != '.') return K;
391 // Some lame default implementation based on some magic section names.
392 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
393 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
394 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
395 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
396 return SectionKind::getBSS();
398 if (strcmp(Name, ".tdata") == 0 ||
399 strncmp(Name, ".tdata.", 7) == 0 ||
400 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
401 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
402 return SectionKind::getThreadData();
404 if (strcmp(Name, ".tbss") == 0 ||
405 strncmp(Name, ".tbss.", 6) == 0 ||
406 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
407 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
408 return SectionKind::getThreadBSS();
413 const MCSection *TargetLoweringObjectFileELF::
414 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
415 Mangler *Mang, const TargetMachine &TM) const {
416 // Infer section flags from the section name if we can.
417 Kind = getELFKindForNamedSection(GV->getSection().c_str(), Kind);
419 return getELFSection(GV->getSection().c_str(), false, Kind);
422 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
423 if (Kind.isText()) return ".gnu.linkonce.t.";
424 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
426 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
427 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
429 if (Kind.isBSS()) return ".gnu.linkonce.b.";
430 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
431 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
432 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
433 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
435 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
436 return ".gnu.linkonce.d.rel.ro.";
439 const MCSection *TargetLoweringObjectFileELF::
440 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
441 Mangler *Mang, const TargetMachine &TM) const {
443 // If this global is linkonce/weak and the target handles this by emitting it
444 // into a 'uniqued' section name, create and return the section now.
445 if (GV->isWeakForLinker()) {
446 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
447 std::string Name = Mang->makeNameProper(GV->getNameStr());
448 return getELFSection((Prefix+Name).c_str(), false, Kind);
451 if (Kind.isText()) return TextSection;
453 if (Kind.isMergeable1ByteCString() ||
454 Kind.isMergeable2ByteCString() ||
455 Kind.isMergeable4ByteCString()) {
457 // We also need alignment here.
458 // FIXME: this is getting the alignment of the character, not the
459 // alignment of the global!
461 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
463 const char *SizeSpec = ".rodata.str1.";
464 if (Kind.isMergeable2ByteCString())
465 SizeSpec = ".rodata.str2.";
466 else if (Kind.isMergeable4ByteCString())
467 SizeSpec = ".rodata.str4.";
469 assert(Kind.isMergeable1ByteCString() && "unknown string width");
472 std::string Name = SizeSpec + utostr(Align);
473 return getELFSection(Name.c_str(), false, Kind);
476 if (Kind.isMergeableConst()) {
477 if (Kind.isMergeableConst4())
478 return MergeableConst4Section;
479 if (Kind.isMergeableConst8())
480 return MergeableConst8Section;
481 if (Kind.isMergeableConst16())
482 return MergeableConst16Section;
483 return ReadOnlySection; // .const
486 if (Kind.isReadOnly()) return ReadOnlySection;
488 if (Kind.isThreadData()) return TLSDataSection;
489 if (Kind.isThreadBSS()) return TLSBSSSection;
491 if (Kind.isBSS()) return BSSSection;
493 if (Kind.isDataNoRel()) return DataSection;
494 if (Kind.isDataRelLocal()) return DataRelLocalSection;
495 if (Kind.isDataRel()) return DataRelSection;
496 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
498 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
499 return DataRelROSection;
502 /// getSectionForConstant - Given a mergeable constant with the
503 /// specified size and relocation information, return a section that it
504 /// should be placed in.
505 const MCSection *TargetLoweringObjectFileELF::
506 getSectionForConstant(SectionKind Kind) const {
507 if (Kind.isMergeableConst4())
508 return MergeableConst4Section;
509 if (Kind.isMergeableConst8())
510 return MergeableConst8Section;
511 if (Kind.isMergeableConst16())
512 return MergeableConst16Section;
513 if (Kind.isReadOnly())
514 return ReadOnlySection;
516 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
517 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
518 return DataRelROSection;
521 //===----------------------------------------------------------------------===//
523 //===----------------------------------------------------------------------===//
525 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
527 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
528 // If we have the MachO uniquing map, free it.
529 delete (MachOUniqueMapTy*)UniquingMap;
533 const MCSectionMachO *TargetLoweringObjectFileMachO::
534 getMachOSection(const StringRef &Segment, const StringRef &Section,
535 unsigned TypeAndAttributes,
536 unsigned Reserved2, SectionKind Kind) const {
537 // We unique sections by their segment/section pair. The returned section
538 // may not have the same flags as the requested section, if so this should be
539 // diagnosed by the client as an error.
541 // Create the map if it doesn't already exist.
542 if (UniquingMap == 0)
543 UniquingMap = new MachOUniqueMapTy();
544 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
546 // Form the name to look up.
547 SmallString<64> Name;
548 Name.append(Segment.begin(), Segment.end());
550 Name.append(Section.begin(), Section.end());
552 // Do the lookup, if we have a hit, return it.
553 const MCSectionMachO *&Entry = Map[StringRef(Name.data(), Name.size())];
554 if (Entry) return Entry;
556 // Otherwise, return a new section.
557 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
558 Reserved2, Kind, getContext());
562 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
563 const TargetMachine &TM) {
564 TargetLoweringObjectFile::Initialize(Ctx, TM);
567 = getMachOSection("__TEXT", "__text",
568 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
569 SectionKind::getText());
571 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
573 CStringSection // .cstring
574 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
575 SectionKind::getMergeable1ByteCString());
577 = getMachOSection("__TEXT","__ustring", 0,
578 SectionKind::getMergeable2ByteCString());
579 FourByteConstantSection // .literal4
580 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
581 SectionKind::getMergeableConst4());
582 EightByteConstantSection // .literal8
583 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
584 SectionKind::getMergeableConst8());
586 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
587 // to using it in -static mode.
588 SixteenByteConstantSection = 0;
589 if (TM.getRelocationModel() != Reloc::Static &&
590 TM.getTargetData()->getPointerSize() == 32)
591 SixteenByteConstantSection = // .literal16
592 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
593 SectionKind::getMergeableConst16());
595 ReadOnlySection // .const
596 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
599 = getMachOSection("__TEXT", "__textcoal_nt",
600 MCSectionMachO::S_COALESCED |
601 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
602 SectionKind::getText());
604 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
605 SectionKind::getText());
607 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
608 SectionKind::getText());
609 ConstDataSection // .const_data
610 = getMachOSection("__DATA", "__const", 0,
611 SectionKind::getReadOnlyWithRel());
613 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
614 SectionKind::getDataRel());
617 LazySymbolPointerSection
618 = getMachOSection("__DATA", "__la_symbol_ptr",
619 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
620 SectionKind::getMetadata());
621 NonLazySymbolPointerSection
622 = getMachOSection("__DATA", "__nl_symbol_ptr",
623 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
624 SectionKind::getMetadata());
626 if (TM.getRelocationModel() == Reloc::Static) {
628 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
630 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
633 = getMachOSection("__DATA", "__mod_init_func",
634 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
635 SectionKind::getDataRel());
637 = getMachOSection("__DATA", "__mod_term_func",
638 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
639 SectionKind::getDataRel());
642 // Exception Handling.
643 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
644 SectionKind::getDataRel());
646 getMachOSection("__TEXT", "__eh_frame",
647 MCSectionMachO::S_COALESCED |
648 MCSectionMachO::S_ATTR_NO_TOC |
649 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
650 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
651 SectionKind::getReadOnly());
653 // Debug Information.
655 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
656 SectionKind::getMetadata());
658 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
659 SectionKind::getMetadata());
661 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
662 SectionKind::getMetadata());
664 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
665 SectionKind::getMetadata());
666 DwarfPubNamesSection =
667 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
668 SectionKind::getMetadata());
669 DwarfPubTypesSection =
670 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
671 SectionKind::getMetadata());
673 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
674 SectionKind::getMetadata());
676 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
677 SectionKind::getMetadata());
678 DwarfARangesSection =
679 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
680 SectionKind::getMetadata());
682 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
683 SectionKind::getMetadata());
684 DwarfMacroInfoSection =
685 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
686 SectionKind::getMetadata());
687 DwarfDebugInlineSection =
688 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
689 SectionKind::getMetadata());
692 const MCSection *TargetLoweringObjectFileMachO::
693 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
694 Mangler *Mang, const TargetMachine &TM) const {
695 // Parse the section specifier and create it if valid.
696 StringRef Segment, Section;
697 unsigned TAA, StubSize;
698 std::string ErrorCode =
699 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
701 if (!ErrorCode.empty()) {
702 // If invalid, report the error with llvm_report_error.
703 llvm_report_error("Global variable '" + GV->getNameStr() +
704 "' has an invalid section specifier '" + GV->getSection()+
705 "': " + ErrorCode + ".");
706 // Fall back to dropping it into the data section.
711 const MCSectionMachO *S =
712 getMachOSection(Segment, Section, TAA, StubSize, Kind);
714 // Okay, now that we got the section, verify that the TAA & StubSize agree.
715 // If the user declared multiple globals with different section flags, we need
716 // to reject it here.
717 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
718 // If invalid, report the error with llvm_report_error.
719 llvm_report_error("Global variable '" + GV->getNameStr() +
720 "' section type or attributes does not match previous"
721 " section specifier");
727 const MCSection *TargetLoweringObjectFileMachO::
728 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
729 Mangler *Mang, const TargetMachine &TM) const {
730 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
733 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
735 // If this is weak/linkonce, put this in a coalescable section, either in text
736 // or data depending on if it is writable.
737 if (GV->isWeakForLinker()) {
738 if (Kind.isReadOnly())
739 return ConstTextCoalSection;
740 return DataCoalSection;
743 // FIXME: Alignment check should be handled by section classifier.
744 if (Kind.isMergeable1ByteCString() ||
745 Kind.isMergeable2ByteCString()) {
746 if (TM.getTargetData()->getPreferredAlignment(
747 cast<GlobalVariable>(GV)) < 32) {
748 if (Kind.isMergeable1ByteCString())
749 return CStringSection;
750 assert(Kind.isMergeable2ByteCString());
751 return UStringSection;
755 if (Kind.isMergeableConst()) {
756 if (Kind.isMergeableConst4())
757 return FourByteConstantSection;
758 if (Kind.isMergeableConst8())
759 return EightByteConstantSection;
760 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
761 return SixteenByteConstantSection;
764 // Otherwise, if it is readonly, but not something we can specially optimize,
765 // just drop it in .const.
766 if (Kind.isReadOnly())
767 return ReadOnlySection;
769 // If this is marked const, put it into a const section. But if the dynamic
770 // linker needs to write to it, put it in the data segment.
771 if (Kind.isReadOnlyWithRel())
772 return ConstDataSection;
774 // Otherwise, just drop the variable in the normal data section.
779 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
780 // If this constant requires a relocation, we have to put it in the data
781 // segment, not in the text segment.
782 if (Kind.isDataRel())
783 return ConstDataSection;
785 if (Kind.isMergeableConst4())
786 return FourByteConstantSection;
787 if (Kind.isMergeableConst8())
788 return EightByteConstantSection;
789 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
790 return SixteenByteConstantSection;
791 return ReadOnlySection; // .const
794 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
795 /// not to emit the UsedDirective for some symbols in llvm.used.
796 // FIXME: REMOVE this (rdar://7071300)
797 bool TargetLoweringObjectFileMachO::
798 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
799 /// On Darwin, internally linked data beginning with "L" or "l" does not have
800 /// the directive emitted (this occurs in ObjC metadata).
801 if (!GV) return false;
803 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
804 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
805 // FIXME: ObjC metadata is currently emitted as internal symbols that have
806 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
807 // this horrible hack can go away.
808 const std::string &Name = Mang->getMangledName(GV);
809 if (Name[0] == 'L' || Name[0] == 'l')
817 //===----------------------------------------------------------------------===//
819 //===----------------------------------------------------------------------===//
821 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
823 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
824 delete (COFFUniqueMapTy*)UniquingMap;
828 const MCSection *TargetLoweringObjectFileCOFF::
829 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
830 // Create the map if it doesn't already exist.
831 if (UniquingMap == 0)
832 UniquingMap = new MachOUniqueMapTy();
833 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
835 // Do the lookup, if we have a hit, return it.
836 const MCSectionCOFF *&Entry = Map[Name];
837 if (Entry) return Entry;
839 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
842 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
843 const TargetMachine &TM) {
844 TargetLoweringObjectFile::Initialize(Ctx, TM);
845 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
846 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
848 getCOFFSection(".ctors", false, SectionKind::getDataRel());
850 getCOFFSection(".dtors", false, SectionKind::getDataRel());
854 // FIXME: Don't use 'directive' mode here.
856 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
857 true, SectionKind::getMetadata());
859 getCOFFSection("\t.section\t.debug_info,\"dr\"",
860 true, SectionKind::getMetadata());
862 getCOFFSection("\t.section\t.debug_line,\"dr\"",
863 true, SectionKind::getMetadata());
865 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
866 true, SectionKind::getMetadata());
867 DwarfPubNamesSection =
868 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
869 true, SectionKind::getMetadata());
870 DwarfPubTypesSection =
871 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
872 true, SectionKind::getMetadata());
874 getCOFFSection("\t.section\t.debug_str,\"dr\"",
875 true, SectionKind::getMetadata());
877 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
878 true, SectionKind::getMetadata());
879 DwarfARangesSection =
880 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
881 true, SectionKind::getMetadata());
883 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
884 true, SectionKind::getMetadata());
885 DwarfMacroInfoSection =
886 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
887 true, SectionKind::getMetadata());
890 const MCSection *TargetLoweringObjectFileCOFF::
891 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
892 Mangler *Mang, const TargetMachine &TM) const {
893 return getCOFFSection(GV->getSection().c_str(), false, Kind);
896 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
898 return ".text$linkonce";
899 if (Kind.isWriteable())
900 return ".data$linkonce";
901 return ".rdata$linkonce";
905 const MCSection *TargetLoweringObjectFileCOFF::
906 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
907 Mangler *Mang, const TargetMachine &TM) const {
908 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
910 // If this global is linkonce/weak and the target handles this by emitting it
911 // into a 'uniqued' section name, create and return the section now.
912 if (GV->isWeakForLinker()) {
913 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
914 std::string Name = Mang->makeNameProper(GV->getNameStr());
915 return getCOFFSection((Prefix+Name).c_str(), false, Kind);
919 return getTextSection();
921 return getDataSection();