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/MCExpr.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
44 StaticCtorSection = 0;
45 StaticDtorSection = 0;
49 DwarfAbbrevSection = 0;
52 DwarfFrameSection = 0;
53 DwarfPubNamesSection = 0;
54 DwarfPubTypesSection = 0;
55 DwarfDebugInlineSection = 0;
58 DwarfARangesSection = 0;
59 DwarfRangesSection = 0;
60 DwarfMacroInfoSection = 0;
63 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
66 static bool isSuitableForBSS(const GlobalVariable *GV) {
67 Constant *C = GV->getInitializer();
69 // Must have zero initializer.
70 if (!C->isNullValue())
73 // Leave constant zeros in readonly constant sections, so they can be shared.
77 // If the global has an explicit section specified, don't put it in BSS.
78 if (!GV->getSection().empty())
81 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
85 // Otherwise, put it in BSS!
89 /// IsNullTerminatedString - Return true if the specified constant (which is
90 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
91 /// nul value and contains no other nuls in it.
92 static bool IsNullTerminatedString(const Constant *C) {
93 const ArrayType *ATy = cast<ArrayType>(C->getType());
95 // First check: is we have constant array of i8 terminated with zero
96 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
97 if (ATy->getNumElements() == 0) return false;
100 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
101 if (Null == 0 || Null->getZExtValue() != 0)
102 return false; // Not null terminated.
104 // Verify that the null doesn't occur anywhere else in the string.
105 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
106 // Reject constantexpr elements etc.
107 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
108 CVA->getOperand(i) == Null)
113 // Another possibility: [1 x i8] zeroinitializer
114 if (isa<ConstantAggregateZero>(C))
115 return ATy->getNumElements() == 1;
120 /// getKindForGlobal - This is a top-level target-independent classifier for
121 /// a global variable. Given an global variable and information from TM, it
122 /// classifies the global in a variety of ways that make various target
123 /// implementations simpler. The target implementation is free to ignore this
124 /// extra info of course.
125 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
126 const TargetMachine &TM){
127 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
128 "Can only be used for global definitions");
130 Reloc::Model ReloModel = TM.getRelocationModel();
132 // Early exit - functions should be always in text sections.
133 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
135 return SectionKind::getText();
137 // Handle thread-local data first.
138 if (GVar->isThreadLocal()) {
139 if (isSuitableForBSS(GVar))
140 return SectionKind::getThreadBSS();
141 return SectionKind::getThreadData();
144 // Variable can be easily put to BSS section.
145 if (isSuitableForBSS(GVar))
146 return SectionKind::getBSS();
148 Constant *C = GVar->getInitializer();
150 // If the global is marked constant, we can put it into a mergable section,
151 // a mergable string section, or general .data if it contains relocations.
152 if (GVar->isConstant()) {
153 // If the initializer for the global contains something that requires a
154 // relocation, then we may have to drop this into a wriable data section
155 // even though it is marked const.
156 switch (C->getRelocationInfo()) {
157 default: assert(0 && "unknown relocation info kind");
158 case Constant::NoRelocation:
159 // If initializer is a null-terminated string, put it in a "cstring"
160 // section of the right width.
161 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
162 if (const IntegerType *ITy =
163 dyn_cast<IntegerType>(ATy->getElementType())) {
164 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
165 ITy->getBitWidth() == 32) &&
166 IsNullTerminatedString(C)) {
167 if (ITy->getBitWidth() == 8)
168 return SectionKind::getMergeable1ByteCString();
169 if (ITy->getBitWidth() == 16)
170 return SectionKind::getMergeable2ByteCString();
172 assert(ITy->getBitWidth() == 32 && "Unknown width");
173 return SectionKind::getMergeable4ByteCString();
178 // Otherwise, just drop it into a mergable constant section. If we have
179 // a section for this size, use it, otherwise use the arbitrary sized
181 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
182 case 4: return SectionKind::getMergeableConst4();
183 case 8: return SectionKind::getMergeableConst8();
184 case 16: return SectionKind::getMergeableConst16();
185 default: return SectionKind::getMergeableConst();
188 case Constant::LocalRelocation:
189 // In static relocation model, the linker will resolve all addresses, so
190 // the relocation entries will actually be constants by the time the app
191 // starts up. However, we can't put this into a mergable section, because
192 // the linker doesn't take relocations into consideration when it tries to
193 // merge entries in the section.
194 if (ReloModel == Reloc::Static)
195 return SectionKind::getReadOnly();
197 // Otherwise, the dynamic linker needs to fix it up, put it in the
198 // writable data.rel.local section.
199 return SectionKind::getReadOnlyWithRelLocal();
201 case Constant::GlobalRelocations:
202 // In static relocation model, the linker will resolve all addresses, so
203 // the relocation entries will actually be constants by the time the app
204 // starts up. However, we can't put this into a mergable section, because
205 // the linker doesn't take relocations into consideration when it tries to
206 // merge entries in the section.
207 if (ReloModel == Reloc::Static)
208 return SectionKind::getReadOnly();
210 // Otherwise, the dynamic linker needs to fix it up, put it in the
211 // writable data.rel section.
212 return SectionKind::getReadOnlyWithRel();
216 // Okay, this isn't a constant. If the initializer for the global is going
217 // to require a runtime relocation by the dynamic linker, put it into a more
218 // specific section to improve startup time of the app. This coalesces these
219 // globals together onto fewer pages, improving the locality of the dynamic
221 if (ReloModel == Reloc::Static)
222 return SectionKind::getDataNoRel();
224 switch (C->getRelocationInfo()) {
225 default: assert(0 && "unknown relocation info kind");
226 case Constant::NoRelocation:
227 return SectionKind::getDataNoRel();
228 case Constant::LocalRelocation:
229 return SectionKind::getDataRelLocal();
230 case Constant::GlobalRelocations:
231 return SectionKind::getDataRel();
235 /// SectionForGlobal - This method computes the appropriate section to emit
236 /// the specified global variable or function definition. This should not
237 /// be passed external (or available externally) globals.
238 const MCSection *TargetLoweringObjectFile::
239 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
240 const TargetMachine &TM) const {
241 // Select section name.
242 if (GV->hasSection())
243 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
246 // Use default section depending on the 'type' of global
247 return SelectSectionForGlobal(GV, Kind, Mang, TM);
251 // Lame default implementation. Calculate the section name for global.
253 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
256 const TargetMachine &TM) const{
257 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
260 return getTextSection();
262 if (Kind.isBSS() && BSSSection != 0)
265 if (Kind.isReadOnly() && ReadOnlySection != 0)
266 return ReadOnlySection;
268 return getDataSection();
271 /// getSectionForConstant - Given a mergable constant with the
272 /// specified size and relocation information, return a section that it
273 /// should be placed in.
275 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
276 if (Kind.isReadOnly() && ReadOnlySection != 0)
277 return ReadOnlySection;
282 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
283 /// pc-relative reference to the specified global variable from exception
284 /// handling information. In addition to the symbol, this returns
287 /// IsIndirect - True if the returned symbol is actually a stub that contains
288 /// the address of the symbol, false if the symbol is the global itself.
290 /// IsPCRel - True if the symbol reference is already pc-relative, false if
291 /// the caller needs to subtract off the address of the reference from the
294 const MCExpr *TargetLoweringObjectFile::
295 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
296 MachineModuleInfo *MMI,
297 bool &IsIndirect, bool &IsPCRel) const {
298 // The generic implementation of this just returns a direct reference to the
303 SmallString<128> Name;
304 Mang->getNameWithPrefix(Name, GV, false);
305 return MCSymbolRefExpr::Create(Name.str(), getContext());
309 //===----------------------------------------------------------------------===//
311 //===----------------------------------------------------------------------===//
312 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
314 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
315 // If we have the section uniquing map, free it.
316 delete (ELFUniqueMapTy*)UniquingMap;
319 const MCSection *TargetLoweringObjectFileELF::
320 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
321 SectionKind Kind, bool IsExplicit) const {
322 if (UniquingMap == 0)
323 UniquingMap = new ELFUniqueMapTy();
324 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
326 // Do the lookup, if we have a hit, return it.
327 const MCSectionELF *&Entry = Map[Section];
328 if (Entry) return Entry;
330 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
334 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
335 const TargetMachine &TM) {
336 if (UniquingMap != 0)
337 ((ELFUniqueMapTy*)UniquingMap)->clear();
338 TargetLoweringObjectFile::Initialize(Ctx, TM);
341 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
342 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
343 SectionKind::getBSS());
346 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
347 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
348 SectionKind::getText());
351 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
352 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
353 SectionKind::getDataRel());
356 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
357 MCSectionELF::SHF_ALLOC,
358 SectionKind::getReadOnly());
361 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
362 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
363 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
366 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
367 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
368 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
371 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
372 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
373 SectionKind::getDataRel());
375 DataRelLocalSection =
376 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
377 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
378 SectionKind::getDataRelLocal());
381 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
382 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
383 SectionKind::getReadOnlyWithRel());
385 DataRelROLocalSection =
386 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
387 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
388 SectionKind::getReadOnlyWithRelLocal());
390 MergeableConst4Section =
391 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
392 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
393 SectionKind::getMergeableConst4());
395 MergeableConst8Section =
396 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
397 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
398 SectionKind::getMergeableConst8());
400 MergeableConst16Section =
401 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
402 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
403 SectionKind::getMergeableConst16());
406 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
407 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
408 SectionKind::getDataRel());
411 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
412 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
413 SectionKind::getDataRel());
415 // Exception Handling Sections.
417 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
418 // it contains relocatable pointers. In PIC mode, this is probably a big
419 // runtime hit for C++ apps. Either the contents of the LSDA need to be
420 // adjusted or this should be a data section.
422 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
423 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
425 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
426 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
427 SectionKind::getDataRel());
429 // Debug Info Sections.
431 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
432 SectionKind::getMetadata());
434 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
435 SectionKind::getMetadata());
437 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
438 SectionKind::getMetadata());
440 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
441 SectionKind::getMetadata());
442 DwarfPubNamesSection =
443 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
444 SectionKind::getMetadata());
445 DwarfPubTypesSection =
446 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
447 SectionKind::getMetadata());
449 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
450 SectionKind::getMetadata());
452 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
453 SectionKind::getMetadata());
454 DwarfARangesSection =
455 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
456 SectionKind::getMetadata());
458 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
459 SectionKind::getMetadata());
460 DwarfMacroInfoSection =
461 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
462 SectionKind::getMetadata());
467 getELFKindForNamedSection(const char *Name, SectionKind K) {
468 if (Name[0] != '.') return K;
470 // Some lame default implementation based on some magic section names.
471 if (strcmp(Name, ".bss") == 0 ||
472 strncmp(Name, ".bss.", 5) == 0 ||
473 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
474 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
475 strcmp(Name, ".sbss") == 0 ||
476 strncmp(Name, ".sbss.", 6) == 0 ||
477 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
478 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
479 return SectionKind::getBSS();
481 if (strcmp(Name, ".tdata") == 0 ||
482 strncmp(Name, ".tdata.", 7) == 0 ||
483 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
484 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
485 return SectionKind::getThreadData();
487 if (strcmp(Name, ".tbss") == 0 ||
488 strncmp(Name, ".tbss.", 6) == 0 ||
489 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
490 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
491 return SectionKind::getThreadBSS();
497 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
499 if (Name == ".init_array")
500 return MCSectionELF::SHT_INIT_ARRAY;
502 if (Name == ".fini_array")
503 return MCSectionELF::SHT_FINI_ARRAY;
505 if (Name == ".preinit_array")
506 return MCSectionELF::SHT_PREINIT_ARRAY;
508 if (K.isBSS() || K.isThreadBSS())
509 return MCSectionELF::SHT_NOBITS;
511 return MCSectionELF::SHT_PROGBITS;
516 getELFSectionFlags(SectionKind K) {
520 Flags |= MCSectionELF::SHF_ALLOC;
523 Flags |= MCSectionELF::SHF_EXECINSTR;
526 Flags |= MCSectionELF::SHF_WRITE;
528 if (K.isThreadLocal())
529 Flags |= MCSectionELF::SHF_TLS;
531 // K.isMergeableConst() is left out to honour PR4650
532 if (K.isMergeableCString() || K.isMergeableConst4() ||
533 K.isMergeableConst8() || K.isMergeableConst16())
534 Flags |= MCSectionELF::SHF_MERGE;
536 if (K.isMergeableCString())
537 Flags |= MCSectionELF::SHF_STRINGS;
543 const MCSection *TargetLoweringObjectFileELF::
544 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
545 Mangler *Mang, const TargetMachine &TM) const {
546 const char *SectionName = GV->getSection().c_str();
548 // Infer section flags from the section name if we can.
549 Kind = getELFKindForNamedSection(SectionName, Kind);
551 return getELFSection(SectionName,
552 getELFSectionType(SectionName, Kind),
553 getELFSectionFlags(Kind), Kind, true);
556 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
557 if (Kind.isText()) return ".gnu.linkonce.t.";
558 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
560 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
561 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
563 if (Kind.isBSS()) return ".gnu.linkonce.b.";
564 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
565 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
566 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
567 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
569 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
570 return ".gnu.linkonce.d.rel.ro.";
573 const MCSection *TargetLoweringObjectFileELF::
574 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
575 Mangler *Mang, const TargetMachine &TM) const {
577 // If this global is linkonce/weak and the target handles this by emitting it
578 // into a 'uniqued' section name, create and return the section now.
579 if (GV->isWeakForLinker()) {
580 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
581 SmallString<128> Name, MangledName;
582 Name.append(Prefix, Prefix+strlen(Prefix));
583 Mang->getNameWithPrefix(Name, GV, false);
585 raw_svector_ostream OS(MangledName);
586 MCSymbol::printMangledName(Name, OS, 0);
589 return getELFSection(MangledName.str(),
590 getELFSectionType(MangledName.str(), Kind),
591 getELFSectionFlags(Kind),
595 if (Kind.isText()) return TextSection;
597 if (Kind.isMergeable1ByteCString() ||
598 Kind.isMergeable2ByteCString() ||
599 Kind.isMergeable4ByteCString()) {
601 // We also need alignment here.
602 // FIXME: this is getting the alignment of the character, not the
603 // alignment of the global!
605 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
607 const char *SizeSpec = ".rodata.str1.";
608 if (Kind.isMergeable2ByteCString())
609 SizeSpec = ".rodata.str2.";
610 else if (Kind.isMergeable4ByteCString())
611 SizeSpec = ".rodata.str4.";
613 assert(Kind.isMergeable1ByteCString() && "unknown string width");
616 std::string Name = SizeSpec + utostr(Align);
617 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
618 MCSectionELF::SHF_ALLOC |
619 MCSectionELF::SHF_MERGE |
620 MCSectionELF::SHF_STRINGS,
624 if (Kind.isMergeableConst()) {
625 if (Kind.isMergeableConst4() && MergeableConst4Section)
626 return MergeableConst4Section;
627 if (Kind.isMergeableConst8() && MergeableConst8Section)
628 return MergeableConst8Section;
629 if (Kind.isMergeableConst16() && MergeableConst16Section)
630 return MergeableConst16Section;
631 return ReadOnlySection; // .const
634 if (Kind.isReadOnly()) return ReadOnlySection;
636 if (Kind.isThreadData()) return TLSDataSection;
637 if (Kind.isThreadBSS()) return TLSBSSSection;
639 if (Kind.isBSS()) return BSSSection;
641 if (Kind.isDataNoRel()) return DataSection;
642 if (Kind.isDataRelLocal()) return DataRelLocalSection;
643 if (Kind.isDataRel()) return DataRelSection;
644 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
646 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
647 return DataRelROSection;
650 /// getSectionForConstant - Given a mergeable constant with the
651 /// specified size and relocation information, return a section that it
652 /// should be placed in.
653 const MCSection *TargetLoweringObjectFileELF::
654 getSectionForConstant(SectionKind Kind) const {
655 if (Kind.isMergeableConst4() && MergeableConst4Section)
656 return MergeableConst4Section;
657 if (Kind.isMergeableConst8() && MergeableConst8Section)
658 return MergeableConst8Section;
659 if (Kind.isMergeableConst16() && MergeableConst16Section)
660 return MergeableConst16Section;
661 if (Kind.isReadOnly())
662 return ReadOnlySection;
664 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
665 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
666 return DataRelROSection;
669 //===----------------------------------------------------------------------===//
671 //===----------------------------------------------------------------------===//
673 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
675 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
676 // If we have the MachO uniquing map, free it.
677 delete (MachOUniqueMapTy*)UniquingMap;
681 const MCSectionMachO *TargetLoweringObjectFileMachO::
682 getMachOSection(StringRef Segment, StringRef Section,
683 unsigned TypeAndAttributes,
684 unsigned Reserved2, SectionKind Kind) const {
685 // We unique sections by their segment/section pair. The returned section
686 // may not have the same flags as the requested section, if so this should be
687 // diagnosed by the client as an error.
689 // Create the map if it doesn't already exist.
690 if (UniquingMap == 0)
691 UniquingMap = new MachOUniqueMapTy();
692 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
694 // Form the name to look up.
695 SmallString<64> Name;
700 // Do the lookup, if we have a hit, return it.
701 const MCSectionMachO *&Entry = Map[Name.str()];
702 if (Entry) return Entry;
704 // Otherwise, return a new section.
705 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
706 Reserved2, Kind, getContext());
710 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
711 const TargetMachine &TM) {
712 if (UniquingMap != 0)
713 ((MachOUniqueMapTy*)UniquingMap)->clear();
714 TargetLoweringObjectFile::Initialize(Ctx, TM);
717 = getMachOSection("__TEXT", "__text",
718 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
719 SectionKind::getText());
721 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
723 CStringSection // .cstring
724 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
725 SectionKind::getMergeable1ByteCString());
727 = getMachOSection("__TEXT","__ustring", 0,
728 SectionKind::getMergeable2ByteCString());
729 FourByteConstantSection // .literal4
730 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
731 SectionKind::getMergeableConst4());
732 EightByteConstantSection // .literal8
733 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
734 SectionKind::getMergeableConst8());
736 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
737 // to using it in -static mode.
738 SixteenByteConstantSection = 0;
739 if (TM.getRelocationModel() != Reloc::Static &&
740 TM.getTargetData()->getPointerSize() == 32)
741 SixteenByteConstantSection = // .literal16
742 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
743 SectionKind::getMergeableConst16());
745 ReadOnlySection // .const
746 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
749 = getMachOSection("__TEXT", "__textcoal_nt",
750 MCSectionMachO::S_COALESCED |
751 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
752 SectionKind::getText());
754 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
755 SectionKind::getText());
757 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
758 SectionKind::getText());
759 ConstDataSection // .const_data
760 = getMachOSection("__DATA", "__const", 0,
761 SectionKind::getReadOnlyWithRel());
763 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
764 SectionKind::getDataRel());
767 LazySymbolPointerSection
768 = getMachOSection("__DATA", "__la_symbol_ptr",
769 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
770 SectionKind::getMetadata());
771 NonLazySymbolPointerSection
772 = getMachOSection("__DATA", "__nl_symbol_ptr",
773 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
774 SectionKind::getMetadata());
776 if (TM.getRelocationModel() == Reloc::Static) {
778 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
780 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
783 = getMachOSection("__DATA", "__mod_init_func",
784 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
785 SectionKind::getDataRel());
787 = getMachOSection("__DATA", "__mod_term_func",
788 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
789 SectionKind::getDataRel());
792 // Exception Handling.
793 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
794 SectionKind::getDataRel());
796 getMachOSection("__TEXT", "__eh_frame",
797 MCSectionMachO::S_COALESCED |
798 MCSectionMachO::S_ATTR_NO_TOC |
799 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
800 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
801 SectionKind::getReadOnly());
803 // Debug Information.
805 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
806 SectionKind::getMetadata());
808 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
809 SectionKind::getMetadata());
811 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
812 SectionKind::getMetadata());
814 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
815 SectionKind::getMetadata());
816 DwarfPubNamesSection =
817 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
818 SectionKind::getMetadata());
819 DwarfPubTypesSection =
820 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
821 SectionKind::getMetadata());
823 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
824 SectionKind::getMetadata());
826 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
827 SectionKind::getMetadata());
828 DwarfARangesSection =
829 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
830 SectionKind::getMetadata());
832 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
833 SectionKind::getMetadata());
834 DwarfMacroInfoSection =
835 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
836 SectionKind::getMetadata());
837 DwarfDebugInlineSection =
838 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
839 SectionKind::getMetadata());
842 const MCSection *TargetLoweringObjectFileMachO::
843 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
844 Mangler *Mang, const TargetMachine &TM) const {
845 // Parse the section specifier and create it if valid.
846 StringRef Segment, Section;
847 unsigned TAA, StubSize;
848 std::string ErrorCode =
849 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
851 if (!ErrorCode.empty()) {
852 // If invalid, report the error with llvm_report_error.
853 llvm_report_error("Global variable '" + GV->getNameStr() +
854 "' has an invalid section specifier '" + GV->getSection()+
855 "': " + ErrorCode + ".");
856 // Fall back to dropping it into the data section.
861 const MCSectionMachO *S =
862 getMachOSection(Segment, Section, TAA, StubSize, Kind);
864 // Okay, now that we got the section, verify that the TAA & StubSize agree.
865 // If the user declared multiple globals with different section flags, we need
866 // to reject it here.
867 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
868 // If invalid, report the error with llvm_report_error.
869 llvm_report_error("Global variable '" + GV->getNameStr() +
870 "' section type or attributes does not match previous"
871 " section specifier");
877 const MCSection *TargetLoweringObjectFileMachO::
878 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
879 Mangler *Mang, const TargetMachine &TM) const {
880 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
883 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
885 // If this is weak/linkonce, put this in a coalescable section, either in text
886 // or data depending on if it is writable.
887 if (GV->isWeakForLinker()) {
888 if (Kind.isReadOnly())
889 return ConstTextCoalSection;
890 return DataCoalSection;
893 // FIXME: Alignment check should be handled by section classifier.
894 if (Kind.isMergeable1ByteCString() ||
895 Kind.isMergeable2ByteCString()) {
896 if (TM.getTargetData()->getPreferredAlignment(
897 cast<GlobalVariable>(GV)) < 32) {
898 if (Kind.isMergeable1ByteCString())
899 return CStringSection;
900 assert(Kind.isMergeable2ByteCString());
901 return UStringSection;
905 if (Kind.isMergeableConst()) {
906 if (Kind.isMergeableConst4())
907 return FourByteConstantSection;
908 if (Kind.isMergeableConst8())
909 return EightByteConstantSection;
910 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
911 return SixteenByteConstantSection;
914 // Otherwise, if it is readonly, but not something we can specially optimize,
915 // just drop it in .const.
916 if (Kind.isReadOnly())
917 return ReadOnlySection;
919 // If this is marked const, put it into a const section. But if the dynamic
920 // linker needs to write to it, put it in the data segment.
921 if (Kind.isReadOnlyWithRel())
922 return ConstDataSection;
924 // Otherwise, just drop the variable in the normal data section.
929 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
930 // If this constant requires a relocation, we have to put it in the data
931 // segment, not in the text segment.
932 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
933 return ConstDataSection;
935 if (Kind.isMergeableConst4())
936 return FourByteConstantSection;
937 if (Kind.isMergeableConst8())
938 return EightByteConstantSection;
939 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
940 return SixteenByteConstantSection;
941 return ReadOnlySection; // .const
944 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
945 /// not to emit the UsedDirective for some symbols in llvm.used.
946 // FIXME: REMOVE this (rdar://7071300)
947 bool TargetLoweringObjectFileMachO::
948 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
949 /// On Darwin, internally linked data beginning with "L" or "l" does not have
950 /// the directive emitted (this occurs in ObjC metadata).
951 if (!GV) return false;
953 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
954 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
955 // FIXME: ObjC metadata is currently emitted as internal symbols that have
956 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
957 // this horrible hack can go away.
958 const std::string &Name = Mang->getMangledName(GV);
959 if (Name[0] == 'L' || Name[0] == 'l')
966 const MCExpr *TargetLoweringObjectFileMachO::
967 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
968 MachineModuleInfo *MMI,
969 bool &IsIndirect, bool &IsPCRel) const {
970 // The mach-o version of this method defaults to returning a stub reference.
974 SmallString<128> Name;
975 Mang->getNameWithPrefix(Name, GV, true);
976 Name += "$non_lazy_ptr";
977 return MCSymbolRefExpr::Create(Name.str(), getContext());
981 //===----------------------------------------------------------------------===//
983 //===----------------------------------------------------------------------===//
985 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
987 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
988 delete (COFFUniqueMapTy*)UniquingMap;
992 const MCSection *TargetLoweringObjectFileCOFF::
993 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const {
994 // Create the map if it doesn't already exist.
995 if (UniquingMap == 0)
996 UniquingMap = new MachOUniqueMapTy();
997 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
999 // Do the lookup, if we have a hit, return it.
1000 const MCSectionCOFF *&Entry = Map[Name];
1001 if (Entry) return Entry;
1003 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
1006 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1007 const TargetMachine &TM) {
1008 if (UniquingMap != 0)
1009 ((COFFUniqueMapTy*)UniquingMap)->clear();
1010 TargetLoweringObjectFile::Initialize(Ctx, TM);
1011 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1012 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1014 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1016 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1018 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1019 // though it contains relocatable pointers. In PIC mode, this is probably a
1020 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1021 // adjusted or this should be a data section.
1023 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1025 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1028 // FIXME: Don't use 'directive' mode here.
1029 DwarfAbbrevSection =
1030 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1031 true, SectionKind::getMetadata());
1033 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1034 true, SectionKind::getMetadata());
1036 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1037 true, SectionKind::getMetadata());
1039 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1040 true, SectionKind::getMetadata());
1041 DwarfPubNamesSection =
1042 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1043 true, SectionKind::getMetadata());
1044 DwarfPubTypesSection =
1045 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1046 true, SectionKind::getMetadata());
1048 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1049 true, SectionKind::getMetadata());
1051 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1052 true, SectionKind::getMetadata());
1053 DwarfARangesSection =
1054 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1055 true, SectionKind::getMetadata());
1056 DwarfRangesSection =
1057 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1058 true, SectionKind::getMetadata());
1059 DwarfMacroInfoSection =
1060 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1061 true, SectionKind::getMetadata());
1064 const MCSection *TargetLoweringObjectFileCOFF::
1065 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1066 Mangler *Mang, const TargetMachine &TM) const {
1067 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1070 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1072 return ".text$linkonce";
1073 if (Kind.isWriteable())
1074 return ".data$linkonce";
1075 return ".rdata$linkonce";
1079 const MCSection *TargetLoweringObjectFileCOFF::
1080 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1081 Mangler *Mang, const TargetMachine &TM) const {
1082 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1084 // If this global is linkonce/weak and the target handles this by emitting it
1085 // into a 'uniqued' section name, create and return the section now.
1086 if (GV->isWeakForLinker()) {
1087 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1088 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1089 Mang->getNameWithPrefix(Name, GV, false);
1090 return getCOFFSection(Name.str(), false, Kind);
1094 return getTextSection();
1096 return getDataSection();