Change allowsUnalignedMemoryAccesses to take type argument since some targets
[llvm/avr.git] / lib / Target / TargetLoweringObjectFile.cpp
blobd64cf07b01ea601271ed3a5710ad4b018a869eb9
1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/MCSectionMachO.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
29 using namespace llvm;
31 //===----------------------------------------------------------------------===//
32 // Generic Code
33 //===----------------------------------------------------------------------===//
35 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
36 TextSection = 0;
37 DataSection = 0;
38 BSSSection = 0;
39 ReadOnlySection = 0;
40 StaticCtorSection = 0;
41 StaticDtorSection = 0;
42 LSDASection = 0;
43 EHFrameSection = 0;
45 DwarfAbbrevSection = 0;
46 DwarfInfoSection = 0;
47 DwarfLineSection = 0;
48 DwarfFrameSection = 0;
49 DwarfPubNamesSection = 0;
50 DwarfPubTypesSection = 0;
51 DwarfDebugInlineSection = 0;
52 DwarfStrSection = 0;
53 DwarfLocSection = 0;
54 DwarfARangesSection = 0;
55 DwarfRangesSection = 0;
56 DwarfMacroInfoSection = 0;
59 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
62 static bool isSuitableForBSS(const GlobalVariable *GV) {
63 Constant *C = GV->getInitializer();
65 // Must have zero initializer.
66 if (!C->isNullValue())
67 return false;
69 // Leave constant zeros in readonly constant sections, so they can be shared.
70 if (GV->isConstant())
71 return false;
73 // If the global has an explicit section specified, don't put it in BSS.
74 if (!GV->getSection().empty())
75 return false;
77 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
78 if (NoZerosInBSS)
79 return false;
81 // Otherwise, put it in BSS!
82 return true;
85 /// IsNullTerminatedString - Return true if the specified constant (which is
86 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
87 /// nul value and contains no other nuls in it.
88 static bool IsNullTerminatedString(const Constant *C) {
89 const ArrayType *ATy = cast<ArrayType>(C->getType());
91 // First check: is we have constant array of i8 terminated with zero
92 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
93 if (ATy->getNumElements() == 0) return false;
95 ConstantInt *Null =
96 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
97 if (Null == 0 || Null->getZExtValue() != 0)
98 return false; // Not null terminated.
100 // Verify that the null doesn't occur anywhere else in the string.
101 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
102 // Reject constantexpr elements etc.
103 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
104 CVA->getOperand(i) == Null)
105 return false;
106 return true;
109 // Another possibility: [1 x i8] zeroinitializer
110 if (isa<ConstantAggregateZero>(C))
111 return ATy->getNumElements() == 1;
113 return false;
116 /// getKindForGlobal - This is a top-level target-independent classifier for
117 /// a global variable. Given an global variable and information from TM, it
118 /// classifies the global in a variety of ways that make various target
119 /// implementations simpler. The target implementation is free to ignore this
120 /// extra info of course.
121 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
122 const TargetMachine &TM){
123 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
124 "Can only be used for global definitions");
126 Reloc::Model ReloModel = TM.getRelocationModel();
128 // Early exit - functions should be always in text sections.
129 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
130 if (GVar == 0)
131 return SectionKind::getText();
133 // Handle thread-local data first.
134 if (GVar->isThreadLocal()) {
135 if (isSuitableForBSS(GVar))
136 return SectionKind::getThreadBSS();
137 return SectionKind::getThreadData();
140 // Variable can be easily put to BSS section.
141 if (isSuitableForBSS(GVar))
142 return SectionKind::getBSS();
144 Constant *C = GVar->getInitializer();
146 // If the global is marked constant, we can put it into a mergable section,
147 // a mergable string section, or general .data if it contains relocations.
148 if (GVar->isConstant()) {
149 // If the initializer for the global contains something that requires a
150 // relocation, then we may have to drop this into a wriable data section
151 // even though it is marked const.
152 switch (C->getRelocationInfo()) {
153 default: llvm_unreachable("unknown relocation info kind");
154 case Constant::NoRelocation:
155 // If initializer is a null-terminated string, put it in a "cstring"
156 // section of the right width.
157 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
158 if (const IntegerType *ITy =
159 dyn_cast<IntegerType>(ATy->getElementType())) {
160 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
161 ITy->getBitWidth() == 32) &&
162 IsNullTerminatedString(C)) {
163 if (ITy->getBitWidth() == 8)
164 return SectionKind::getMergeable1ByteCString();
165 if (ITy->getBitWidth() == 16)
166 return SectionKind::getMergeable2ByteCString();
168 assert(ITy->getBitWidth() == 32 && "Unknown width");
169 return SectionKind::getMergeable4ByteCString();
174 // Otherwise, just drop it into a mergable constant section. If we have
175 // a section for this size, use it, otherwise use the arbitrary sized
176 // mergable section.
177 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
178 case 4: return SectionKind::getMergeableConst4();
179 case 8: return SectionKind::getMergeableConst8();
180 case 16: return SectionKind::getMergeableConst16();
181 default: return SectionKind::getMergeableConst();
184 case Constant::LocalRelocation:
185 // In static relocation model, the linker will resolve all addresses, so
186 // the relocation entries will actually be constants by the time the app
187 // starts up. However, we can't put this into a mergable section, because
188 // the linker doesn't take relocations into consideration when it tries to
189 // merge entries in the section.
190 if (ReloModel == Reloc::Static)
191 return SectionKind::getReadOnly();
193 // Otherwise, the dynamic linker needs to fix it up, put it in the
194 // writable data.rel.local section.
195 return SectionKind::getReadOnlyWithRelLocal();
197 case Constant::GlobalRelocations:
198 // In static relocation model, the linker will resolve all addresses, so
199 // the relocation entries will actually be constants by the time the app
200 // starts up. However, we can't put this into a mergable section, because
201 // the linker doesn't take relocations into consideration when it tries to
202 // merge entries in the section.
203 if (ReloModel == Reloc::Static)
204 return SectionKind::getReadOnly();
206 // Otherwise, the dynamic linker needs to fix it up, put it in the
207 // writable data.rel section.
208 return SectionKind::getReadOnlyWithRel();
212 // Okay, this isn't a constant. If the initializer for the global is going
213 // to require a runtime relocation by the dynamic linker, put it into a more
214 // specific section to improve startup time of the app. This coalesces these
215 // globals together onto fewer pages, improving the locality of the dynamic
216 // linker.
217 if (ReloModel == Reloc::Static)
218 return SectionKind::getDataNoRel();
220 switch (C->getRelocationInfo()) {
221 default: llvm_unreachable("unknown relocation info kind");
222 case Constant::NoRelocation:
223 return SectionKind::getDataNoRel();
224 case Constant::LocalRelocation:
225 return SectionKind::getDataRelLocal();
226 case Constant::GlobalRelocations:
227 return SectionKind::getDataRel();
231 /// SectionForGlobal - This method computes the appropriate section to emit
232 /// the specified global variable or function definition. This should not
233 /// be passed external (or available externally) globals.
234 const MCSection *TargetLoweringObjectFile::
235 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
236 const TargetMachine &TM) const {
237 // Select section name.
238 if (GV->hasSection())
239 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
242 // Use default section depending on the 'type' of global
243 return SelectSectionForGlobal(GV, Kind, Mang, TM);
247 // Lame default implementation. Calculate the section name for global.
248 const MCSection *
249 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
250 SectionKind Kind,
251 Mangler *Mang,
252 const TargetMachine &TM) const{
253 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
255 if (Kind.isText())
256 return getTextSection();
258 if (Kind.isBSS() && BSSSection != 0)
259 return BSSSection;
261 if (Kind.isReadOnly() && ReadOnlySection != 0)
262 return ReadOnlySection;
264 return getDataSection();
267 /// getSectionForConstant - Given a mergable constant with the
268 /// specified size and relocation information, return a section that it
269 /// should be placed in.
270 const MCSection *
271 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
272 if (Kind.isReadOnly() && ReadOnlySection != 0)
273 return ReadOnlySection;
275 return DataSection;
280 //===----------------------------------------------------------------------===//
281 // ELF
282 //===----------------------------------------------------------------------===//
283 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
285 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
286 // If we have the section uniquing map, free it.
287 delete (ELFUniqueMapTy*)UniquingMap;
290 const MCSection *TargetLoweringObjectFileELF::
291 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
292 SectionKind Kind, bool IsExplicit) const {
293 if (UniquingMap == 0)
294 UniquingMap = new ELFUniqueMapTy();
295 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
297 // Do the lookup, if we have a hit, return it.
298 const MCSectionELF *&Entry = Map[Section];
299 if (Entry) return Entry;
301 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
302 getContext());
305 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
306 const TargetMachine &TM) {
307 TargetLoweringObjectFile::Initialize(Ctx, TM);
309 BSSSection =
310 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
311 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
312 SectionKind::getBSS());
314 TextSection =
315 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
316 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
317 SectionKind::getText());
319 DataSection =
320 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
321 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
322 SectionKind::getDataRel());
324 ReadOnlySection =
325 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
326 MCSectionELF::SHF_ALLOC,
327 SectionKind::getReadOnly());
329 TLSDataSection =
330 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
331 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
332 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
334 TLSBSSSection =
335 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
336 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
337 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
339 DataRelSection =
340 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
341 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
342 SectionKind::getDataRel());
344 DataRelLocalSection =
345 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
346 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
347 SectionKind::getDataRelLocal());
349 DataRelROSection =
350 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
351 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
352 SectionKind::getReadOnlyWithRel());
354 DataRelROLocalSection =
355 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
356 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
357 SectionKind::getReadOnlyWithRelLocal());
359 MergeableConst4Section =
360 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
361 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
362 SectionKind::getMergeableConst4());
364 MergeableConst8Section =
365 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
366 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
367 SectionKind::getMergeableConst8());
369 MergeableConst16Section =
370 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
371 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
372 SectionKind::getMergeableConst16());
374 StaticCtorSection =
375 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
376 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
377 SectionKind::getDataRel());
379 StaticDtorSection =
380 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
381 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
382 SectionKind::getDataRel());
384 // Exception Handling Sections.
386 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
387 // it contains relocatable pointers. In PIC mode, this is probably a big
388 // runtime hit for C++ apps. Either the contents of the LSDA need to be
389 // adjusted or this should be a data section.
390 LSDASection =
391 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
392 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
393 EHFrameSection =
394 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
395 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
396 SectionKind::getDataRel());
398 // Debug Info Sections.
399 DwarfAbbrevSection =
400 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
401 SectionKind::getMetadata());
402 DwarfInfoSection =
403 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
404 SectionKind::getMetadata());
405 DwarfLineSection =
406 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
407 SectionKind::getMetadata());
408 DwarfFrameSection =
409 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
410 SectionKind::getMetadata());
411 DwarfPubNamesSection =
412 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
413 SectionKind::getMetadata());
414 DwarfPubTypesSection =
415 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
416 SectionKind::getMetadata());
417 DwarfStrSection =
418 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
419 SectionKind::getMetadata());
420 DwarfLocSection =
421 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
422 SectionKind::getMetadata());
423 DwarfARangesSection =
424 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
425 SectionKind::getMetadata());
426 DwarfRangesSection =
427 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
428 SectionKind::getMetadata());
429 DwarfMacroInfoSection =
430 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
431 SectionKind::getMetadata());
435 static SectionKind
436 getELFKindForNamedSection(const char *Name, SectionKind K) {
437 if (Name[0] != '.') return K;
439 // Some lame default implementation based on some magic section names.
440 if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
441 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
442 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
443 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
444 return SectionKind::getBSS();
446 if (strcmp(Name, ".tdata") == 0 ||
447 strncmp(Name, ".tdata.", 7) == 0 ||
448 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
449 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
450 return SectionKind::getThreadData();
452 if (strcmp(Name, ".tbss") == 0 ||
453 strncmp(Name, ".tbss.", 6) == 0 ||
454 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
455 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
456 return SectionKind::getThreadBSS();
458 return K;
462 static unsigned
463 getELFSectionType(const char *Name, SectionKind K) {
465 if (strcmp(Name, ".init_array") == 0)
466 return MCSectionELF::SHT_INIT_ARRAY;
468 if (strcmp(Name, ".fini_array") == 0)
469 return MCSectionELF::SHT_FINI_ARRAY;
471 if (strcmp(Name, ".preinit_array") == 0)
472 return MCSectionELF::SHT_PREINIT_ARRAY;
474 if (K.isBSS() || K.isThreadBSS())
475 return MCSectionELF::SHT_NOBITS;
477 return MCSectionELF::SHT_PROGBITS;
481 static unsigned
482 getELFSectionFlags(SectionKind K) {
483 unsigned Flags = 0;
485 if (!K.isMetadata())
486 Flags |= MCSectionELF::SHF_ALLOC;
488 if (K.isWriteable())
489 Flags |= MCSectionELF::SHF_WRITE;
491 if (K.isThreadLocal())
492 Flags |= MCSectionELF::SHF_TLS;
494 // K.isMergeableConst() is left out to honour PR4650
495 if (K.isMergeableCString() || K.isMergeableConst4() ||
496 K.isMergeableConst8() || K.isMergeableConst16())
497 Flags |= MCSectionELF::SHF_MERGE;
499 if (K.isMergeableCString())
500 Flags |= MCSectionELF::SHF_STRINGS;
502 return Flags;
506 const MCSection *TargetLoweringObjectFileELF::
507 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
508 Mangler *Mang, const TargetMachine &TM) const {
509 const char *SectionName = GV->getSection().c_str();
511 // Infer section flags from the section name if we can.
512 Kind = getELFKindForNamedSection(SectionName, Kind);
514 return getELFSection(SectionName,
515 getELFSectionType(SectionName, Kind),
516 getELFSectionFlags(Kind), Kind, true);
519 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
520 if (Kind.isText()) return ".gnu.linkonce.t.";
521 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
523 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
524 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
526 if (Kind.isBSS()) return ".gnu.linkonce.b.";
527 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
528 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
529 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
530 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
532 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
533 return ".gnu.linkonce.d.rel.ro.";
536 const MCSection *TargetLoweringObjectFileELF::
537 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
538 Mangler *Mang, const TargetMachine &TM) const {
540 // If this global is linkonce/weak and the target handles this by emitting it
541 // into a 'uniqued' section name, create and return the section now.
542 if (GV->isWeakForLinker()) {
543 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
544 std::string Name = Mang->makeNameProper(GV->getNameStr());
546 return getELFSection((Prefix+Name).c_str(),
547 getELFSectionType((Prefix+Name).c_str(), Kind),
548 getELFSectionFlags(Kind),
549 Kind);
552 if (Kind.isText()) return TextSection;
554 if (Kind.isMergeable1ByteCString() ||
555 Kind.isMergeable2ByteCString() ||
556 Kind.isMergeable4ByteCString()) {
558 // We also need alignment here.
559 // FIXME: this is getting the alignment of the character, not the
560 // alignment of the global!
561 unsigned Align =
562 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
564 const char *SizeSpec = ".rodata.str1.";
565 if (Kind.isMergeable2ByteCString())
566 SizeSpec = ".rodata.str2.";
567 else if (Kind.isMergeable4ByteCString())
568 SizeSpec = ".rodata.str4.";
569 else
570 assert(Kind.isMergeable1ByteCString() && "unknown string width");
573 std::string Name = SizeSpec + utostr(Align);
574 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
575 MCSectionELF::SHF_ALLOC |
576 MCSectionELF::SHF_MERGE |
577 MCSectionELF::SHF_STRINGS,
578 Kind);
581 if (Kind.isMergeableConst()) {
582 if (Kind.isMergeableConst4() && MergeableConst4Section)
583 return MergeableConst4Section;
584 if (Kind.isMergeableConst8() && MergeableConst8Section)
585 return MergeableConst8Section;
586 if (Kind.isMergeableConst16() && MergeableConst16Section)
587 return MergeableConst16Section;
588 return ReadOnlySection; // .const
591 if (Kind.isReadOnly()) return ReadOnlySection;
593 if (Kind.isThreadData()) return TLSDataSection;
594 if (Kind.isThreadBSS()) return TLSBSSSection;
596 if (Kind.isBSS()) return BSSSection;
598 if (Kind.isDataNoRel()) return DataSection;
599 if (Kind.isDataRelLocal()) return DataRelLocalSection;
600 if (Kind.isDataRel()) return DataRelSection;
601 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
603 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
604 return DataRelROSection;
607 /// getSectionForConstant - Given a mergeable constant with the
608 /// specified size and relocation information, return a section that it
609 /// should be placed in.
610 const MCSection *TargetLoweringObjectFileELF::
611 getSectionForConstant(SectionKind Kind) const {
612 if (Kind.isMergeableConst4())
613 return MergeableConst4Section;
614 if (Kind.isMergeableConst8())
615 return MergeableConst8Section;
616 if (Kind.isMergeableConst16())
617 return MergeableConst16Section;
618 if (Kind.isReadOnly())
619 return ReadOnlySection;
621 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
622 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
623 return DataRelROSection;
626 //===----------------------------------------------------------------------===//
627 // MachO
628 //===----------------------------------------------------------------------===//
630 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
632 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
633 // If we have the MachO uniquing map, free it.
634 delete (MachOUniqueMapTy*)UniquingMap;
638 const MCSectionMachO *TargetLoweringObjectFileMachO::
639 getMachOSection(const StringRef &Segment, const StringRef &Section,
640 unsigned TypeAndAttributes,
641 unsigned Reserved2, SectionKind Kind) const {
642 // We unique sections by their segment/section pair. The returned section
643 // may not have the same flags as the requested section, if so this should be
644 // diagnosed by the client as an error.
646 // Create the map if it doesn't already exist.
647 if (UniquingMap == 0)
648 UniquingMap = new MachOUniqueMapTy();
649 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
651 // Form the name to look up.
652 SmallString<64> Name;
653 Name.append(Segment.begin(), Segment.end());
654 Name.push_back(',');
655 Name.append(Section.begin(), Section.end());
657 // Do the lookup, if we have a hit, return it.
658 const MCSectionMachO *&Entry = Map[StringRef(Name.data(), Name.size())];
659 if (Entry) return Entry;
661 // Otherwise, return a new section.
662 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
663 Reserved2, Kind, getContext());
667 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
668 const TargetMachine &TM) {
669 TargetLoweringObjectFile::Initialize(Ctx, TM);
671 TextSection // .text
672 = getMachOSection("__TEXT", "__text",
673 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
674 SectionKind::getText());
675 DataSection // .data
676 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
678 CStringSection // .cstring
679 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
680 SectionKind::getMergeable1ByteCString());
681 UStringSection
682 = getMachOSection("__TEXT","__ustring", 0,
683 SectionKind::getMergeable2ByteCString());
684 FourByteConstantSection // .literal4
685 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
686 SectionKind::getMergeableConst4());
687 EightByteConstantSection // .literal8
688 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
689 SectionKind::getMergeableConst8());
691 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
692 // to using it in -static mode.
693 SixteenByteConstantSection = 0;
694 if (TM.getRelocationModel() != Reloc::Static &&
695 TM.getTargetData()->getPointerSize() == 32)
696 SixteenByteConstantSection = // .literal16
697 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
698 SectionKind::getMergeableConst16());
700 ReadOnlySection // .const
701 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
703 TextCoalSection
704 = getMachOSection("__TEXT", "__textcoal_nt",
705 MCSectionMachO::S_COALESCED |
706 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
707 SectionKind::getText());
708 ConstTextCoalSection
709 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
710 SectionKind::getText());
711 ConstDataCoalSection
712 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
713 SectionKind::getText());
714 ConstDataSection // .const_data
715 = getMachOSection("__DATA", "__const", 0,
716 SectionKind::getReadOnlyWithRel());
717 DataCoalSection
718 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
719 SectionKind::getDataRel());
722 LazySymbolPointerSection
723 = getMachOSection("__DATA", "__la_symbol_ptr",
724 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
725 SectionKind::getMetadata());
726 NonLazySymbolPointerSection
727 = getMachOSection("__DATA", "__nl_symbol_ptr",
728 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
729 SectionKind::getMetadata());
731 if (TM.getRelocationModel() == Reloc::Static) {
732 StaticCtorSection
733 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
734 StaticDtorSection
735 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
736 } else {
737 StaticCtorSection
738 = getMachOSection("__DATA", "__mod_init_func",
739 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
740 SectionKind::getDataRel());
741 StaticDtorSection
742 = getMachOSection("__DATA", "__mod_term_func",
743 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
744 SectionKind::getDataRel());
747 // Exception Handling.
748 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
749 SectionKind::getDataRel());
750 EHFrameSection =
751 getMachOSection("__TEXT", "__eh_frame",
752 MCSectionMachO::S_COALESCED |
753 MCSectionMachO::S_ATTR_NO_TOC |
754 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
755 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
756 SectionKind::getReadOnly());
758 // Debug Information.
759 DwarfAbbrevSection =
760 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
761 SectionKind::getMetadata());
762 DwarfInfoSection =
763 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
764 SectionKind::getMetadata());
765 DwarfLineSection =
766 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
767 SectionKind::getMetadata());
768 DwarfFrameSection =
769 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
770 SectionKind::getMetadata());
771 DwarfPubNamesSection =
772 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
773 SectionKind::getMetadata());
774 DwarfPubTypesSection =
775 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
776 SectionKind::getMetadata());
777 DwarfStrSection =
778 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
779 SectionKind::getMetadata());
780 DwarfLocSection =
781 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
782 SectionKind::getMetadata());
783 DwarfARangesSection =
784 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
785 SectionKind::getMetadata());
786 DwarfRangesSection =
787 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
788 SectionKind::getMetadata());
789 DwarfMacroInfoSection =
790 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
791 SectionKind::getMetadata());
792 DwarfDebugInlineSection =
793 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
794 SectionKind::getMetadata());
797 const MCSection *TargetLoweringObjectFileMachO::
798 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
799 Mangler *Mang, const TargetMachine &TM) const {
800 // Parse the section specifier and create it if valid.
801 StringRef Segment, Section;
802 unsigned TAA, StubSize;
803 std::string ErrorCode =
804 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
805 TAA, StubSize);
806 if (!ErrorCode.empty()) {
807 // If invalid, report the error with llvm_report_error.
808 llvm_report_error("Global variable '" + GV->getNameStr() +
809 "' has an invalid section specifier '" + GV->getSection()+
810 "': " + ErrorCode + ".");
811 // Fall back to dropping it into the data section.
812 return DataSection;
815 // Get the section.
816 const MCSectionMachO *S =
817 getMachOSection(Segment, Section, TAA, StubSize, Kind);
819 // Okay, now that we got the section, verify that the TAA & StubSize agree.
820 // If the user declared multiple globals with different section flags, we need
821 // to reject it here.
822 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
823 // If invalid, report the error with llvm_report_error.
824 llvm_report_error("Global variable '" + GV->getNameStr() +
825 "' section type or attributes does not match previous"
826 " section specifier");
829 return S;
832 const MCSection *TargetLoweringObjectFileMachO::
833 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
834 Mangler *Mang, const TargetMachine &TM) const {
835 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
837 if (Kind.isText())
838 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
840 // If this is weak/linkonce, put this in a coalescable section, either in text
841 // or data depending on if it is writable.
842 if (GV->isWeakForLinker()) {
843 if (Kind.isReadOnly())
844 return ConstTextCoalSection;
845 return DataCoalSection;
848 // FIXME: Alignment check should be handled by section classifier.
849 if (Kind.isMergeable1ByteCString() ||
850 Kind.isMergeable2ByteCString()) {
851 if (TM.getTargetData()->getPreferredAlignment(
852 cast<GlobalVariable>(GV)) < 32) {
853 if (Kind.isMergeable1ByteCString())
854 return CStringSection;
855 assert(Kind.isMergeable2ByteCString());
856 return UStringSection;
860 if (Kind.isMergeableConst()) {
861 if (Kind.isMergeableConst4())
862 return FourByteConstantSection;
863 if (Kind.isMergeableConst8())
864 return EightByteConstantSection;
865 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
866 return SixteenByteConstantSection;
869 // Otherwise, if it is readonly, but not something we can specially optimize,
870 // just drop it in .const.
871 if (Kind.isReadOnly())
872 return ReadOnlySection;
874 // If this is marked const, put it into a const section. But if the dynamic
875 // linker needs to write to it, put it in the data segment.
876 if (Kind.isReadOnlyWithRel())
877 return ConstDataSection;
879 // Otherwise, just drop the variable in the normal data section.
880 return DataSection;
883 const MCSection *
884 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
885 // If this constant requires a relocation, we have to put it in the data
886 // segment, not in the text segment.
887 if (Kind.isDataRel())
888 return ConstDataSection;
890 if (Kind.isMergeableConst4())
891 return FourByteConstantSection;
892 if (Kind.isMergeableConst8())
893 return EightByteConstantSection;
894 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
895 return SixteenByteConstantSection;
896 return ReadOnlySection; // .const
899 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
900 /// not to emit the UsedDirective for some symbols in llvm.used.
901 // FIXME: REMOVE this (rdar://7071300)
902 bool TargetLoweringObjectFileMachO::
903 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
904 /// On Darwin, internally linked data beginning with "L" or "l" does not have
905 /// the directive emitted (this occurs in ObjC metadata).
906 if (!GV) return false;
908 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
909 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
910 // FIXME: ObjC metadata is currently emitted as internal symbols that have
911 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
912 // this horrible hack can go away.
913 const std::string &Name = Mang->getMangledName(GV);
914 if (Name[0] == 'L' || Name[0] == 'l')
915 return false;
918 return true;
922 //===----------------------------------------------------------------------===//
923 // COFF
924 //===----------------------------------------------------------------------===//
926 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
928 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
929 delete (COFFUniqueMapTy*)UniquingMap;
933 const MCSection *TargetLoweringObjectFileCOFF::
934 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
935 // Create the map if it doesn't already exist.
936 if (UniquingMap == 0)
937 UniquingMap = new MachOUniqueMapTy();
938 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
940 // Do the lookup, if we have a hit, return it.
941 const MCSectionCOFF *&Entry = Map[Name];
942 if (Entry) return Entry;
944 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
947 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
948 const TargetMachine &TM) {
949 TargetLoweringObjectFile::Initialize(Ctx, TM);
950 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
951 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
952 StaticCtorSection =
953 getCOFFSection(".ctors", false, SectionKind::getDataRel());
954 StaticDtorSection =
955 getCOFFSection(".dtors", false, SectionKind::getDataRel());
958 // Debug info.
959 // FIXME: Don't use 'directive' mode here.
960 DwarfAbbrevSection =
961 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
962 true, SectionKind::getMetadata());
963 DwarfInfoSection =
964 getCOFFSection("\t.section\t.debug_info,\"dr\"",
965 true, SectionKind::getMetadata());
966 DwarfLineSection =
967 getCOFFSection("\t.section\t.debug_line,\"dr\"",
968 true, SectionKind::getMetadata());
969 DwarfFrameSection =
970 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
971 true, SectionKind::getMetadata());
972 DwarfPubNamesSection =
973 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
974 true, SectionKind::getMetadata());
975 DwarfPubTypesSection =
976 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
977 true, SectionKind::getMetadata());
978 DwarfStrSection =
979 getCOFFSection("\t.section\t.debug_str,\"dr\"",
980 true, SectionKind::getMetadata());
981 DwarfLocSection =
982 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
983 true, SectionKind::getMetadata());
984 DwarfARangesSection =
985 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
986 true, SectionKind::getMetadata());
987 DwarfRangesSection =
988 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
989 true, SectionKind::getMetadata());
990 DwarfMacroInfoSection =
991 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
992 true, SectionKind::getMetadata());
995 const MCSection *TargetLoweringObjectFileCOFF::
996 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
997 Mangler *Mang, const TargetMachine &TM) const {
998 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1001 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1002 if (Kind.isText())
1003 return ".text$linkonce";
1004 if (Kind.isWriteable())
1005 return ".data$linkonce";
1006 return ".rdata$linkonce";
1010 const MCSection *TargetLoweringObjectFileCOFF::
1011 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1012 Mangler *Mang, const TargetMachine &TM) const {
1013 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1015 // If this global is linkonce/weak and the target handles this by emitting it
1016 // into a 'uniqued' section name, create and return the section now.
1017 if (GV->isWeakForLinker()) {
1018 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1019 std::string Name = Mang->makeNameProper(GV->getNameStr());
1020 return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1023 if (Kind.isText())
1024 return getTextSection();
1026 return getDataSection();