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/GlobalVariable.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/ADT/StringExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
37 StaticCtorSection = 0;
38 StaticDtorSection = 0;
41 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
44 static bool isSuitableForBSS(const GlobalVariable *GV) {
45 Constant *C = GV->getInitializer();
47 // Must have zero initializer.
48 if (!C->isNullValue())
51 // Leave constant zeros in readonly constant sections, so they can be shared.
55 // If the global has an explicit section specified, don't put it in BSS.
56 if (!GV->getSection().empty())
59 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
63 // Otherwise, put it in BSS!
67 static bool isConstantString(const Constant *C) {
68 // First check: is we have constant array of i8 terminated with zero
69 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
70 // Check, if initializer is a null-terminated string
71 if (CVA && CVA->isCString())
74 // Another possibility: [1 x i8] zeroinitializer
75 if (isa<ConstantAggregateZero>(C))
76 if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
77 return (Ty->getElementType() == Type::Int8Ty &&
78 Ty->getNumElements() == 1);
83 /// SectionKindForGlobal - This is a top-level target-independent classifier for
84 /// a global variable. Given an global variable and information from TM, it
85 /// classifies the global in a variety of ways that make various target
86 /// implementations simpler. The target implementation is free to ignore this
87 /// extra info of course.
88 static SectionKind SectionKindForGlobal(const GlobalValue *GV,
89 const TargetMachine &TM) {
90 Reloc::Model ReloModel = TM.getRelocationModel();
92 // Early exit - functions should be always in text sections.
93 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
95 return SectionKind::getText();
98 // Handle thread-local data first.
99 if (GVar->isThreadLocal()) {
100 if (isSuitableForBSS(GVar))
101 return SectionKind::getThreadBSS();
102 return SectionKind::getThreadData();
105 // Variable can be easily put to BSS section.
106 if (isSuitableForBSS(GVar))
107 return SectionKind::getBSS();
109 Constant *C = GVar->getInitializer();
111 // If the global is marked constant, we can put it into a mergable section,
112 // a mergable string section, or general .data if it contains relocations.
113 if (GVar->isConstant()) {
114 // If the initializer for the global contains something that requires a
115 // relocation, then we may have to drop this into a wriable data section
116 // even though it is marked const.
117 switch (C->getRelocationInfo()) {
118 default: llvm_unreachable("unknown relocation info kind");
119 case Constant::NoRelocation:
120 // If initializer is a null-terminated string, put it in a "cstring"
121 // section if the target has it.
122 if (isConstantString(C))
123 return SectionKind::getMergeableCString();
125 // Otherwise, just drop it into a mergable constant section. If we have
126 // a section for this size, use it, otherwise use the arbitrary sized
128 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
129 case 4: return SectionKind::getMergeableConst4();
130 case 8: return SectionKind::getMergeableConst8();
131 case 16: return SectionKind::getMergeableConst16();
132 default: return SectionKind::getMergeableConst();
135 case Constant::LocalRelocation:
136 // In static relocation model, the linker will resolve all addresses, so
137 // the relocation entries will actually be constants by the time the app
138 // starts up. However, we can't put this into a mergable section, because
139 // the linker doesn't take relocations into consideration when it tries to
140 // merge entries in the section.
141 if (ReloModel == Reloc::Static)
142 return SectionKind::getReadOnly();
144 // Otherwise, the dynamic linker needs to fix it up, put it in the
145 // writable data.rel.local section.
146 return SectionKind::getReadOnlyWithRelLocal();
148 case Constant::GlobalRelocations:
149 // In static relocation model, the linker will resolve all addresses, so
150 // the relocation entries will actually be constants by the time the app
151 // starts up. However, we can't put this into a mergable section, because
152 // the linker doesn't take relocations into consideration when it tries to
153 // merge entries in the section.
154 if (ReloModel == Reloc::Static)
155 return SectionKind::getReadOnly();
157 // Otherwise, the dynamic linker needs to fix it up, put it in the
158 // writable data.rel section.
159 return SectionKind::getReadOnlyWithRel();
163 // Okay, this isn't a constant. If the initializer for the global is going
164 // to require a runtime relocation by the dynamic linker, put it into a more
165 // specific section to improve startup time of the app. This coalesces these
166 // globals together onto fewer pages, improving the locality of the dynamic
168 if (ReloModel == Reloc::Static)
169 return SectionKind::getDataNoRel();
171 switch (C->getRelocationInfo()) {
172 default: llvm_unreachable("unknown relocation info kind");
173 case Constant::NoRelocation:
174 return SectionKind::getDataNoRel();
175 case Constant::LocalRelocation:
176 return SectionKind::getDataRelLocal();
177 case Constant::GlobalRelocations:
178 return SectionKind::getDataRel();
182 /// SectionForGlobal - This method computes the appropriate section to emit
183 /// the specified global variable or function definition. This should not
184 /// be passed external (or available externally) globals.
185 const MCSection *TargetLoweringObjectFile::
186 SectionForGlobal(const GlobalValue *GV, Mangler *Mang,
187 const TargetMachine &TM) const {
188 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
189 "Can only be used for global definitions");
191 SectionKind Kind = SectionKindForGlobal(GV, TM);
193 // Select section name.
194 if (GV->hasSection()) {
195 // If the target has special section hacks for specifically named globals,
197 if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Kind))
200 // If the target has magic semantics for certain section names, make sure to
201 // pick up the flags. This allows the user to write things with attribute
202 // section and still get the appropriate section flags printed.
203 Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
205 return getOrCreateSection(GV->getSection().c_str(), false, Kind);
209 // Use default section depending on the 'type' of global
210 return SelectSectionForGlobal(GV, Kind, Mang, TM);
213 // Lame default implementation. Calculate the section name for global.
215 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
218 const TargetMachine &TM) const{
219 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
222 return getTextSection();
224 if (Kind.isBSS() && BSSSection != 0)
227 if (Kind.isReadOnly() && ReadOnlySection != 0)
228 return ReadOnlySection;
230 return getDataSection();
233 /// getSectionForConstant - Given a mergable constant with the
234 /// specified size and relocation information, return a section that it
235 /// should be placed in.
237 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
238 if (Kind.isReadOnly() && ReadOnlySection != 0)
239 return ReadOnlySection;
245 const MCSection *TargetLoweringObjectFile::
246 getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
247 if (MCSection *S = Ctx->GetSection(Name))
249 return MCSection::Create(Name, isDirective, Kind, *Ctx);
254 //===----------------------------------------------------------------------===//
256 //===----------------------------------------------------------------------===//
258 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
259 const TargetMachine &TM) {
260 TargetLoweringObjectFile::Initialize(Ctx, TM);
262 BSSSection = getOrCreateSection("\t.bss", true, SectionKind::getBSS());
264 // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
265 // FIXME: Does .section .bss work everywhere??
266 // FIXME2: this should just be handle by the section printer. We should get
267 // away from syntactic view of the sections and MCSection should just be a
269 BSSSection = getOrCreateSection("\t.bss", false, SectionKind::getBSS());
272 TextSection = getOrCreateSection("\t.text", true, SectionKind::getText());
273 DataSection = getOrCreateSection("\t.data", true, SectionKind::getDataRel());
275 getOrCreateSection("\t.rodata", false, SectionKind::getReadOnly());
277 getOrCreateSection("\t.tdata", false, SectionKind::getThreadData());
278 CStringSection = getOrCreateSection("\t.rodata.str", true,
279 SectionKind::getMergeableCString());
281 TLSBSSSection = getOrCreateSection("\t.tbss", false,
282 SectionKind::getThreadBSS());
284 DataRelSection = getOrCreateSection("\t.data.rel", false,
285 SectionKind::getDataRel());
286 DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
287 SectionKind::getDataRelLocal());
288 DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
289 SectionKind::getReadOnlyWithRel());
290 DataRelROLocalSection =
291 getOrCreateSection("\t.data.rel.ro.local", false,
292 SectionKind::getReadOnlyWithRelLocal());
294 MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
295 SectionKind::getMergeableConst4());
296 MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
297 SectionKind::getMergeableConst8());
298 MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
299 SectionKind::getMergeableConst16());
302 getOrCreateSection(".ctors", false, SectionKind::getDataRel());
304 getOrCreateSection(".dtors", false, SectionKind::getDataRel());
308 SectionKind TargetLoweringObjectFileELF::
309 getKindForNamedSection(const char *Name, SectionKind K) const {
310 if (Name[0] != '.') return K;
312 // Some lame default implementation based on some magic section names.
313 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
314 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
315 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
316 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
317 return SectionKind::getBSS();
319 if (strcmp(Name, ".tdata") == 0 ||
320 strncmp(Name, ".tdata.", 7) == 0 ||
321 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
322 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
323 return SectionKind::getThreadData();
325 if (strcmp(Name, ".tbss") == 0 ||
326 strncmp(Name, ".tbss.", 6) == 0 ||
327 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
328 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
329 return SectionKind::getThreadBSS();
334 void TargetLoweringObjectFileELF::
335 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
339 if (!Kind.isMetadata())
343 if (Kind.isWriteable())
345 if (Kind.isMergeableCString() ||
346 Kind.isMergeableConst4() ||
347 Kind.isMergeableConst8() ||
348 Kind.isMergeableConst16())
350 if (Kind.isMergeableCString())
352 if (Kind.isThreadLocal())
358 // If comment string is '@', e.g. as on ARM - use '%' instead
365 if (Kind.isBSS() || Kind.isThreadBSS())
368 KindStr = "progbits";
370 Str.append(KindStr, KindStr+strlen(KindStr));
372 if (Kind.isMergeableCString()) {
373 // TODO: Eventually handle multiple byte character strings. For now, all
374 // mergable C strings are single byte.
377 } else if (Kind.isMergeableConst4()) {
380 } else if (Kind.isMergeableConst8()) {
383 } else if (Kind.isMergeableConst16()) {
391 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
392 if (Kind.isText()) return ".gnu.linkonce.t.";
393 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
395 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
396 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
398 if (Kind.isBSS()) return ".gnu.linkonce.b.";
399 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
400 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
401 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
402 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
404 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
405 return ".gnu.linkonce.d.rel.ro.";
408 const MCSection *TargetLoweringObjectFileELF::
409 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
410 Mangler *Mang, const TargetMachine &TM) const {
412 // If this global is linkonce/weak and the target handles this by emitting it
413 // into a 'uniqued' section name, create and return the section now.
414 if (GV->isWeakForLinker()) {
415 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
416 std::string Name = Mang->makeNameProper(GV->getNameStr());
417 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
420 if (Kind.isText()) return TextSection;
422 if (Kind.isMergeableCString()) {
423 assert(CStringSection && "Should have string section prefix");
425 // We also need alignment here.
426 // FIXME: this is getting the alignment of the character, not the
427 // alignment of the global!
429 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
431 std::string Name = CStringSection->getName() + "1." + utostr(Align);
432 return getOrCreateSection(Name.c_str(), false,
433 SectionKind::getMergeableCString());
436 if (Kind.isMergeableConst()) {
437 if (Kind.isMergeableConst4())
438 return MergeableConst4Section;
439 if (Kind.isMergeableConst8())
440 return MergeableConst8Section;
441 if (Kind.isMergeableConst16())
442 return MergeableConst16Section;
443 return ReadOnlySection; // .const
446 if (Kind.isReadOnly()) return ReadOnlySection;
448 if (Kind.isThreadData()) return TLSDataSection;
449 if (Kind.isThreadBSS()) return TLSBSSSection;
451 if (Kind.isBSS()) return BSSSection;
453 if (Kind.isDataNoRel()) return DataSection;
454 if (Kind.isDataRelLocal()) return DataRelLocalSection;
455 if (Kind.isDataRel()) return DataRelSection;
456 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
458 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
459 return DataRelROSection;
462 /// getSectionForConstant - Given a mergeable constant with the
463 /// specified size and relocation information, return a section that it
464 /// should be placed in.
465 const MCSection *TargetLoweringObjectFileELF::
466 getSectionForConstant(SectionKind Kind) const {
467 if (Kind.isMergeableConst4())
468 return MergeableConst4Section;
469 if (Kind.isMergeableConst8())
470 return MergeableConst8Section;
471 if (Kind.isMergeableConst16())
472 return MergeableConst16Section;
473 if (Kind.isReadOnly())
474 return ReadOnlySection;
476 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
477 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
478 return DataRelROSection;
481 //===----------------------------------------------------------------------===//
483 //===----------------------------------------------------------------------===//
485 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
486 const TargetMachine &TM) {
487 TargetLoweringObjectFile::Initialize(Ctx, TM);
488 TextSection = getOrCreateSection("\t.text", true,
489 SectionKind::getText());
490 DataSection = getOrCreateSection("\t.data", true,
491 SectionKind::getDataRel());
493 CStringSection = getOrCreateSection("\t.cstring", true,
494 SectionKind::getMergeableCString());
495 FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
496 SectionKind::getMergeableConst4());
497 EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
498 SectionKind::getMergeableConst8());
500 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
501 // to using it in -static mode.
502 if (TM.getRelocationModel() != Reloc::Static &&
503 TM.getTargetData()->getPointerSize() == 32)
504 SixteenByteConstantSection =
505 getOrCreateSection("\t.literal16\n", true,
506 SectionKind::getMergeableConst16());
508 SixteenByteConstantSection = 0;
510 ReadOnlySection = getOrCreateSection("\t.const", true,
511 SectionKind::getReadOnly());
514 getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
515 false, SectionKind::getText());
516 ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
518 SectionKind::getText());
519 ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
521 SectionKind::getText());
522 ConstDataSection = getOrCreateSection("\t.const_data", true,
523 SectionKind::getReadOnlyWithRel());
524 DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
526 SectionKind::getDataRel());
528 if (TM.getRelocationModel() == Reloc::Static) {
530 getOrCreateSection(".constructor", true, SectionKind::getDataRel());
532 getOrCreateSection(".destructor", true, SectionKind::getDataRel());
535 getOrCreateSection(".mod_init_func", true, SectionKind::getDataRel());
537 getOrCreateSection(".mod_term_func", true, SectionKind::getDataRel());
542 const MCSection *TargetLoweringObjectFileMachO::
543 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
544 Mangler *Mang, const TargetMachine &TM) const {
545 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
548 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
550 // If this is weak/linkonce, put this in a coalescable section, either in text
551 // or data depending on if it is writable.
552 if (GV->isWeakForLinker()) {
553 if (Kind.isReadOnly())
554 return ConstTextCoalSection;
555 return DataCoalSection;
558 // FIXME: Alignment check should be handled by section classifier.
559 if (Kind.isMergeableCString()) {
560 Constant *C = cast<GlobalVariable>(GV)->getInitializer();
561 const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
562 const TargetData &TD = *TM.getTargetData();
563 unsigned Size = TD.getTypeAllocSize(Ty);
565 unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
567 return CStringSection;
570 return ReadOnlySection;
573 if (Kind.isMergeableConst()) {
574 if (Kind.isMergeableConst4())
575 return FourByteConstantSection;
576 if (Kind.isMergeableConst8())
577 return EightByteConstantSection;
578 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
579 return SixteenByteConstantSection;
580 return ReadOnlySection; // .const
583 // FIXME: ROData -> const in -static mode that is relocatable but they happen
584 // by the static linker. Why not mergeable?
585 if (Kind.isReadOnly())
586 return ReadOnlySection;
588 // If this is marked const, put it into a const section. But if the dynamic
589 // linker needs to write to it, put it in the data segment.
590 if (Kind.isReadOnlyWithRel())
591 return ConstDataSection;
593 // Otherwise, just drop the variable in the normal data section.
598 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
599 // If this constant requires a relocation, we have to put it in the data
600 // segment, not in the text segment.
601 if (Kind.isDataRel())
602 return ConstDataSection;
604 if (Kind.isMergeableConst4())
605 return FourByteConstantSection;
606 if (Kind.isMergeableConst8())
607 return EightByteConstantSection;
608 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
609 return SixteenByteConstantSection;
610 return ReadOnlySection; // .const
613 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
614 /// not to emit the UsedDirective for some symbols in llvm.used.
615 // FIXME: REMOVE this (rdar://7071300)
616 bool TargetLoweringObjectFileMachO::
617 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
618 /// On Darwin, internally linked data beginning with "L" or "l" does not have
619 /// the directive emitted (this occurs in ObjC metadata).
620 if (!GV) return false;
622 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
623 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
624 // FIXME: ObjC metadata is currently emitted as internal symbols that have
625 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
626 // this horrible hack can go away.
627 const std::string &Name = Mang->getMangledName(GV);
628 if (Name[0] == 'L' || Name[0] == 'l')
636 //===----------------------------------------------------------------------===//
638 //===----------------------------------------------------------------------===//
640 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
641 const TargetMachine &TM) {
642 TargetLoweringObjectFile::Initialize(Ctx, TM);
643 TextSection = getOrCreateSection("\t.text", true,
644 SectionKind::getText());
645 DataSection = getOrCreateSection("\t.data", true,
646 SectionKind::getDataRel());
648 getOrCreateSection(".ctors", false, SectionKind::getDataRel());
650 getOrCreateSection(".dtors", false, SectionKind::getDataRel());
653 void TargetLoweringObjectFileCOFF::
654 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
655 // FIXME: Inefficient.
656 std::string Res = ",\"";
659 if (Kind.isWriteable())
663 Str.append(Res.begin(), Res.end());
666 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
668 return ".text$linkonce";
669 if (Kind.isWriteable())
670 return ".data$linkonce";
671 return ".rdata$linkonce";
675 const MCSection *TargetLoweringObjectFileCOFF::
676 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
677 Mangler *Mang, const TargetMachine &TM) const {
678 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
680 // If this global is linkonce/weak and the target handles this by emitting it
681 // into a 'uniqued' section name, create and return the section now.
682 if (GV->isWeakForLinker()) {
683 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
684 std::string Name = Mang->makeNameProper(GV->getNameStr());
685 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
689 return getTextSection();
691 return getDataSection();