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);
193 SectionInfo Info = SectionInfo::get(Kind, GV->isWeakForLinker());
195 // Select section name.
196 if (GV->hasSection()) {
197 // If the target has special section hacks for specifically named globals,
199 if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Info))
202 // If the target has magic semantics for certain section names, make sure to
203 // pick up the flags. This allows the user to write things with attribute
204 // section and still get the appropriate section flags printed.
205 Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
207 return getOrCreateSection(GV->getSection().c_str(), false, Kind);
211 // Use default section depending on the 'type' of global
212 return SelectSectionForGlobal(GV, Info, Mang, TM);
215 // Lame default implementation. Calculate the section name for global.
217 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
220 const TargetMachine &TM) const{
221 assert(!Info.isThreadLocal() && "Doesn't support TLS");
224 return getTextSection();
226 if (Info.isBSS() && BSSSection_ != 0)
229 if (Info.isReadOnly() && ReadOnlySection != 0)
230 return ReadOnlySection;
232 return getDataSection();
235 /// getSectionForMergableConstant - Given a mergable constant with the
236 /// specified size and relocation information, return a section that it
237 /// should be placed in.
239 TargetLoweringObjectFile::
240 getSectionForMergeableConstant(SectionKind Kind) const {
241 if (Kind.isReadOnly() && ReadOnlySection != 0)
242 return ReadOnlySection;
248 const MCSection *TargetLoweringObjectFile::
249 getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
250 if (MCSection *S = Ctx->GetSection(Name))
252 return MCSection::Create(Name, isDirective, Kind, *Ctx);
257 //===----------------------------------------------------------------------===//
259 //===----------------------------------------------------------------------===//
261 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
262 const TargetMachine &TM) {
263 TargetLoweringObjectFile::Initialize(Ctx, TM);
265 BSSSection_ = getOrCreateSection("\t.bss", true,
266 SectionKind::get(SectionKind::BSS));
268 // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
269 // FIXME: Does .section .bss work everywhere??
270 // FIXME2: this should just be handle by the section printer. We should get
271 // away from syntactic view of the sections and MCSection should just be a
273 BSSSection_ = getOrCreateSection("\t.bss", false,
274 SectionKind::get(SectionKind::BSS));
277 TextSection = getOrCreateSection("\t.text", true,
278 SectionKind::get(SectionKind::Text));
279 DataSection = getOrCreateSection("\t.data", true,
280 SectionKind::get(SectionKind::DataRel));
282 getOrCreateSection("\t.rodata", false,
283 SectionKind::get(SectionKind::ReadOnly));
285 getOrCreateSection("\t.tdata", false,
286 SectionKind::get(SectionKind::ThreadData));
287 CStringSection_ = getOrCreateSection("\t.rodata.str", true,
288 SectionKind::get(SectionKind::MergeableCString));
290 TLSBSSSection = getOrCreateSection("\t.tbss", false,
291 SectionKind::get(SectionKind::ThreadBSS));
293 DataRelSection = getOrCreateSection("\t.data.rel", false,
294 SectionKind::get(SectionKind::DataRel));
295 DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
296 SectionKind::get(SectionKind::DataRelLocal));
297 DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
298 SectionKind::get(SectionKind::ReadOnlyWithRel));
299 DataRelROLocalSection =
300 getOrCreateSection("\t.data.rel.ro.local", false,
301 SectionKind::get(SectionKind::ReadOnlyWithRelLocal));
303 MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
304 SectionKind::get(SectionKind::MergeableConst4));
305 MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
306 SectionKind::get(SectionKind::MergeableConst8));
307 MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
308 SectionKind::get(SectionKind::MergeableConst16));
312 SectionKind TargetLoweringObjectFileELF::
313 getKindForNamedSection(const char *Name, SectionKind K) const {
314 if (Name[0] != '.') return K;
316 // Some lame default implementation based on some magic section names.
317 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
318 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
319 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
320 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
321 return SectionKind::get(SectionKind::BSS);
323 if (strcmp(Name, ".tdata") == 0 ||
324 strncmp(Name, ".tdata.", 7) == 0 ||
325 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
326 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
327 return SectionKind::get(SectionKind::ThreadData);
329 if (strcmp(Name, ".tbss") == 0 ||
330 strncmp(Name, ".tbss.", 6) == 0 ||
331 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
332 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
333 return SectionKind::get(SectionKind::ThreadBSS);
338 void TargetLoweringObjectFileELF::
339 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
343 if (!Kind.isMetadata())
347 if (Kind.isWriteable())
349 if (Kind.isMergeableCString() ||
350 Kind.isMergeableConst4() ||
351 Kind.isMergeableConst8() ||
352 Kind.isMergeableConst16())
354 if (Kind.isMergeableCString())
356 if (Kind.isThreadLocal())
362 // If comment string is '@', e.g. as on ARM - use '%' instead
369 if (Kind.isBSS() || Kind.isThreadBSS())
372 KindStr = "progbits";
374 Str.append(KindStr, KindStr+strlen(KindStr));
376 if (Kind.isMergeableCString()) {
377 // TODO: Eventually handle multiple byte character strings. For now, all
378 // mergable C strings are single byte.
381 } else if (Kind.isMergeableConst4()) {
384 } else if (Kind.isMergeableConst8()) {
387 } else if (Kind.isMergeableConst16()) {
395 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
396 if (Kind.isText()) return ".gnu.linkonce.t.";
397 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
399 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
400 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
402 if (Kind.isBSS()) return ".gnu.linkonce.b.";
403 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
404 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
405 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
406 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
408 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
409 return ".gnu.linkonce.d.rel.ro.";
412 const MCSection *TargetLoweringObjectFileELF::
413 SelectSectionForGlobal(const GlobalValue *GV, SectionInfo Info,
414 Mangler *Mang, const TargetMachine &TM) const {
416 // If this global is linkonce/weak and the target handles this by emitting it
417 // into a 'uniqued' section name, create and return the section now.
419 const char *Prefix = getSectionPrefixForUniqueGlobal(Info);
420 std::string Name = Mang->makeNameProper(GV->getNameStr());
421 return getOrCreateSection((Prefix+Name).c_str(), false, Info);
424 if (Info.isText()) return TextSection;
426 if (Info.isMergeableCString()) {
427 assert(CStringSection_ && "Should have string section prefix");
429 // We also need alignment here.
430 // FIXME: this is getting the alignment of the character, not the
431 // alignment of the global!
433 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
435 std::string Name = CStringSection_->getName() + "1." + utostr(Align);
436 return getOrCreateSection(Name.c_str(), false,
437 SectionKind::get(SectionKind::MergeableCString));
440 if (Info.isMergeableConst()) {
441 if (Info.isMergeableConst4())
442 return MergeableConst4Section;
443 if (Info.isMergeableConst8())
444 return MergeableConst8Section;
445 if (Info.isMergeableConst16())
446 return MergeableConst16Section;
447 return ReadOnlySection; // .const
450 if (Info.isReadOnly()) return ReadOnlySection;
452 if (Info.isThreadData()) return TLSDataSection;
453 if (Info.isThreadBSS()) return TLSBSSSection;
455 if (Info.isBSS()) return BSSSection_;
457 if (Info.isDataNoRel()) return DataSection;
458 if (Info.isDataRelLocal()) return DataRelLocalSection;
459 if (Info.isDataRel()) return DataRelSection;
460 if (Info.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
462 assert(Info.isReadOnlyWithRel() && "Unknown section kind");
463 return DataRelROSection;
466 /// getSectionForMergeableConstant - Given a mergeable constant with the
467 /// specified size and relocation information, return a section that it
468 /// should be placed in.
469 const MCSection *TargetLoweringObjectFileELF::
470 getSectionForMergeableConstant(SectionKind Kind) const {
471 if (Kind.isMergeableConst4())
472 return MergeableConst4Section;
473 if (Kind.isMergeableConst8())
474 return MergeableConst8Section;
475 if (Kind.isMergeableConst16())
476 return MergeableConst16Section;
477 if (Kind.isReadOnly())
478 return ReadOnlySection;
480 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
481 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
482 return DataRelROSection;
485 //===----------------------------------------------------------------------===//
487 //===----------------------------------------------------------------------===//
489 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
490 const TargetMachine &TM) {
491 TargetLoweringObjectFile::Initialize(Ctx, TM);
492 TextSection = getOrCreateSection("\t.text", true,
493 SectionKind::get(SectionKind::Text));
494 DataSection = getOrCreateSection("\t.data", true,
495 SectionKind::get(SectionKind::DataRel));
497 CStringSection_ = getOrCreateSection("\t.cstring", true,
498 SectionKind::get(SectionKind::MergeableCString));
499 FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
500 SectionKind::get(SectionKind::MergeableConst4));
501 EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
502 SectionKind::get(SectionKind::MergeableConst8));
504 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
505 // to using it in -static mode.
506 if (TM.getRelocationModel() != Reloc::Static &&
507 TM.getTargetData()->getPointerSize() == 32)
508 SixteenByteConstantSection =
509 getOrCreateSection("\t.literal16\n", true,
510 SectionKind::get(SectionKind::MergeableConst16));
512 SixteenByteConstantSection = 0;
514 ReadOnlySection = getOrCreateSection("\t.const", true,
515 SectionKind::get(SectionKind::ReadOnly));
518 getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
519 false, SectionKind::get(SectionKind::Text));
520 ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
522 SectionKind::get(SectionKind::Text));
523 ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
525 SectionKind::get(SectionKind::Text));
526 ConstDataSection = getOrCreateSection("\t.const_data", true,
527 SectionKind::get(SectionKind::ReadOnlyWithRel));
528 DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
530 SectionKind::get(SectionKind::DataRel));
533 const MCSection *TargetLoweringObjectFileMachO::
534 SelectSectionForGlobal(const GlobalValue *GV, SectionInfo Info,
535 Mangler *Mang, const TargetMachine &TM) const {
536 assert(!Info.isThreadLocal() && "Darwin doesn't support TLS");
539 return Info.isWeak() ? TextCoalSection : TextSection;
541 // If this is weak/linkonce, put this in a coalescable section, either in text
542 // or data depending on if it is writable.
544 if (Info.isReadOnly())
545 return ConstTextCoalSection;
546 return DataCoalSection;
549 // FIXME: Alignment check should be handled by section classifier.
550 if (Info.isMergeableCString()) {
551 Constant *C = cast<GlobalVariable>(GV)->getInitializer();
552 const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
553 const TargetData &TD = *TM.getTargetData();
554 unsigned Size = TD.getTypeAllocSize(Ty);
556 unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
558 return CStringSection_;
561 return ReadOnlySection;
564 if (Info.isMergeableConst()) {
565 if (Info.isMergeableConst4())
566 return FourByteConstantSection;
567 if (Info.isMergeableConst8())
568 return EightByteConstantSection;
569 if (Info.isMergeableConst16() && SixteenByteConstantSection)
570 return SixteenByteConstantSection;
571 return ReadOnlySection; // .const
574 // FIXME: ROData -> const in -static mode that is relocatable but they happen
575 // by the static linker. Why not mergeable?
576 if (Info.isReadOnly())
577 return ReadOnlySection;
579 // If this is marked const, put it into a const section. But if the dynamic
580 // linker needs to write to it, put it in the data segment.
581 if (Info.isReadOnlyWithRel())
582 return ConstDataSection;
584 // Otherwise, just drop the variable in the normal data section.
589 TargetLoweringObjectFileMachO::
590 getSectionForMergeableConstant(SectionKind Kind) const {
591 // If this constant requires a relocation, we have to put it in the data
592 // segment, not in the text segment.
593 if (Kind.isDataRel())
594 return ConstDataSection;
596 if (Kind.isMergeableConst4())
597 return FourByteConstantSection;
598 if (Kind.isMergeableConst8())
599 return EightByteConstantSection;
600 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
601 return SixteenByteConstantSection;
602 return ReadOnlySection; // .const
605 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
606 /// not to emit the UsedDirective for some symbols in llvm.used.
607 // FIXME: REMOVE this (rdar://7071300)
608 bool TargetLoweringObjectFileMachO::
609 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
610 /// On Darwin, internally linked data beginning with "L" or "l" does not have
611 /// the directive emitted (this occurs in ObjC metadata).
612 if (!GV) return false;
614 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
615 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
616 // FIXME: ObjC metadata is currently emitted as internal symbols that have
617 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
618 // this horrible hack can go away.
619 const std::string &Name = Mang->getMangledName(GV);
620 if (Name[0] == 'L' || Name[0] == 'l')
628 //===----------------------------------------------------------------------===//
630 //===----------------------------------------------------------------------===//
632 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
633 const TargetMachine &TM) {
634 TargetLoweringObjectFile::Initialize(Ctx, TM);
635 TextSection = getOrCreateSection("\t.text", true,
636 SectionKind::get(SectionKind::Text));
637 DataSection = getOrCreateSection("\t.data", true,
638 SectionKind::get(SectionKind::DataRel));
641 void TargetLoweringObjectFileCOFF::
642 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
643 // FIXME: Inefficient.
644 std::string Res = ",\"";
647 if (Kind.isWriteable())
651 Str.append(Res.begin(), Res.end());
654 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
656 return ".text$linkonce";
657 if (Kind.isWriteable())
658 return ".data$linkonce";
659 return ".rdata$linkonce";
663 const MCSection *TargetLoweringObjectFileCOFF::
664 SelectSectionForGlobal(const GlobalValue *GV, SectionInfo Info,
665 Mangler *Mang, const TargetMachine &TM) const {
666 assert(!Info.isThreadLocal() && "Doesn't support TLS");
668 // If this global is linkonce/weak and the target handles this by emitting it
669 // into a 'uniqued' section name, create and return the section now.
671 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Info);
672 std::string Name = Mang->makeNameProper(GV->getNameStr());
673 return getOrCreateSection((Prefix+Name).c_str(), false, Info);
677 return getTextSection();
679 if (Info.isBSS() && BSSSection_ != 0)
682 if (Info.isReadOnly() && ReadOnlySection != 0)
683 return ReadOnlySection;
685 return getDataSection();