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/MC/MCSectionELF.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(StringRef Section, unsigned Type, unsigned Flags,
292 SectionKind Kind, bool IsExplicit) const {
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[Section];
299 if (Entry) return Entry;
301 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
305 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
306 const TargetMachine &TM) {
307 if (UniquingMap != 0)
308 ((ELFUniqueMapTy*)UniquingMap)->clear();
309 TargetLoweringObjectFile::Initialize(Ctx, TM);
312 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
313 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
314 SectionKind::getBSS());
317 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
318 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
319 SectionKind::getText());
322 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
323 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
324 SectionKind::getDataRel());
327 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
328 MCSectionELF::SHF_ALLOC,
329 SectionKind::getReadOnly());
332 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
333 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
334 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
337 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
338 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
339 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
342 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
343 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
344 SectionKind::getDataRel());
346 DataRelLocalSection =
347 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
348 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
349 SectionKind::getDataRelLocal());
352 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
353 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
354 SectionKind::getReadOnlyWithRel());
356 DataRelROLocalSection =
357 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
358 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
359 SectionKind::getReadOnlyWithRelLocal());
361 MergeableConst4Section =
362 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
363 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
364 SectionKind::getMergeableConst4());
366 MergeableConst8Section =
367 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
368 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
369 SectionKind::getMergeableConst8());
371 MergeableConst16Section =
372 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
373 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
374 SectionKind::getMergeableConst16());
377 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
378 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
379 SectionKind::getDataRel());
382 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
383 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
384 SectionKind::getDataRel());
386 // Exception Handling Sections.
388 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
389 // it contains relocatable pointers. In PIC mode, this is probably a big
390 // runtime hit for C++ apps. Either the contents of the LSDA need to be
391 // adjusted or this should be a data section.
393 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
394 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
396 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
397 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
398 SectionKind::getDataRel());
400 // Debug Info Sections.
402 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
403 SectionKind::getMetadata());
405 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
406 SectionKind::getMetadata());
408 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
409 SectionKind::getMetadata());
411 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
412 SectionKind::getMetadata());
413 DwarfPubNamesSection =
414 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
415 SectionKind::getMetadata());
416 DwarfPubTypesSection =
417 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
418 SectionKind::getMetadata());
420 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
421 SectionKind::getMetadata());
423 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
424 SectionKind::getMetadata());
425 DwarfARangesSection =
426 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
427 SectionKind::getMetadata());
429 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
430 SectionKind::getMetadata());
431 DwarfMacroInfoSection =
432 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
433 SectionKind::getMetadata());
438 getELFKindForNamedSection(const char *Name, SectionKind K) {
439 if (Name[0] != '.') return K;
441 // Some lame default implementation based on some magic section names.
442 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
443 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
444 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
445 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
446 return SectionKind::getBSS();
448 if (strcmp(Name, ".tdata") == 0 ||
449 strncmp(Name, ".tdata.", 7) == 0 ||
450 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
451 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
452 return SectionKind::getThreadData();
454 if (strcmp(Name, ".tbss") == 0 ||
455 strncmp(Name, ".tbss.", 6) == 0 ||
456 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
457 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
458 return SectionKind::getThreadBSS();
465 getELFSectionType(const char *Name, SectionKind K) {
467 if (strcmp(Name, ".init_array") == 0)
468 return MCSectionELF::SHT_INIT_ARRAY;
470 if (strcmp(Name, ".fini_array") == 0)
471 return MCSectionELF::SHT_FINI_ARRAY;
473 if (strcmp(Name, ".preinit_array") == 0)
474 return MCSectionELF::SHT_PREINIT_ARRAY;
476 if (K.isBSS() || K.isThreadBSS())
477 return MCSectionELF::SHT_NOBITS;
479 return MCSectionELF::SHT_PROGBITS;
484 getELFSectionFlags(SectionKind K) {
488 Flags |= MCSectionELF::SHF_ALLOC;
491 Flags |= MCSectionELF::SHF_EXECINSTR;
494 Flags |= MCSectionELF::SHF_WRITE;
496 if (K.isThreadLocal())
497 Flags |= MCSectionELF::SHF_TLS;
499 // K.isMergeableConst() is left out to honour PR4650
500 if (K.isMergeableCString() || K.isMergeableConst4() ||
501 K.isMergeableConst8() || K.isMergeableConst16())
502 Flags |= MCSectionELF::SHF_MERGE;
504 if (K.isMergeableCString())
505 Flags |= MCSectionELF::SHF_STRINGS;
511 const MCSection *TargetLoweringObjectFileELF::
512 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
513 Mangler *Mang, const TargetMachine &TM) const {
514 const char *SectionName = GV->getSection().c_str();
516 // Infer section flags from the section name if we can.
517 Kind = getELFKindForNamedSection(SectionName, Kind);
519 return getELFSection(SectionName,
520 getELFSectionType(SectionName, Kind),
521 getELFSectionFlags(Kind), Kind, true);
524 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
525 if (Kind.isText()) return ".gnu.linkonce.t.";
526 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
528 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
529 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
531 if (Kind.isBSS()) return ".gnu.linkonce.b.";
532 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
533 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
534 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
535 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
537 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
538 return ".gnu.linkonce.d.rel.ro.";
541 const MCSection *TargetLoweringObjectFileELF::
542 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
543 Mangler *Mang, const TargetMachine &TM) const {
545 // If this global is linkonce/weak and the target handles this by emitting it
546 // into a 'uniqued' section name, create and return the section now.
547 if (GV->isWeakForLinker()) {
548 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
549 std::string Name = Mang->makeNameProper(GV->getNameStr());
551 return getELFSection((Prefix+Name).c_str(),
552 getELFSectionType((Prefix+Name).c_str(), Kind),
553 getELFSectionFlags(Kind),
557 if (Kind.isText()) return TextSection;
559 if (Kind.isMergeable1ByteCString() ||
560 Kind.isMergeable2ByteCString() ||
561 Kind.isMergeable4ByteCString()) {
563 // We also need alignment here.
564 // FIXME: this is getting the alignment of the character, not the
565 // alignment of the global!
567 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
569 const char *SizeSpec = ".rodata.str1.";
570 if (Kind.isMergeable2ByteCString())
571 SizeSpec = ".rodata.str2.";
572 else if (Kind.isMergeable4ByteCString())
573 SizeSpec = ".rodata.str4.";
575 assert(Kind.isMergeable1ByteCString() && "unknown string width");
578 std::string Name = SizeSpec + utostr(Align);
579 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
580 MCSectionELF::SHF_ALLOC |
581 MCSectionELF::SHF_MERGE |
582 MCSectionELF::SHF_STRINGS,
586 if (Kind.isMergeableConst()) {
587 if (Kind.isMergeableConst4() && MergeableConst4Section)
588 return MergeableConst4Section;
589 if (Kind.isMergeableConst8() && MergeableConst8Section)
590 return MergeableConst8Section;
591 if (Kind.isMergeableConst16() && MergeableConst16Section)
592 return MergeableConst16Section;
593 return ReadOnlySection; // .const
596 if (Kind.isReadOnly()) return ReadOnlySection;
598 if (Kind.isThreadData()) return TLSDataSection;
599 if (Kind.isThreadBSS()) return TLSBSSSection;
601 if (Kind.isBSS()) return BSSSection;
603 if (Kind.isDataNoRel()) return DataSection;
604 if (Kind.isDataRelLocal()) return DataRelLocalSection;
605 if (Kind.isDataRel()) return DataRelSection;
606 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
608 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
609 return DataRelROSection;
612 /// getSectionForConstant - Given a mergeable constant with the
613 /// specified size and relocation information, return a section that it
614 /// should be placed in.
615 const MCSection *TargetLoweringObjectFileELF::
616 getSectionForConstant(SectionKind Kind) const {
617 if (Kind.isMergeableConst4() && MergeableConst4Section)
618 return MergeableConst4Section;
619 if (Kind.isMergeableConst8() && MergeableConst8Section)
620 return MergeableConst8Section;
621 if (Kind.isMergeableConst16() && MergeableConst16Section)
622 return MergeableConst16Section;
623 if (Kind.isReadOnly())
624 return ReadOnlySection;
626 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
627 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
628 return DataRelROSection;
631 //===----------------------------------------------------------------------===//
633 //===----------------------------------------------------------------------===//
635 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
637 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
638 // If we have the MachO uniquing map, free it.
639 delete (MachOUniqueMapTy*)UniquingMap;
643 const MCSectionMachO *TargetLoweringObjectFileMachO::
644 getMachOSection(const StringRef &Segment, const StringRef &Section,
645 unsigned TypeAndAttributes,
646 unsigned Reserved2, SectionKind Kind) const {
647 // We unique sections by their segment/section pair. The returned section
648 // may not have the same flags as the requested section, if so this should be
649 // diagnosed by the client as an error.
651 // Create the map if it doesn't already exist.
652 if (UniquingMap == 0)
653 UniquingMap = new MachOUniqueMapTy();
654 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
656 // Form the name to look up.
657 SmallString<64> Name;
658 Name.append(Segment.begin(), Segment.end());
660 Name.append(Section.begin(), Section.end());
662 // Do the lookup, if we have a hit, return it.
663 const MCSectionMachO *&Entry = Map[StringRef(Name.data(), Name.size())];
664 if (Entry) return Entry;
666 // Otherwise, return a new section.
667 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
668 Reserved2, Kind, getContext());
672 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
673 const TargetMachine &TM) {
674 if (UniquingMap != 0)
675 ((MachOUniqueMapTy*)UniquingMap)->clear();
676 TargetLoweringObjectFile::Initialize(Ctx, TM);
679 = getMachOSection("__TEXT", "__text",
680 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
681 SectionKind::getText());
683 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
685 CStringSection // .cstring
686 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
687 SectionKind::getMergeable1ByteCString());
689 = getMachOSection("__TEXT","__ustring", 0,
690 SectionKind::getMergeable2ByteCString());
691 FourByteConstantSection // .literal4
692 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
693 SectionKind::getMergeableConst4());
694 EightByteConstantSection // .literal8
695 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
696 SectionKind::getMergeableConst8());
698 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
699 // to using it in -static mode.
700 SixteenByteConstantSection = 0;
701 if (TM.getRelocationModel() != Reloc::Static &&
702 TM.getTargetData()->getPointerSize() == 32)
703 SixteenByteConstantSection = // .literal16
704 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
705 SectionKind::getMergeableConst16());
707 ReadOnlySection // .const
708 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
711 = getMachOSection("__TEXT", "__textcoal_nt",
712 MCSectionMachO::S_COALESCED |
713 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
714 SectionKind::getText());
716 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
717 SectionKind::getText());
719 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
720 SectionKind::getText());
721 ConstDataSection // .const_data
722 = getMachOSection("__DATA", "__const", 0,
723 SectionKind::getReadOnlyWithRel());
725 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
726 SectionKind::getDataRel());
729 LazySymbolPointerSection
730 = getMachOSection("__DATA", "__la_symbol_ptr",
731 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
732 SectionKind::getMetadata());
733 NonLazySymbolPointerSection
734 = getMachOSection("__DATA", "__nl_symbol_ptr",
735 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
736 SectionKind::getMetadata());
738 if (TM.getRelocationModel() == Reloc::Static) {
740 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
742 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
745 = getMachOSection("__DATA", "__mod_init_func",
746 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
747 SectionKind::getDataRel());
749 = getMachOSection("__DATA", "__mod_term_func",
750 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
751 SectionKind::getDataRel());
754 // Exception Handling.
755 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
756 SectionKind::getDataRel());
758 getMachOSection("__TEXT", "__eh_frame",
759 MCSectionMachO::S_COALESCED |
760 MCSectionMachO::S_ATTR_NO_TOC |
761 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
762 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
763 SectionKind::getReadOnly());
765 // Debug Information.
767 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
768 SectionKind::getMetadata());
770 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
771 SectionKind::getMetadata());
773 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
774 SectionKind::getMetadata());
776 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
777 SectionKind::getMetadata());
778 DwarfPubNamesSection =
779 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
780 SectionKind::getMetadata());
781 DwarfPubTypesSection =
782 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
783 SectionKind::getMetadata());
785 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
786 SectionKind::getMetadata());
788 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
789 SectionKind::getMetadata());
790 DwarfARangesSection =
791 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
792 SectionKind::getMetadata());
794 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
795 SectionKind::getMetadata());
796 DwarfMacroInfoSection =
797 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
798 SectionKind::getMetadata());
799 DwarfDebugInlineSection =
800 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
801 SectionKind::getMetadata());
804 const MCSection *TargetLoweringObjectFileMachO::
805 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
806 Mangler *Mang, const TargetMachine &TM) const {
807 // Parse the section specifier and create it if valid.
808 StringRef Segment, Section;
809 unsigned TAA, StubSize;
810 std::string ErrorCode =
811 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
813 if (!ErrorCode.empty()) {
814 // If invalid, report the error with llvm_report_error.
815 llvm_report_error("Global variable '" + GV->getNameStr() +
816 "' has an invalid section specifier '" + GV->getSection()+
817 "': " + ErrorCode + ".");
818 // Fall back to dropping it into the data section.
823 const MCSectionMachO *S =
824 getMachOSection(Segment, Section, TAA, StubSize, Kind);
826 // Okay, now that we got the section, verify that the TAA & StubSize agree.
827 // If the user declared multiple globals with different section flags, we need
828 // to reject it here.
829 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
830 // If invalid, report the error with llvm_report_error.
831 llvm_report_error("Global variable '" + GV->getNameStr() +
832 "' section type or attributes does not match previous"
833 " section specifier");
839 const MCSection *TargetLoweringObjectFileMachO::
840 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
841 Mangler *Mang, const TargetMachine &TM) const {
842 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
845 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
847 // If this is weak/linkonce, put this in a coalescable section, either in text
848 // or data depending on if it is writable.
849 if (GV->isWeakForLinker()) {
850 if (Kind.isReadOnly())
851 return ConstTextCoalSection;
852 return DataCoalSection;
855 // FIXME: Alignment check should be handled by section classifier.
856 if (Kind.isMergeable1ByteCString() ||
857 Kind.isMergeable2ByteCString()) {
858 if (TM.getTargetData()->getPreferredAlignment(
859 cast<GlobalVariable>(GV)) < 32) {
860 if (Kind.isMergeable1ByteCString())
861 return CStringSection;
862 assert(Kind.isMergeable2ByteCString());
863 return UStringSection;
867 if (Kind.isMergeableConst()) {
868 if (Kind.isMergeableConst4())
869 return FourByteConstantSection;
870 if (Kind.isMergeableConst8())
871 return EightByteConstantSection;
872 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
873 return SixteenByteConstantSection;
876 // Otherwise, if it is readonly, but not something we can specially optimize,
877 // just drop it in .const.
878 if (Kind.isReadOnly())
879 return ReadOnlySection;
881 // If this is marked const, put it into a const section. But if the dynamic
882 // linker needs to write to it, put it in the data segment.
883 if (Kind.isReadOnlyWithRel())
884 return ConstDataSection;
886 // Otherwise, just drop the variable in the normal data section.
891 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
892 // If this constant requires a relocation, we have to put it in the data
893 // segment, not in the text segment.
894 if (Kind.isDataRel())
895 return ConstDataSection;
897 if (Kind.isMergeableConst4())
898 return FourByteConstantSection;
899 if (Kind.isMergeableConst8())
900 return EightByteConstantSection;
901 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
902 return SixteenByteConstantSection;
903 return ReadOnlySection; // .const
906 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
907 /// not to emit the UsedDirective for some symbols in llvm.used.
908 // FIXME: REMOVE this (rdar://7071300)
909 bool TargetLoweringObjectFileMachO::
910 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
911 /// On Darwin, internally linked data beginning with "L" or "l" does not have
912 /// the directive emitted (this occurs in ObjC metadata).
913 if (!GV) return false;
915 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
916 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
917 // FIXME: ObjC metadata is currently emitted as internal symbols that have
918 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
919 // this horrible hack can go away.
920 const std::string &Name = Mang->getMangledName(GV);
921 if (Name[0] == 'L' || Name[0] == 'l')
929 //===----------------------------------------------------------------------===//
931 //===----------------------------------------------------------------------===//
933 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
935 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
936 delete (COFFUniqueMapTy*)UniquingMap;
940 const MCSection *TargetLoweringObjectFileCOFF::
941 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
942 // Create the map if it doesn't already exist.
943 if (UniquingMap == 0)
944 UniquingMap = new MachOUniqueMapTy();
945 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
947 // Do the lookup, if we have a hit, return it.
948 const MCSectionCOFF *&Entry = Map[Name];
949 if (Entry) return Entry;
951 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
954 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
955 const TargetMachine &TM) {
956 if (UniquingMap != 0)
957 ((COFFUniqueMapTy*)UniquingMap)->clear();
958 TargetLoweringObjectFile::Initialize(Ctx, TM);
959 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
960 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
962 getCOFFSection(".ctors", false, SectionKind::getDataRel());
964 getCOFFSection(".dtors", false, SectionKind::getDataRel());
966 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
967 // though it contains relocatable pointers. In PIC mode, this is probably a
968 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
969 // adjusted or this should be a data section.
971 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
973 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
976 // FIXME: Don't use 'directive' mode here.
978 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
979 true, SectionKind::getMetadata());
981 getCOFFSection("\t.section\t.debug_info,\"dr\"",
982 true, SectionKind::getMetadata());
984 getCOFFSection("\t.section\t.debug_line,\"dr\"",
985 true, SectionKind::getMetadata());
987 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
988 true, SectionKind::getMetadata());
989 DwarfPubNamesSection =
990 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
991 true, SectionKind::getMetadata());
992 DwarfPubTypesSection =
993 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
994 true, SectionKind::getMetadata());
996 getCOFFSection("\t.section\t.debug_str,\"dr\"",
997 true, SectionKind::getMetadata());
999 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1000 true, SectionKind::getMetadata());
1001 DwarfARangesSection =
1002 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1003 true, SectionKind::getMetadata());
1004 DwarfRangesSection =
1005 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1006 true, SectionKind::getMetadata());
1007 DwarfMacroInfoSection =
1008 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1009 true, SectionKind::getMetadata());
1012 const MCSection *TargetLoweringObjectFileCOFF::
1013 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1014 Mangler *Mang, const TargetMachine &TM) const {
1015 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1018 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1020 return ".text$linkonce";
1021 if (Kind.isWriteable())
1022 return ".data$linkonce";
1023 return ".rdata$linkonce";
1027 const MCSection *TargetLoweringObjectFileCOFF::
1028 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1029 Mangler *Mang, const TargetMachine &TM) const {
1030 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1032 // If this global is linkonce/weak and the target handles this by emitting it
1033 // into a 'uniqued' section name, create and return the section now.
1034 if (GV->isWeakForLinker()) {
1035 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1036 std::string Name = Mang->makeNameProper(GV->getNameStr());
1037 return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1041 return getTextSection();
1043 return getDataSection();