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) {
39 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
42 static bool isSuitableForBSS(const GlobalVariable *GV) {
43 Constant *C = GV->getInitializer();
45 // Must have zero initializer.
46 if (!C->isNullValue())
49 // Leave constant zeros in readonly constant sections, so they can be shared.
53 // If the global has an explicit section specified, don't put it in BSS.
54 if (!GV->getSection().empty())
57 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
61 // Otherwise, put it in BSS!
65 static bool isConstantString(const Constant *C) {
66 // First check: is we have constant array of i8 terminated with zero
67 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
68 // Check, if initializer is a null-terminated string
69 if (CVA && CVA->isCString())
72 // Another possibility: [1 x i8] zeroinitializer
73 if (isa<ConstantAggregateZero>(C))
74 if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
75 return (Ty->getElementType() == Type::Int8Ty &&
76 Ty->getNumElements() == 1);
81 /// SectionKindForGlobal - This is a top-level target-independent classifier for
82 /// a global variable. Given an global variable and information from TM, it
83 /// classifies the global in a variety of ways that make various target
84 /// implementations simpler. The target implementation is free to ignore this
85 /// extra info of course.
86 static SectionKind SectionKindForGlobal(const GlobalValue *GV,
87 const TargetMachine &TM) {
88 Reloc::Model ReloModel = TM.getRelocationModel();
90 // Early exit - functions should be always in text sections.
91 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
93 return SectionKind::get(SectionKind::Text);
96 // Handle thread-local data first.
97 if (GVar->isThreadLocal()) {
98 if (isSuitableForBSS(GVar))
99 return SectionKind::get(SectionKind::ThreadBSS);
100 return SectionKind::get(SectionKind::ThreadData);
103 // Variable can be easily put to BSS section.
104 if (isSuitableForBSS(GVar))
105 return SectionKind::get(SectionKind::BSS);
107 Constant *C = GVar->getInitializer();
109 // If the global is marked constant, we can put it into a mergable section,
110 // a mergable string section, or general .data if it contains relocations.
111 if (GVar->isConstant()) {
112 // If the initializer for the global contains something that requires a
113 // relocation, then we may have to drop this into a wriable data section
114 // even though it is marked const.
115 switch (C->getRelocationInfo()) {
116 default: llvm_unreachable("unknown relocation info kind");
117 case Constant::NoRelocation:
118 // If initializer is a null-terminated string, put it in a "cstring"
119 // section if the target has it.
120 if (isConstantString(C))
121 return SectionKind::get(SectionKind::MergeableCString);
123 // Otherwise, just drop it into a mergable constant section. If we have
124 // a section for this size, use it, otherwise use the arbitrary sized
126 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
127 case 4: return SectionKind::get(SectionKind::MergeableConst4);
128 case 8: return SectionKind::get(SectionKind::MergeableConst8);
129 case 16: return SectionKind::get(SectionKind::MergeableConst16);
130 default: return SectionKind::get(SectionKind::MergeableConst);
133 case Constant::LocalRelocation:
134 // In static relocation model, the linker will resolve all addresses, so
135 // the relocation entries will actually be constants by the time the app
136 // starts up. However, we can't put this into a mergable section, because
137 // the linker doesn't take relocations into consideration when it tries to
138 // merge entries in the section.
139 if (ReloModel == Reloc::Static)
140 return SectionKind::get(SectionKind::ReadOnly);
142 // Otherwise, the dynamic linker needs to fix it up, put it in the
143 // writable data.rel.local section.
144 return SectionKind::get(SectionKind::ReadOnlyWithRelLocal);
146 case Constant::GlobalRelocations:
147 // In static relocation model, the linker will resolve all addresses, so
148 // the relocation entries will actually be constants by the time the app
149 // starts up. However, we can't put this into a mergable section, because
150 // the linker doesn't take relocations into consideration when it tries to
151 // merge entries in the section.
152 if (ReloModel == Reloc::Static)
153 return SectionKind::get(SectionKind::ReadOnly);
155 // Otherwise, the dynamic linker needs to fix it up, put it in the
156 // writable data.rel section.
157 return SectionKind::get(SectionKind::ReadOnlyWithRel);
161 // Okay, this isn't a constant. If the initializer for the global is going
162 // to require a runtime relocation by the dynamic linker, put it into a more
163 // specific section to improve startup time of the app. This coalesces these
164 // globals together onto fewer pages, improving the locality of the dynamic
166 if (ReloModel == Reloc::Static)
167 return SectionKind::get(SectionKind::DataNoRel);
169 switch (C->getRelocationInfo()) {
170 default: llvm_unreachable("unknown relocation info kind");
171 case Constant::NoRelocation:
172 return SectionKind::get(SectionKind::DataNoRel);
173 case Constant::LocalRelocation:
174 return SectionKind::get(SectionKind::DataRelLocal);
175 case Constant::GlobalRelocations:
176 return SectionKind::get(SectionKind::DataRel);
180 /// SectionForGlobal - This method computes the appropriate section to emit
181 /// the specified global variable or function definition. This should not
182 /// be passed external (or available externally) globals.
183 const MCSection *TargetLoweringObjectFile::
184 SectionForGlobal(const GlobalValue *GV, Mangler *Mang,
185 const TargetMachine &TM) const {
186 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
187 "Can only be used for global definitions");
189 SectionKind Kind = SectionKindForGlobal(GV, TM);
191 // Select section name.
192 if (GV->hasSection()) {
193 // If the target has special section hacks for specifically named globals,
195 if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Kind))
198 // If the target has magic semantics for certain section names, make sure to
199 // pick up the flags. This allows the user to write things with attribute
200 // section and still get the appropriate section flags printed.
201 Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
203 return getOrCreateSection(GV->getSection().c_str(), false, Kind);
207 // Use default section depending on the 'type' of global
208 return SelectSectionForGlobal(GV, Kind, Mang, TM);
211 // Lame default implementation. Calculate the section name for global.
213 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
216 const TargetMachine &TM) const{
217 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
220 return getTextSection();
222 if (Kind.isBSS() && BSSSection != 0)
225 if (Kind.isReadOnly() && ReadOnlySection != 0)
226 return ReadOnlySection;
228 return getDataSection();
231 /// getSectionForConstant - Given a mergable constant with the
232 /// specified size and relocation information, return a section that it
233 /// should be placed in.
235 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
236 if (Kind.isReadOnly() && ReadOnlySection != 0)
237 return ReadOnlySection;
243 const MCSection *TargetLoweringObjectFile::
244 getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
245 if (MCSection *S = Ctx->GetSection(Name))
247 return MCSection::Create(Name, isDirective, Kind, *Ctx);
252 //===----------------------------------------------------------------------===//
254 //===----------------------------------------------------------------------===//
256 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
257 const TargetMachine &TM) {
258 TargetLoweringObjectFile::Initialize(Ctx, TM);
260 BSSSection = getOrCreateSection("\t.bss", true,
261 SectionKind::get(SectionKind::BSS));
263 // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
264 // FIXME: Does .section .bss work everywhere??
265 // FIXME2: this should just be handle by the section printer. We should get
266 // away from syntactic view of the sections and MCSection should just be a
268 BSSSection = getOrCreateSection("\t.bss", false,
269 SectionKind::get(SectionKind::BSS));
272 TextSection = getOrCreateSection("\t.text", true,
273 SectionKind::get(SectionKind::Text));
274 DataSection = getOrCreateSection("\t.data", true,
275 SectionKind::get(SectionKind::DataRel));
277 getOrCreateSection("\t.rodata", false,
278 SectionKind::get(SectionKind::ReadOnly));
280 getOrCreateSection("\t.tdata", false,
281 SectionKind::get(SectionKind::ThreadData));
282 CStringSection = getOrCreateSection("\t.rodata.str", true,
283 SectionKind::get(SectionKind::MergeableCString));
285 TLSBSSSection = getOrCreateSection("\t.tbss", false,
286 SectionKind::get(SectionKind::ThreadBSS));
288 DataRelSection = getOrCreateSection("\t.data.rel", false,
289 SectionKind::get(SectionKind::DataRel));
290 DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
291 SectionKind::get(SectionKind::DataRelLocal));
292 DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
293 SectionKind::get(SectionKind::ReadOnlyWithRel));
294 DataRelROLocalSection =
295 getOrCreateSection("\t.data.rel.ro.local", false,
296 SectionKind::get(SectionKind::ReadOnlyWithRelLocal));
298 MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
299 SectionKind::get(SectionKind::MergeableConst4));
300 MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
301 SectionKind::get(SectionKind::MergeableConst8));
302 MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
303 SectionKind::get(SectionKind::MergeableConst16));
307 SectionKind TargetLoweringObjectFileELF::
308 getKindForNamedSection(const char *Name, SectionKind K) const {
309 if (Name[0] != '.') return K;
311 // Some lame default implementation based on some magic section names.
312 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
313 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
314 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
315 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
316 return SectionKind::get(SectionKind::BSS);
318 if (strcmp(Name, ".tdata") == 0 ||
319 strncmp(Name, ".tdata.", 7) == 0 ||
320 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
321 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
322 return SectionKind::get(SectionKind::ThreadData);
324 if (strcmp(Name, ".tbss") == 0 ||
325 strncmp(Name, ".tbss.", 6) == 0 ||
326 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
327 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
328 return SectionKind::get(SectionKind::ThreadBSS);
333 void TargetLoweringObjectFileELF::
334 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
338 if (!Kind.isMetadata())
342 if (Kind.isWriteable())
344 if (Kind.isMergeableCString() ||
345 Kind.isMergeableConst4() ||
346 Kind.isMergeableConst8() ||
347 Kind.isMergeableConst16())
349 if (Kind.isMergeableCString())
351 if (Kind.isThreadLocal())
357 // If comment string is '@', e.g. as on ARM - use '%' instead
364 if (Kind.isBSS() || Kind.isThreadBSS())
367 KindStr = "progbits";
369 Str.append(KindStr, KindStr+strlen(KindStr));
371 if (Kind.isMergeableCString()) {
372 // TODO: Eventually handle multiple byte character strings. For now, all
373 // mergable C strings are single byte.
376 } else if (Kind.isMergeableConst4()) {
379 } else if (Kind.isMergeableConst8()) {
382 } else if (Kind.isMergeableConst16()) {
390 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
391 if (Kind.isText()) return ".gnu.linkonce.t.";
392 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
394 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
395 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
397 if (Kind.isBSS()) return ".gnu.linkonce.b.";
398 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
399 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
400 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
401 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
403 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
404 return ".gnu.linkonce.d.rel.ro.";
407 const MCSection *TargetLoweringObjectFileELF::
408 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
409 Mangler *Mang, const TargetMachine &TM) const {
411 // If this global is linkonce/weak and the target handles this by emitting it
412 // into a 'uniqued' section name, create and return the section now.
413 if (GV->isWeakForLinker()) {
414 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
415 std::string Name = Mang->makeNameProper(GV->getNameStr());
416 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
419 if (Kind.isText()) return TextSection;
421 if (Kind.isMergeableCString()) {
422 assert(CStringSection && "Should have string section prefix");
424 // We also need alignment here.
425 // FIXME: this is getting the alignment of the character, not the
426 // alignment of the global!
428 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
430 std::string Name = CStringSection->getName() + "1." + utostr(Align);
431 return getOrCreateSection(Name.c_str(), false,
432 SectionKind::get(SectionKind::MergeableCString));
435 if (Kind.isMergeableConst()) {
436 if (Kind.isMergeableConst4())
437 return MergeableConst4Section;
438 if (Kind.isMergeableConst8())
439 return MergeableConst8Section;
440 if (Kind.isMergeableConst16())
441 return MergeableConst16Section;
442 return ReadOnlySection; // .const
445 if (Kind.isReadOnly()) return ReadOnlySection;
447 if (Kind.isThreadData()) return TLSDataSection;
448 if (Kind.isThreadBSS()) return TLSBSSSection;
450 if (Kind.isBSS()) return BSSSection;
452 if (Kind.isDataNoRel()) return DataSection;
453 if (Kind.isDataRelLocal()) return DataRelLocalSection;
454 if (Kind.isDataRel()) return DataRelSection;
455 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
457 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
458 return DataRelROSection;
461 /// getSectionForConstant - Given a mergeable constant with the
462 /// specified size and relocation information, return a section that it
463 /// should be placed in.
464 const MCSection *TargetLoweringObjectFileELF::
465 getSectionForConstant(SectionKind Kind) const {
466 if (Kind.isMergeableConst4())
467 return MergeableConst4Section;
468 if (Kind.isMergeableConst8())
469 return MergeableConst8Section;
470 if (Kind.isMergeableConst16())
471 return MergeableConst16Section;
472 if (Kind.isReadOnly())
473 return ReadOnlySection;
475 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
476 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
477 return DataRelROSection;
480 //===----------------------------------------------------------------------===//
482 //===----------------------------------------------------------------------===//
484 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
485 const TargetMachine &TM) {
486 TargetLoweringObjectFile::Initialize(Ctx, TM);
487 TextSection = getOrCreateSection("\t.text", true,
488 SectionKind::get(SectionKind::Text));
489 DataSection = getOrCreateSection("\t.data", true,
490 SectionKind::get(SectionKind::DataRel));
492 CStringSection = getOrCreateSection("\t.cstring", true,
493 SectionKind::get(SectionKind::MergeableCString));
494 FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
495 SectionKind::get(SectionKind::MergeableConst4));
496 EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
497 SectionKind::get(SectionKind::MergeableConst8));
499 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
500 // to using it in -static mode.
501 if (TM.getRelocationModel() != Reloc::Static &&
502 TM.getTargetData()->getPointerSize() == 32)
503 SixteenByteConstantSection =
504 getOrCreateSection("\t.literal16\n", true,
505 SectionKind::get(SectionKind::MergeableConst16));
507 SixteenByteConstantSection = 0;
509 ReadOnlySection = getOrCreateSection("\t.const", true,
510 SectionKind::get(SectionKind::ReadOnly));
513 getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
514 false, SectionKind::get(SectionKind::Text));
515 ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
517 SectionKind::get(SectionKind::Text));
518 ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
520 SectionKind::get(SectionKind::Text));
521 ConstDataSection = getOrCreateSection("\t.const_data", true,
522 SectionKind::get(SectionKind::ReadOnlyWithRel));
523 DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
525 SectionKind::get(SectionKind::DataRel));
528 const MCSection *TargetLoweringObjectFileMachO::
529 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
530 Mangler *Mang, const TargetMachine &TM) const {
531 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
534 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
536 // If this is weak/linkonce, put this in a coalescable section, either in text
537 // or data depending on if it is writable.
538 if (GV->isWeakForLinker()) {
539 if (Kind.isReadOnly())
540 return ConstTextCoalSection;
541 return DataCoalSection;
544 // FIXME: Alignment check should be handled by section classifier.
545 if (Kind.isMergeableCString()) {
546 Constant *C = cast<GlobalVariable>(GV)->getInitializer();
547 const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
548 const TargetData &TD = *TM.getTargetData();
549 unsigned Size = TD.getTypeAllocSize(Ty);
551 unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
553 return CStringSection;
556 return ReadOnlySection;
559 if (Kind.isMergeableConst()) {
560 if (Kind.isMergeableConst4())
561 return FourByteConstantSection;
562 if (Kind.isMergeableConst8())
563 return EightByteConstantSection;
564 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
565 return SixteenByteConstantSection;
566 return ReadOnlySection; // .const
569 // FIXME: ROData -> const in -static mode that is relocatable but they happen
570 // by the static linker. Why not mergeable?
571 if (Kind.isReadOnly())
572 return ReadOnlySection;
574 // If this is marked const, put it into a const section. But if the dynamic
575 // linker needs to write to it, put it in the data segment.
576 if (Kind.isReadOnlyWithRel())
577 return ConstDataSection;
579 // Otherwise, just drop the variable in the normal data section.
584 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
585 // If this constant requires a relocation, we have to put it in the data
586 // segment, not in the text segment.
587 if (Kind.isDataRel())
588 return ConstDataSection;
590 if (Kind.isMergeableConst4())
591 return FourByteConstantSection;
592 if (Kind.isMergeableConst8())
593 return EightByteConstantSection;
594 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
595 return SixteenByteConstantSection;
596 return ReadOnlySection; // .const
599 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
600 /// not to emit the UsedDirective for some symbols in llvm.used.
601 // FIXME: REMOVE this (rdar://7071300)
602 bool TargetLoweringObjectFileMachO::
603 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
604 /// On Darwin, internally linked data beginning with "L" or "l" does not have
605 /// the directive emitted (this occurs in ObjC metadata).
606 if (!GV) return false;
608 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
609 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
610 // FIXME: ObjC metadata is currently emitted as internal symbols that have
611 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
612 // this horrible hack can go away.
613 const std::string &Name = Mang->getMangledName(GV);
614 if (Name[0] == 'L' || Name[0] == 'l')
622 //===----------------------------------------------------------------------===//
624 //===----------------------------------------------------------------------===//
626 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
627 const TargetMachine &TM) {
628 TargetLoweringObjectFile::Initialize(Ctx, TM);
629 TextSection = getOrCreateSection("\t.text", true,
630 SectionKind::get(SectionKind::Text));
631 DataSection = getOrCreateSection("\t.data", true,
632 SectionKind::get(SectionKind::DataRel));
635 void TargetLoweringObjectFileCOFF::
636 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
637 // FIXME: Inefficient.
638 std::string Res = ",\"";
641 if (Kind.isWriteable())
645 Str.append(Res.begin(), Res.end());
648 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
650 return ".text$linkonce";
651 if (Kind.isWriteable())
652 return ".data$linkonce";
653 return ".rdata$linkonce";
657 const MCSection *TargetLoweringObjectFileCOFF::
658 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
659 Mangler *Mang, const TargetMachine &TM) const {
660 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
662 // If this global is linkonce/weak and the target handles this by emitting it
663 // into a 'uniqued' section name, create and return the section now.
664 if (GV->isWeakForLinker()) {
665 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
666 std::string Name = Mang->makeNameProper(GV->getNameStr());
667 return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
671 return getTextSection();
673 return getDataSection();