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/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/ErrorHandling.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 // Variables with common linkage always get classified as common.
145 if (GVar->hasCommonLinkage())
146 return SectionKind::getCommon();
148 // Variable can be easily put to BSS section.
149 if (isSuitableForBSS(GVar))
150 return SectionKind::getBSS();
152 Constant *C = GVar->getInitializer();
154 // If the global is marked constant, we can put it into a mergable section,
155 // a mergable string section, or general .data if it contains relocations.
156 if (GVar->isConstant()) {
157 // If the initializer for the global contains something that requires a
158 // relocation, then we may have to drop this into a wriable data section
159 // even though it is marked const.
160 switch (C->getRelocationInfo()) {
161 default: assert(0 && "unknown relocation info kind");
162 case Constant::NoRelocation:
163 // If initializer is a null-terminated string, put it in a "cstring"
164 // section of the right width.
165 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
166 if (const IntegerType *ITy =
167 dyn_cast<IntegerType>(ATy->getElementType())) {
168 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
169 ITy->getBitWidth() == 32) &&
170 IsNullTerminatedString(C)) {
171 if (ITy->getBitWidth() == 8)
172 return SectionKind::getMergeable1ByteCString();
173 if (ITy->getBitWidth() == 16)
174 return SectionKind::getMergeable2ByteCString();
176 assert(ITy->getBitWidth() == 32 && "Unknown width");
177 return SectionKind::getMergeable4ByteCString();
182 // Otherwise, just drop it into a mergable constant section. If we have
183 // a section for this size, use it, otherwise use the arbitrary sized
185 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
186 case 4: return SectionKind::getMergeableConst4();
187 case 8: return SectionKind::getMergeableConst8();
188 case 16: return SectionKind::getMergeableConst16();
189 default: return SectionKind::getMergeableConst();
192 case Constant::LocalRelocation:
193 // In static relocation model, the linker will resolve all addresses, so
194 // the relocation entries will actually be constants by the time the app
195 // starts up. However, we can't put this into a mergable section, because
196 // the linker doesn't take relocations into consideration when it tries to
197 // merge entries in the section.
198 if (ReloModel == Reloc::Static)
199 return SectionKind::getReadOnly();
201 // Otherwise, the dynamic linker needs to fix it up, put it in the
202 // writable data.rel.local section.
203 return SectionKind::getReadOnlyWithRelLocal();
205 case Constant::GlobalRelocations:
206 // In static relocation model, the linker will resolve all addresses, so
207 // the relocation entries will actually be constants by the time the app
208 // starts up. However, we can't put this into a mergable section, because
209 // the linker doesn't take relocations into consideration when it tries to
210 // merge entries in the section.
211 if (ReloModel == Reloc::Static)
212 return SectionKind::getReadOnly();
214 // Otherwise, the dynamic linker needs to fix it up, put it in the
215 // writable data.rel section.
216 return SectionKind::getReadOnlyWithRel();
220 // Okay, this isn't a constant. If the initializer for the global is going
221 // to require a runtime relocation by the dynamic linker, put it into a more
222 // specific section to improve startup time of the app. This coalesces these
223 // globals together onto fewer pages, improving the locality of the dynamic
225 if (ReloModel == Reloc::Static)
226 return SectionKind::getDataNoRel();
228 switch (C->getRelocationInfo()) {
229 default: assert(0 && "unknown relocation info kind");
230 case Constant::NoRelocation:
231 return SectionKind::getDataNoRel();
232 case Constant::LocalRelocation:
233 return SectionKind::getDataRelLocal();
234 case Constant::GlobalRelocations:
235 return SectionKind::getDataRel();
239 /// SectionForGlobal - This method computes the appropriate section to emit
240 /// the specified global variable or function definition. This should not
241 /// be passed external (or available externally) globals.
242 const MCSection *TargetLoweringObjectFile::
243 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
244 const TargetMachine &TM) const {
245 // Select section name.
246 if (GV->hasSection())
247 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
250 // Use default section depending on the 'type' of global
251 return SelectSectionForGlobal(GV, Kind, Mang, TM);
255 // Lame default implementation. Calculate the section name for global.
257 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
260 const TargetMachine &TM) const{
261 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
264 return getTextSection();
266 if (Kind.isBSS() && BSSSection != 0)
269 if (Kind.isReadOnly() && ReadOnlySection != 0)
270 return ReadOnlySection;
272 return getDataSection();
275 /// getSectionForConstant - Given a mergable constant with the
276 /// specified size and relocation information, return a section that it
277 /// should be placed in.
279 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
280 if (Kind.isReadOnly() && ReadOnlySection != 0)
281 return ReadOnlySection;
286 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
287 /// pc-relative reference to the specified global variable from exception
288 /// handling information. In addition to the symbol, this returns
291 /// IsIndirect - True if the returned symbol is actually a stub that contains
292 /// the address of the symbol, false if the symbol is the global itself.
294 /// IsPCRel - True if the symbol reference is already pc-relative, false if
295 /// the caller needs to subtract off the address of the reference from the
298 const MCExpr *TargetLoweringObjectFile::
299 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
300 MachineModuleInfo *MMI,
301 bool &IsIndirect, bool &IsPCRel) const {
302 // The generic implementation of this just returns a direct reference to the
307 // FIXME: Use GetGlobalValueSymbol.
308 SmallString<128> Name;
309 Mang->getNameWithPrefix(Name, GV, false);
310 return MCSymbolRefExpr::Create(Name.str(), getContext());
314 //===----------------------------------------------------------------------===//
316 //===----------------------------------------------------------------------===//
317 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
319 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
320 // If we have the section uniquing map, free it.
321 delete (ELFUniqueMapTy*)UniquingMap;
324 const MCSection *TargetLoweringObjectFileELF::
325 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
326 SectionKind Kind, bool IsExplicit) const {
327 if (UniquingMap == 0)
328 UniquingMap = new ELFUniqueMapTy();
329 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
331 // Do the lookup, if we have a hit, return it.
332 const MCSectionELF *&Entry = Map[Section];
333 if (Entry) return Entry;
335 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
339 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
340 const TargetMachine &TM) {
341 if (UniquingMap != 0)
342 ((ELFUniqueMapTy*)UniquingMap)->clear();
343 TargetLoweringObjectFile::Initialize(Ctx, TM);
346 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
347 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
348 SectionKind::getBSS());
351 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
352 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
353 SectionKind::getText());
356 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
357 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
358 SectionKind::getDataRel());
361 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
362 MCSectionELF::SHF_ALLOC,
363 SectionKind::getReadOnly());
366 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
367 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
368 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
371 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
372 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
373 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
376 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
377 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
378 SectionKind::getDataRel());
380 DataRelLocalSection =
381 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
382 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
383 SectionKind::getDataRelLocal());
386 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
387 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
388 SectionKind::getReadOnlyWithRel());
390 DataRelROLocalSection =
391 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
392 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
393 SectionKind::getReadOnlyWithRelLocal());
395 MergeableConst4Section =
396 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
397 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
398 SectionKind::getMergeableConst4());
400 MergeableConst8Section =
401 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
402 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
403 SectionKind::getMergeableConst8());
405 MergeableConst16Section =
406 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
407 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
408 SectionKind::getMergeableConst16());
411 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
412 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
413 SectionKind::getDataRel());
416 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
417 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
418 SectionKind::getDataRel());
420 // Exception Handling Sections.
422 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
423 // it contains relocatable pointers. In PIC mode, this is probably a big
424 // runtime hit for C++ apps. Either the contents of the LSDA need to be
425 // adjusted or this should be a data section.
427 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
428 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
430 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
431 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
432 SectionKind::getDataRel());
434 // Debug Info Sections.
436 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
437 SectionKind::getMetadata());
439 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
440 SectionKind::getMetadata());
442 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
443 SectionKind::getMetadata());
445 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
446 SectionKind::getMetadata());
447 DwarfPubNamesSection =
448 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
449 SectionKind::getMetadata());
450 DwarfPubTypesSection =
451 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
452 SectionKind::getMetadata());
454 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
455 SectionKind::getMetadata());
457 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
458 SectionKind::getMetadata());
459 DwarfARangesSection =
460 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
461 SectionKind::getMetadata());
463 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
464 SectionKind::getMetadata());
465 DwarfMacroInfoSection =
466 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
467 SectionKind::getMetadata());
472 getELFKindForNamedSection(const char *Name, SectionKind K) {
473 if (Name[0] != '.') return K;
475 // Some lame default implementation based on some magic section names.
476 if (strcmp(Name, ".bss") == 0 ||
477 strncmp(Name, ".bss.", 5) == 0 ||
478 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
479 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
480 strcmp(Name, ".sbss") == 0 ||
481 strncmp(Name, ".sbss.", 6) == 0 ||
482 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
483 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
484 return SectionKind::getBSS();
486 if (strcmp(Name, ".tdata") == 0 ||
487 strncmp(Name, ".tdata.", 7) == 0 ||
488 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
489 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
490 return SectionKind::getThreadData();
492 if (strcmp(Name, ".tbss") == 0 ||
493 strncmp(Name, ".tbss.", 6) == 0 ||
494 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
495 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
496 return SectionKind::getThreadBSS();
502 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
504 if (Name == ".init_array")
505 return MCSectionELF::SHT_INIT_ARRAY;
507 if (Name == ".fini_array")
508 return MCSectionELF::SHT_FINI_ARRAY;
510 if (Name == ".preinit_array")
511 return MCSectionELF::SHT_PREINIT_ARRAY;
513 if (K.isBSS() || K.isThreadBSS())
514 return MCSectionELF::SHT_NOBITS;
516 return MCSectionELF::SHT_PROGBITS;
521 getELFSectionFlags(SectionKind K) {
525 Flags |= MCSectionELF::SHF_ALLOC;
528 Flags |= MCSectionELF::SHF_EXECINSTR;
531 Flags |= MCSectionELF::SHF_WRITE;
533 if (K.isThreadLocal())
534 Flags |= MCSectionELF::SHF_TLS;
536 // K.isMergeableConst() is left out to honour PR4650
537 if (K.isMergeableCString() || K.isMergeableConst4() ||
538 K.isMergeableConst8() || K.isMergeableConst16())
539 Flags |= MCSectionELF::SHF_MERGE;
541 if (K.isMergeableCString())
542 Flags |= MCSectionELF::SHF_STRINGS;
548 const MCSection *TargetLoweringObjectFileELF::
549 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
550 Mangler *Mang, const TargetMachine &TM) const {
551 const char *SectionName = GV->getSection().c_str();
553 // Infer section flags from the section name if we can.
554 Kind = getELFKindForNamedSection(SectionName, Kind);
556 return getELFSection(SectionName,
557 getELFSectionType(SectionName, Kind),
558 getELFSectionFlags(Kind), Kind, true);
561 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
562 if (Kind.isText()) return ".gnu.linkonce.t.";
563 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
565 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
566 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
568 if (Kind.isBSS()) return ".gnu.linkonce.b.";
569 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
570 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
571 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
572 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
574 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
575 return ".gnu.linkonce.d.rel.ro.";
578 const MCSection *TargetLoweringObjectFileELF::
579 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
580 Mangler *Mang, const TargetMachine &TM) const {
582 // If this global is linkonce/weak and the target handles this by emitting it
583 // into a 'uniqued' section name, create and return the section now.
584 if (GV->isWeakForLinker() && !Kind.isCommon()) {
585 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
586 SmallString<128> Name;
587 Name.append(Prefix, Prefix+strlen(Prefix));
588 Mang->getNameWithPrefix(Name, GV, false);
589 return getELFSection(Name.str(), getELFSectionType(Name.str(), Kind),
590 getELFSectionFlags(Kind), Kind);
593 if (Kind.isText()) return TextSection;
595 if (Kind.isMergeable1ByteCString() ||
596 Kind.isMergeable2ByteCString() ||
597 Kind.isMergeable4ByteCString()) {
599 // We also need alignment here.
600 // FIXME: this is getting the alignment of the character, not the
601 // alignment of the global!
603 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
605 const char *SizeSpec = ".rodata.str1.";
606 if (Kind.isMergeable2ByteCString())
607 SizeSpec = ".rodata.str2.";
608 else if (Kind.isMergeable4ByteCString())
609 SizeSpec = ".rodata.str4.";
611 assert(Kind.isMergeable1ByteCString() && "unknown string width");
614 std::string Name = SizeSpec + utostr(Align);
615 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
616 MCSectionELF::SHF_ALLOC |
617 MCSectionELF::SHF_MERGE |
618 MCSectionELF::SHF_STRINGS,
622 if (Kind.isMergeableConst()) {
623 if (Kind.isMergeableConst4() && MergeableConst4Section)
624 return MergeableConst4Section;
625 if (Kind.isMergeableConst8() && MergeableConst8Section)
626 return MergeableConst8Section;
627 if (Kind.isMergeableConst16() && MergeableConst16Section)
628 return MergeableConst16Section;
629 return ReadOnlySection; // .const
632 if (Kind.isReadOnly()) return ReadOnlySection;
634 if (Kind.isThreadData()) return TLSDataSection;
635 if (Kind.isThreadBSS()) return TLSBSSSection;
637 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
639 if (Kind.isDataNoRel()) return DataSection;
640 if (Kind.isDataRelLocal()) return DataRelLocalSection;
641 if (Kind.isDataRel()) return DataRelSection;
642 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
644 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
645 return DataRelROSection;
648 /// getSectionForConstant - Given a mergeable constant with the
649 /// specified size and relocation information, return a section that it
650 /// should be placed in.
651 const MCSection *TargetLoweringObjectFileELF::
652 getSectionForConstant(SectionKind Kind) const {
653 if (Kind.isMergeableConst4() && MergeableConst4Section)
654 return MergeableConst4Section;
655 if (Kind.isMergeableConst8() && MergeableConst8Section)
656 return MergeableConst8Section;
657 if (Kind.isMergeableConst16() && MergeableConst16Section)
658 return MergeableConst16Section;
659 if (Kind.isReadOnly())
660 return ReadOnlySection;
662 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
663 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
664 return DataRelROSection;
667 //===----------------------------------------------------------------------===//
669 //===----------------------------------------------------------------------===//
671 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
673 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
674 // If we have the MachO uniquing map, free it.
675 delete (MachOUniqueMapTy*)UniquingMap;
679 const MCSectionMachO *TargetLoweringObjectFileMachO::
680 getMachOSection(StringRef Segment, StringRef Section,
681 unsigned TypeAndAttributes,
682 unsigned Reserved2, SectionKind Kind) const {
683 // We unique sections by their segment/section pair. The returned section
684 // may not have the same flags as the requested section, if so this should be
685 // diagnosed by the client as an error.
687 // Create the map if it doesn't already exist.
688 if (UniquingMap == 0)
689 UniquingMap = new MachOUniqueMapTy();
690 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
692 // Form the name to look up.
693 SmallString<64> Name;
698 // Do the lookup, if we have a hit, return it.
699 const MCSectionMachO *&Entry = Map[Name.str()];
700 if (Entry) return Entry;
702 // Otherwise, return a new section.
703 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
704 Reserved2, Kind, getContext());
708 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
709 const TargetMachine &TM) {
710 if (UniquingMap != 0)
711 ((MachOUniqueMapTy*)UniquingMap)->clear();
712 TargetLoweringObjectFile::Initialize(Ctx, TM);
715 = getMachOSection("__TEXT", "__text",
716 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
717 SectionKind::getText());
719 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
721 CStringSection // .cstring
722 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
723 SectionKind::getMergeable1ByteCString());
725 = getMachOSection("__TEXT","__ustring", 0,
726 SectionKind::getMergeable2ByteCString());
727 FourByteConstantSection // .literal4
728 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
729 SectionKind::getMergeableConst4());
730 EightByteConstantSection // .literal8
731 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
732 SectionKind::getMergeableConst8());
734 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
735 // to using it in -static mode.
736 SixteenByteConstantSection = 0;
737 if (TM.getRelocationModel() != Reloc::Static &&
738 TM.getTargetData()->getPointerSize() == 32)
739 SixteenByteConstantSection = // .literal16
740 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
741 SectionKind::getMergeableConst16());
743 ReadOnlySection // .const
744 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
747 = getMachOSection("__TEXT", "__textcoal_nt",
748 MCSectionMachO::S_COALESCED |
749 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
750 SectionKind::getText());
752 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
753 SectionKind::getText());
755 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
756 SectionKind::getText());
758 = getMachOSection("__DATA","__common", MCSectionMachO::S_ZEROFILL,
759 SectionKind::getBSS());
760 ConstDataSection // .const_data
761 = getMachOSection("__DATA", "__const", 0,
762 SectionKind::getReadOnlyWithRel());
764 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
765 SectionKind::getDataRel());
768 LazySymbolPointerSection
769 = getMachOSection("__DATA", "__la_symbol_ptr",
770 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
771 SectionKind::getMetadata());
772 NonLazySymbolPointerSection
773 = getMachOSection("__DATA", "__nl_symbol_ptr",
774 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
775 SectionKind::getMetadata());
777 if (TM.getRelocationModel() == Reloc::Static) {
779 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
781 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
784 = getMachOSection("__DATA", "__mod_init_func",
785 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
786 SectionKind::getDataRel());
788 = getMachOSection("__DATA", "__mod_term_func",
789 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
790 SectionKind::getDataRel());
793 // Exception Handling.
794 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
795 SectionKind::getDataRel());
797 getMachOSection("__TEXT", "__eh_frame",
798 MCSectionMachO::S_COALESCED |
799 MCSectionMachO::S_ATTR_NO_TOC |
800 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
801 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
802 SectionKind::getReadOnly());
804 // Debug Information.
806 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
807 SectionKind::getMetadata());
809 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
810 SectionKind::getMetadata());
812 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
813 SectionKind::getMetadata());
815 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
816 SectionKind::getMetadata());
817 DwarfPubNamesSection =
818 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
819 SectionKind::getMetadata());
820 DwarfPubTypesSection =
821 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
822 SectionKind::getMetadata());
824 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
825 SectionKind::getMetadata());
827 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
828 SectionKind::getMetadata());
829 DwarfARangesSection =
830 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
831 SectionKind::getMetadata());
833 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
834 SectionKind::getMetadata());
835 DwarfMacroInfoSection =
836 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
837 SectionKind::getMetadata());
838 DwarfDebugInlineSection =
839 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
840 SectionKind::getMetadata());
843 const MCSection *TargetLoweringObjectFileMachO::
844 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
845 Mangler *Mang, const TargetMachine &TM) const {
846 // Parse the section specifier and create it if valid.
847 StringRef Segment, Section;
848 unsigned TAA, StubSize;
849 std::string ErrorCode =
850 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
852 if (!ErrorCode.empty()) {
853 // If invalid, report the error with llvm_report_error.
854 llvm_report_error("Global variable '" + GV->getNameStr() +
855 "' has an invalid section specifier '" + GV->getSection()+
856 "': " + ErrorCode + ".");
857 // Fall back to dropping it into the data section.
862 const MCSectionMachO *S =
863 getMachOSection(Segment, Section, TAA, StubSize, Kind);
865 // Okay, now that we got the section, verify that the TAA & StubSize agree.
866 // If the user declared multiple globals with different section flags, we need
867 // to reject it here.
868 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
869 // If invalid, report the error with llvm_report_error.
870 llvm_report_error("Global variable '" + GV->getNameStr() +
871 "' section type or attributes does not match previous"
872 " section specifier");
878 const MCSection *TargetLoweringObjectFileMachO::
879 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
880 Mangler *Mang, const TargetMachine &TM) const {
881 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
884 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
886 // If this is weak/linkonce, put this in a coalescable section, either in text
887 // or data depending on if it is writable.
888 if (GV->isWeakForLinker()) {
889 if (Kind.isReadOnly())
890 return ConstTextCoalSection;
891 return DataCoalSection;
894 // FIXME: Alignment check should be handled by section classifier.
895 if (Kind.isMergeable1ByteCString() ||
896 Kind.isMergeable2ByteCString()) {
897 if (TM.getTargetData()->getPreferredAlignment(
898 cast<GlobalVariable>(GV)) < 32) {
899 if (Kind.isMergeable1ByteCString())
900 return CStringSection;
901 assert(Kind.isMergeable2ByteCString());
902 return UStringSection;
906 if (Kind.isMergeableConst()) {
907 if (Kind.isMergeableConst4())
908 return FourByteConstantSection;
909 if (Kind.isMergeableConst8())
910 return EightByteConstantSection;
911 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
912 return SixteenByteConstantSection;
915 // Otherwise, if it is readonly, but not something we can specially optimize,
916 // just drop it in .const.
917 if (Kind.isReadOnly())
918 return ReadOnlySection;
920 // If this is marked const, put it into a const section. But if the dynamic
921 // linker needs to write to it, put it in the data segment.
922 if (Kind.isReadOnlyWithRel())
923 return ConstDataSection;
925 // Put zero initialized globals with strong external linkage in the
926 // DATA, __common section with the .zerofill directive.
927 if (Kind.isBSS() && GV->hasExternalLinkage())
928 return DataCommonSection;
930 // Otherwise, just drop the variable in the normal data section.
935 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
936 // If this constant requires a relocation, we have to put it in the data
937 // segment, not in the text segment.
938 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
939 return ConstDataSection;
941 if (Kind.isMergeableConst4())
942 return FourByteConstantSection;
943 if (Kind.isMergeableConst8())
944 return EightByteConstantSection;
945 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
946 return SixteenByteConstantSection;
947 return ReadOnlySection; // .const
950 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
951 /// not to emit the UsedDirective for some symbols in llvm.used.
952 // FIXME: REMOVE this (rdar://7071300)
953 bool TargetLoweringObjectFileMachO::
954 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
955 /// On Darwin, internally linked data beginning with "L" or "l" does not have
956 /// the directive emitted (this occurs in ObjC metadata).
957 if (!GV) return false;
959 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
960 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
961 // FIXME: ObjC metadata is currently emitted as internal symbols that have
962 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
963 // this horrible hack can go away.
964 SmallString<64> Name;
965 Mang->getNameWithPrefix(Name, GV, false);
966 if (Name[0] == 'L' || Name[0] == 'l')
973 const MCExpr *TargetLoweringObjectFileMachO::
974 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
975 MachineModuleInfo *MMI,
976 bool &IsIndirect, bool &IsPCRel) const {
977 // The mach-o version of this method defaults to returning a stub reference.
981 SmallString<128> Name;
982 Mang->getNameWithPrefix(Name, GV, true);
983 Name += "$non_lazy_ptr";
984 return MCSymbolRefExpr::Create(Name.str(), getContext());
988 //===----------------------------------------------------------------------===//
990 //===----------------------------------------------------------------------===//
992 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
994 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
995 delete (COFFUniqueMapTy*)UniquingMap;
999 const MCSection *TargetLoweringObjectFileCOFF::
1000 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const {
1001 // Create the map if it doesn't already exist.
1002 if (UniquingMap == 0)
1003 UniquingMap = new MachOUniqueMapTy();
1004 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
1006 // Do the lookup, if we have a hit, return it.
1007 const MCSectionCOFF *&Entry = Map[Name];
1008 if (Entry) return Entry;
1010 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
1013 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1014 const TargetMachine &TM) {
1015 if (UniquingMap != 0)
1016 ((COFFUniqueMapTy*)UniquingMap)->clear();
1017 TargetLoweringObjectFile::Initialize(Ctx, TM);
1018 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1019 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1021 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1023 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1025 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1026 // though it contains relocatable pointers. In PIC mode, this is probably a
1027 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1028 // adjusted or this should be a data section.
1030 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1032 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1035 // FIXME: Don't use 'directive' mode here.
1036 DwarfAbbrevSection =
1037 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1038 true, SectionKind::getMetadata());
1040 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1041 true, SectionKind::getMetadata());
1043 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1044 true, SectionKind::getMetadata());
1046 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1047 true, SectionKind::getMetadata());
1048 DwarfPubNamesSection =
1049 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1050 true, SectionKind::getMetadata());
1051 DwarfPubTypesSection =
1052 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1053 true, SectionKind::getMetadata());
1055 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1056 true, SectionKind::getMetadata());
1058 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1059 true, SectionKind::getMetadata());
1060 DwarfARangesSection =
1061 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1062 true, SectionKind::getMetadata());
1063 DwarfRangesSection =
1064 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1065 true, SectionKind::getMetadata());
1066 DwarfMacroInfoSection =
1067 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1068 true, SectionKind::getMetadata());
1071 const MCSection *TargetLoweringObjectFileCOFF::
1072 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1073 Mangler *Mang, const TargetMachine &TM) const {
1074 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1077 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1079 return ".text$linkonce";
1080 if (Kind.isWriteable())
1081 return ".data$linkonce";
1082 return ".rdata$linkonce";
1086 const MCSection *TargetLoweringObjectFileCOFF::
1087 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1088 Mangler *Mang, const TargetMachine &TM) const {
1089 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1091 // If this global is linkonce/weak and the target handles this by emitting it
1092 // into a 'uniqued' section name, create and return the section now.
1093 if (GV->isWeakForLinker()) {
1094 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1095 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1096 Mang->getNameWithPrefix(Name, GV, false);
1097 return getCOFFSection(Name.str(), false, Kind);
1101 return getTextSection();
1103 return getDataSection();