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) {
42 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
45 static bool isSuitableForBSS(const GlobalVariable *GV) {
46 Constant *C = GV->getInitializer();
48 // Must have zero initializer.
49 if (!C->isNullValue())
52 // Leave constant zeros in readonly constant sections, so they can be shared.
56 // If the global has an explicit section specified, don't put it in BSS.
57 if (!GV->getSection().empty())
60 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
64 // Otherwise, put it in BSS!
68 static bool isConstantString(const Constant *C) {
69 // First check: is we have constant array of i8 terminated with zero
70 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
71 // Check, if initializer is a null-terminated string
72 if (CVA && CVA->isCString())
75 // Another possibility: [1 x i8] zeroinitializer
76 if (isa<ConstantAggregateZero>(C))
77 if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
78 return (Ty->getElementType() == Type::Int8Ty &&
79 Ty->getNumElements() == 1);
84 /// SectionKindForGlobal - This is a top-level target-independent classifier for
85 /// a global variable. Given an global variable and information from TM, it
86 /// classifies the global in a variety of ways that make various target
87 /// implementations simpler. The target implementation is free to ignore this
88 /// extra info of course.
89 static SectionKind SectionKindForGlobal(const GlobalValue *GV,
90 const TargetMachine &TM) {
91 Reloc::Model ReloModel = TM.getRelocationModel();
93 // Early exit - functions should be always in text sections.
94 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
96 return SectionKind::get(SectionKind::Text);
99 // Handle thread-local data first.
100 if (GVar->isThreadLocal()) {
101 if (isSuitableForBSS(GVar))
102 return SectionKind::get(SectionKind::ThreadBSS);
103 return SectionKind::get(SectionKind::ThreadData);
106 // Variable can be easily put to BSS section.
107 if (isSuitableForBSS(GVar))
108 return SectionKind::get(SectionKind::BSS);
110 Constant *C = GVar->getInitializer();
112 // If the global is marked constant, we can put it into a mergable section,
113 // a mergable string section, or general .data if it contains relocations.
114 if (GVar->isConstant()) {
115 // If the initializer for the global contains something that requires a
116 // relocation, then we may have to drop this into a wriable data section
117 // even though it is marked const.
118 switch (C->getRelocationInfo()) {
119 default: llvm_unreachable("unknown relocation info kind");
120 case Constant::NoRelocation:
121 // If initializer is a null-terminated string, put it in a "cstring"
122 // section if the target has it.
123 if (isConstantString(C))
124 return SectionKind::get(SectionKind::MergeableCString);
126 // Otherwise, just drop it into a mergable constant section. If we have
127 // a section for this size, use it, otherwise use the arbitrary sized
129 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
130 case 4: return SectionKind::get(SectionKind::MergeableConst4);
131 case 8: return SectionKind::get(SectionKind::MergeableConst8);
132 case 16: return SectionKind::get(SectionKind::MergeableConst16);
133 default: return SectionKind::get(SectionKind::MergeableConst);
136 case Constant::LocalRelocation:
137 // In static relocation model, the linker will resolve all addresses, so
138 // the relocation entries will actually be constants by the time the app
139 // starts up. However, we can't put this into a mergable section, because
140 // the linker doesn't take relocations into consideration when it tries to
141 // merge entries in the section.
142 if (ReloModel == Reloc::Static)
143 return SectionKind::get(SectionKind::ReadOnly);
145 // Otherwise, the dynamic linker needs to fix it up, put it in the
146 // writable data.rel.local section.
147 return SectionKind::get(SectionKind::ReadOnlyWithRelLocal);
149 case Constant::GlobalRelocations:
150 // In static relocation model, the linker will resolve all addresses, so
151 // the relocation entries will actually be constants by the time the app
152 // starts up. However, we can't put this into a mergable section, because
153 // the linker doesn't take relocations into consideration when it tries to
154 // merge entries in the section.
155 if (ReloModel == Reloc::Static)
156 return SectionKind::get(SectionKind::ReadOnly);
158 // Otherwise, the dynamic linker needs to fix it up, put it in the
159 // writable data.rel section.
160 return SectionKind::get(SectionKind::ReadOnlyWithRel);
164 // Okay, this isn't a constant. If the initializer for the global is going
165 // to require a runtime relocation by the dynamic linker, put it into a more
166 // specific section to improve startup time of the app. This coalesces these
167 // globals together onto fewer pages, improving the locality of the dynamic
169 if (ReloModel == Reloc::Static)
170 return SectionKind::get(SectionKind::DataNoRel);
172 switch (C->getRelocationInfo()) {
173 default: llvm_unreachable("unknown relocation info kind");
174 case Constant::NoRelocation:
175 return SectionKind::get(SectionKind::DataNoRel);
176 case Constant::LocalRelocation:
177 return SectionKind::get(SectionKind::DataRelLocal);
178 case Constant::GlobalRelocations:
179 return SectionKind::get(SectionKind::DataRel);
183 /// SectionForGlobal - This method computes the appropriate section to emit
184 /// the specified global variable or function definition. This should not
185 /// be passed external (or available externally) globals.
186 const MCSection *TargetLoweringObjectFile::
187 SectionForGlobal(const GlobalValue *GV, Mangler *Mang,
188 const TargetMachine &TM) const {
189 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
190 "Can only be used for global definitions");
192 SectionKind Kind = SectionKindForGlobal(GV, TM);
194 // Select section name.
195 if (GV->hasSection()) {
196 // If the target has special section hacks for specifically named globals,
198 if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Kind))
201 // If the target has magic semantics for certain section names, make sure to
202 // pick up the flags. This allows the user to write things with attribute
203 // section and still get the appropriate section flags printed.
204 Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
206 return getOrCreateSection(GV->getSection().c_str(), false, Kind);
210 // Use default section depending on the 'type' of global
211 return SelectSectionForGlobal(GV, Kind, Mang, TM);
214 // Lame default implementation. Calculate the section name for global.
216 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
219 const TargetMachine &TM) const{
220 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
223 return getTextSection();
225 if (Kind.isBSS() && BSSSection_ != 0)
228 if (Kind.isReadOnly() && ReadOnlySection != 0)
229 return ReadOnlySection;
231 return getDataSection();
234 /// getSectionForMergableConstant - Given a mergable constant with the
235 /// specified size and relocation information, return a section that it
236 /// should be placed in.
238 TargetLoweringObjectFile::
239 getSectionForMergeableConstant(SectionKind Kind) const {
240 if (Kind.isReadOnly() && ReadOnlySection != 0)
241 return ReadOnlySection;
247 const MCSection *TargetLoweringObjectFile::
248 getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
249 if (MCSection *S = Ctx->GetSection(Name))
251 return MCSection::Create(Name, isDirective, Kind, *Ctx);
256 //===----------------------------------------------------------------------===//
258 //===----------------------------------------------------------------------===//
260 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
261 const TargetMachine &TM) {
262 TargetLoweringObjectFile::Initialize(Ctx, TM);
264 BSSSection_ = getOrCreateSection("\t.bss", true,
265 SectionKind::get(SectionKind::BSS));
267 // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
268 // FIXME: Does .section .bss work everywhere??
269 // FIXME2: this should just be handle by the section printer. We should get
270 // away from syntactic view of the sections and MCSection should just be a
272 BSSSection_ = getOrCreateSection("\t.bss", false,
273 SectionKind::get(SectionKind::BSS));
276 TextSection = getOrCreateSection("\t.text", true,
277 SectionKind::get(SectionKind::Text));
278 DataSection = getOrCreateSection("\t.data", true,
279 SectionKind::get(SectionKind::DataRel));
281 getOrCreateSection("\t.rodata", false,
282 SectionKind::get(SectionKind::ReadOnly));
284 getOrCreateSection("\t.tdata", false,
285 SectionKind::get(SectionKind::ThreadData));
286 CStringSection_ = getOrCreateSection("\t.rodata.str", true,
287 SectionKind::get(SectionKind::MergeableCString));
289 TLSBSSSection = getOrCreateSection("\t.tbss", false,
290 SectionKind::get(SectionKind::ThreadBSS));
292 DataRelSection = getOrCreateSection("\t.data.rel", false,
293 SectionKind::get(SectionKind::DataRel));
294 DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
295 SectionKind::get(SectionKind::DataRelLocal));
296 DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
297 SectionKind::get(SectionKind::ReadOnlyWithRel));
298 DataRelROLocalSection =
299 getOrCreateSection("\t.data.rel.ro.local", false,
300 SectionKind::get(SectionKind::ReadOnlyWithRelLocal));
302 MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
303 SectionKind::get(SectionKind::MergeableConst4));
304 MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
305 SectionKind::get(SectionKind::MergeableConst8));
306 MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
307 SectionKind::get(SectionKind::MergeableConst16));
311 SectionKind TargetLoweringObjectFileELF::
312 getKindForNamedSection(const char *Name, SectionKind K) const {
313 if (Name[0] != '.') return K;
315 // Some lame default implementation based on some magic section names.
316 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
317 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
318 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
319 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
320 return SectionKind::get(SectionKind::BSS);
322 if (strcmp(Name, ".tdata") == 0 ||
323 strncmp(Name, ".tdata.", 7) == 0 ||
324 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
325 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
326 return SectionKind::get(SectionKind::ThreadData);
328 if (strcmp(Name, ".tbss") == 0 ||
329 strncmp(Name, ".tbss.", 6) == 0 ||
330 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
331 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
332 return SectionKind::get(SectionKind::ThreadBSS);
337 void TargetLoweringObjectFileELF::
338 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
342 if (!Kind.isMetadata())
346 if (Kind.isWriteable())
348 if (Kind.isMergeableCString() ||
349 Kind.isMergeableConst4() ||
350 Kind.isMergeableConst8() ||
351 Kind.isMergeableConst16())
353 if (Kind.isMergeableCString())
355 if (Kind.isThreadLocal())
361 // If comment string is '@', e.g. as on ARM - use '%' instead
368 if (Kind.isBSS() || Kind.isThreadBSS())
371 KindStr = "progbits";
373 Str.append(KindStr, KindStr+strlen(KindStr));
375 if (Kind.isMergeableCString()) {
376 // TODO: Eventually handle multiple byte character strings. For now, all
377 // mergable C strings are single byte.
380 } else if (Kind.isMergeableConst4()) {
383 } else if (Kind.isMergeableConst8()) {
386 } else if (Kind.isMergeableConst16()) {
394 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
395 if (Kind.isText()) return ".gnu.linkonce.t.";
396 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
398 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
399 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
401 if (Kind.isBSS()) return ".gnu.linkonce.b.";
402 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
403 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
404 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
405 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
407 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
408 return ".gnu.linkonce.d.rel.ro.";
411 const MCSection *TargetLoweringObjectFileELF::
412 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
413 Mangler *Mang, const TargetMachine &TM) const {
415 // If this global is linkonce/weak and the target handles this by emitting it
416 // into a 'uniqued' section name, create and return the section now.
417 if (GV->isWeakForLinker()) {
418 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
419 std::string Name = Mang->makeNameProper(GV->getNameStr());
420 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
423 if (Kind.isText()) return TextSection;
425 if (Kind.isMergeableCString()) {
426 assert(CStringSection_ && "Should have string section prefix");
428 // We also need alignment here.
429 // FIXME: this is getting the alignment of the character, not the
430 // alignment of the global!
432 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
434 std::string Name = CStringSection_->getName() + "1." + utostr(Align);
435 return getOrCreateSection(Name.c_str(), false,
436 SectionKind::get(SectionKind::MergeableCString));
439 if (Kind.isMergeableConst()) {
440 if (Kind.isMergeableConst4())
441 return MergeableConst4Section;
442 if (Kind.isMergeableConst8())
443 return MergeableConst8Section;
444 if (Kind.isMergeableConst16())
445 return MergeableConst16Section;
446 return ReadOnlySection; // .const
449 if (Kind.isReadOnly()) return ReadOnlySection;
451 if (Kind.isThreadData()) return TLSDataSection;
452 if (Kind.isThreadBSS()) return TLSBSSSection;
454 if (Kind.isBSS()) return BSSSection_;
456 if (Kind.isDataNoRel()) return DataSection;
457 if (Kind.isDataRelLocal()) return DataRelLocalSection;
458 if (Kind.isDataRel()) return DataRelSection;
459 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
461 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
462 return DataRelROSection;
465 /// getSectionForMergeableConstant - Given a mergeable constant with the
466 /// specified size and relocation information, return a section that it
467 /// should be placed in.
468 const MCSection *TargetLoweringObjectFileELF::
469 getSectionForMergeableConstant(SectionKind Kind) const {
470 if (Kind.isMergeableConst4())
471 return MergeableConst4Section;
472 if (Kind.isMergeableConst8())
473 return MergeableConst8Section;
474 if (Kind.isMergeableConst16())
475 return MergeableConst16Section;
476 if (Kind.isReadOnly())
477 return ReadOnlySection;
479 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
480 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
481 return DataRelROSection;
484 //===----------------------------------------------------------------------===//
486 //===----------------------------------------------------------------------===//
488 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
489 const TargetMachine &TM) {
490 TargetLoweringObjectFile::Initialize(Ctx, TM);
491 TextSection = getOrCreateSection("\t.text", true,
492 SectionKind::get(SectionKind::Text));
493 DataSection = getOrCreateSection("\t.data", true,
494 SectionKind::get(SectionKind::DataRel));
496 CStringSection_ = getOrCreateSection("\t.cstring", true,
497 SectionKind::get(SectionKind::MergeableCString));
498 FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
499 SectionKind::get(SectionKind::MergeableConst4));
500 EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
501 SectionKind::get(SectionKind::MergeableConst8));
503 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
504 // to using it in -static mode.
505 if (TM.getRelocationModel() != Reloc::Static &&
506 TM.getTargetData()->getPointerSize() == 32)
507 SixteenByteConstantSection =
508 getOrCreateSection("\t.literal16\n", true,
509 SectionKind::get(SectionKind::MergeableConst16));
511 SixteenByteConstantSection = 0;
513 ReadOnlySection = getOrCreateSection("\t.const", true,
514 SectionKind::get(SectionKind::ReadOnly));
517 getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
518 false, SectionKind::get(SectionKind::Text));
519 ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
521 SectionKind::get(SectionKind::Text));
522 ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
524 SectionKind::get(SectionKind::Text));
525 ConstDataSection = getOrCreateSection("\t.const_data", true,
526 SectionKind::get(SectionKind::ReadOnlyWithRel));
527 DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
529 SectionKind::get(SectionKind::DataRel));
532 const MCSection *TargetLoweringObjectFileMachO::
533 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
534 Mangler *Mang, const TargetMachine &TM) const {
535 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
538 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
540 // If this is weak/linkonce, put this in a coalescable section, either in text
541 // or data depending on if it is writable.
542 if (GV->isWeakForLinker()) {
543 if (Kind.isReadOnly())
544 return ConstTextCoalSection;
545 return DataCoalSection;
548 // FIXME: Alignment check should be handled by section classifier.
549 if (Kind.isMergeableCString()) {
550 Constant *C = cast<GlobalVariable>(GV)->getInitializer();
551 const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
552 const TargetData &TD = *TM.getTargetData();
553 unsigned Size = TD.getTypeAllocSize(Ty);
555 unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
557 return CStringSection_;
560 return ReadOnlySection;
563 if (Kind.isMergeableConst()) {
564 if (Kind.isMergeableConst4())
565 return FourByteConstantSection;
566 if (Kind.isMergeableConst8())
567 return EightByteConstantSection;
568 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
569 return SixteenByteConstantSection;
570 return ReadOnlySection; // .const
573 // FIXME: ROData -> const in -static mode that is relocatable but they happen
574 // by the static linker. Why not mergeable?
575 if (Kind.isReadOnly())
576 return ReadOnlySection;
578 // If this is marked const, put it into a const section. But if the dynamic
579 // linker needs to write to it, put it in the data segment.
580 if (Kind.isReadOnlyWithRel())
581 return ConstDataSection;
583 // Otherwise, just drop the variable in the normal data section.
588 TargetLoweringObjectFileMachO::
589 getSectionForMergeableConstant(SectionKind Kind) const {
590 // If this constant requires a relocation, we have to put it in the data
591 // segment, not in the text segment.
592 if (Kind.isDataRel())
593 return ConstDataSection;
595 if (Kind.isMergeableConst4())
596 return FourByteConstantSection;
597 if (Kind.isMergeableConst8())
598 return EightByteConstantSection;
599 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
600 return SixteenByteConstantSection;
601 return ReadOnlySection; // .const
604 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
605 /// not to emit the UsedDirective for some symbols in llvm.used.
606 // FIXME: REMOVE this (rdar://7071300)
607 bool TargetLoweringObjectFileMachO::
608 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
609 /// On Darwin, internally linked data beginning with "L" or "l" does not have
610 /// the directive emitted (this occurs in ObjC metadata).
611 if (!GV) return false;
613 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
614 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
615 // FIXME: ObjC metadata is currently emitted as internal symbols that have
616 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
617 // this horrible hack can go away.
618 const std::string &Name = Mang->getMangledName(GV);
619 if (Name[0] == 'L' || Name[0] == 'l')
627 //===----------------------------------------------------------------------===//
629 //===----------------------------------------------------------------------===//
631 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
632 const TargetMachine &TM) {
633 TargetLoweringObjectFile::Initialize(Ctx, TM);
634 TextSection = getOrCreateSection("\t.text", true,
635 SectionKind::get(SectionKind::Text));
636 DataSection = getOrCreateSection("\t.data", true,
637 SectionKind::get(SectionKind::DataRel));
640 void TargetLoweringObjectFileCOFF::
641 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
642 // FIXME: Inefficient.
643 std::string Res = ",\"";
646 if (Kind.isWriteable())
650 Str.append(Res.begin(), Res.end());
653 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
655 return ".text$linkonce";
656 if (Kind.isWriteable())
657 return ".data$linkonce";
658 return ".rdata$linkonce";
662 const MCSection *TargetLoweringObjectFileCOFF::
663 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
664 Mangler *Mang, const TargetMachine &TM) const {
665 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
667 // If this global is linkonce/weak and the target handles this by emitting it
668 // into a 'uniqued' section name, create and return the section now.
669 if (GV->isWeakForLinker()) {
670 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
671 std::string Name = Mang->makeNameProper(GV->getNameStr());
672 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
676 return getTextSection();
678 if (Kind.isReadOnly() && ReadOnlySection != 0)
679 return ReadOnlySection;
681 return getDataSection();