TargetLoweringObjectFile.cpp revision 5277b22687d3513dd29d5a9c8510cac740f933f6
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.
12//
13//===----------------------------------------------------------------------===//
14
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/TargetAsmInfo.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/Support/Mangler.h"
26#include "llvm/ADT/StringExtras.h"
27using namespace llvm;
28
29//===----------------------------------------------------------------------===//
30//                              Generic Code
31//===----------------------------------------------------------------------===//
32
33TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
34  TextSection = 0;
35  DataSection = 0;
36  BSSSection = 0;
37  ReadOnlySection = 0;
38  StaticCtorSection = 0;
39  StaticDtorSection = 0;
40  LSDASection = 0;
41  EHFrameSection = 0;
42
43  DwarfAbbrevSection = 0;
44  DwarfInfoSection = 0;
45  DwarfLineSection = 0;
46  DwarfFrameSection = 0;
47  DwarfPubNamesSection = 0;
48  DwarfPubTypesSection = 0;
49  DwarfDebugInlineSection = 0;
50  DwarfStrSection = 0;
51  DwarfLocSection = 0;
52  DwarfARangesSection = 0;
53  DwarfRangesSection = 0;
54  DwarfMacroInfoSection = 0;
55}
56
57TargetLoweringObjectFile::~TargetLoweringObjectFile() {
58}
59
60static bool isSuitableForBSS(const GlobalVariable *GV) {
61  Constant *C = GV->getInitializer();
62
63  // Must have zero initializer.
64  if (!C->isNullValue())
65    return false;
66
67  // Leave constant zeros in readonly constant sections, so they can be shared.
68  if (GV->isConstant())
69    return false;
70
71  // If the global has an explicit section specified, don't put it in BSS.
72  if (!GV->getSection().empty())
73    return false;
74
75  // If -nozero-initialized-in-bss is specified, don't ever use BSS.
76  if (NoZerosInBSS)
77    return false;
78
79  // Otherwise, put it in BSS!
80  return true;
81}
82
83/// IsNullTerminatedString - Return true if the specified constant (which is
84/// known to have a type that is an array of 1/2/4 byte elements) ends with a
85/// nul value and contains no other nuls in it.
86static bool IsNullTerminatedString(const Constant *C) {
87  const ArrayType *ATy = cast<ArrayType>(C->getType());
88
89  // First check: is we have constant array of i8 terminated with zero
90  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
91    if (ATy->getNumElements() == 0) return false;
92
93    ConstantInt *Null =
94      dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
95    if (Null == 0 || Null->getZExtValue() != 0)
96      return false; // Not null terminated.
97
98    // Verify that the null doesn't occur anywhere else in the string.
99    for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
100      // Reject constantexpr elements etc.
101      if (!isa<ConstantInt>(CVA->getOperand(i)) ||
102          CVA->getOperand(i) == Null)
103        return false;
104    return true;
105  }
106
107  // Another possibility: [1 x i8] zeroinitializer
108  if (isa<ConstantAggregateZero>(C))
109    return ATy->getNumElements() == 1;
110
111  return false;
112}
113
114/// getKindForGlobal - This is a top-level target-independent classifier for
115/// a global variable.  Given an global variable and information from TM, it
116/// classifies the global in a variety of ways that make various target
117/// implementations simpler.  The target implementation is free to ignore this
118/// extra info of course.
119SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
120                                                       const TargetMachine &TM){
121  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
122         "Can only be used for global definitions");
123
124  Reloc::Model ReloModel = TM.getRelocationModel();
125
126  // Early exit - functions should be always in text sections.
127  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
128  if (GVar == 0)
129    return SectionKind::getText();
130
131
132  // Handle thread-local data first.
133  if (GVar->isThreadLocal()) {
134    if (isSuitableForBSS(GVar))
135      return SectionKind::getThreadBSS();
136    return SectionKind::getThreadData();
137  }
138
139  // Variable can be easily put to BSS section.
140  if (isSuitableForBSS(GVar))
141    return SectionKind::getBSS();
142
143  Constant *C = GVar->getInitializer();
144
145  // If the global is marked constant, we can put it into a mergable section,
146  // a mergable string section, or general .data if it contains relocations.
147  if (GVar->isConstant()) {
148    // If the initializer for the global contains something that requires a
149    // relocation, then we may have to drop this into a wriable data section
150    // even though it is marked const.
151    switch (C->getRelocationInfo()) {
152    default: llvm_unreachable("unknown relocation info kind");
153    case Constant::NoRelocation:
154      // If initializer is a null-terminated string, put it in a "cstring"
155      // section of the right width.
156      if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
157        if (const IntegerType *ITy =
158              dyn_cast<IntegerType>(ATy->getElementType())) {
159          if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
160               ITy->getBitWidth() == 32) &&
161              IsNullTerminatedString(C)) {
162            if (ITy->getBitWidth() == 8)
163              return SectionKind::getMergeable1ByteCString();
164            if (ITy->getBitWidth() == 16)
165              return SectionKind::getMergeable2ByteCString();
166
167            assert(ITy->getBitWidth() == 32 && "Unknown width");
168            return SectionKind::getMergeable4ByteCString();
169          }
170        }
171      }
172
173      // Otherwise, just drop it into a mergable constant section.  If we have
174      // a section for this size, use it, otherwise use the arbitrary sized
175      // mergable section.
176      switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
177      case 4:  return SectionKind::getMergeableConst4();
178      case 8:  return SectionKind::getMergeableConst8();
179      case 16: return SectionKind::getMergeableConst16();
180      default: return SectionKind::getMergeableConst();
181      }
182
183    case Constant::LocalRelocation:
184      // In static relocation model, the linker will resolve all addresses, so
185      // the relocation entries will actually be constants by the time the app
186      // starts up.  However, we can't put this into a mergable section, because
187      // the linker doesn't take relocations into consideration when it tries to
188      // merge entries in the section.
189      if (ReloModel == Reloc::Static)
190        return SectionKind::getReadOnly();
191
192      // Otherwise, the dynamic linker needs to fix it up, put it in the
193      // writable data.rel.local section.
194      return SectionKind::getReadOnlyWithRelLocal();
195
196    case Constant::GlobalRelocations:
197      // In static relocation model, the linker will resolve all addresses, so
198      // the relocation entries will actually be constants by the time the app
199      // starts up.  However, we can't put this into a mergable section, because
200      // the linker doesn't take relocations into consideration when it tries to
201      // merge entries in the section.
202      if (ReloModel == Reloc::Static)
203        return SectionKind::getReadOnly();
204
205      // Otherwise, the dynamic linker needs to fix it up, put it in the
206      // writable data.rel section.
207      return SectionKind::getReadOnlyWithRel();
208    }
209  }
210
211  // Okay, this isn't a constant.  If the initializer for the global is going
212  // to require a runtime relocation by the dynamic linker, put it into a more
213  // specific section to improve startup time of the app.  This coalesces these
214  // globals together onto fewer pages, improving the locality of the dynamic
215  // linker.
216  if (ReloModel == Reloc::Static)
217    return SectionKind::getDataNoRel();
218
219  switch (C->getRelocationInfo()) {
220  default: llvm_unreachable("unknown relocation info kind");
221  case Constant::NoRelocation:
222    return SectionKind::getDataNoRel();
223  case Constant::LocalRelocation:
224    return SectionKind::getDataRelLocal();
225  case Constant::GlobalRelocations:
226    return SectionKind::getDataRel();
227  }
228}
229
230/// SectionForGlobal - This method computes the appropriate section to emit
231/// the specified global variable or function definition.  This should not
232/// be passed external (or available externally) globals.
233const MCSection *TargetLoweringObjectFile::
234SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
235                 const TargetMachine &TM) const {
236  // Select section name.
237  if (GV->hasSection())
238    return getExplicitSectionGlobal(GV, Kind, Mang, TM);
239
240
241  // Use default section depending on the 'type' of global
242  return SelectSectionForGlobal(GV, Kind, Mang, TM);
243}
244
245
246// Lame default implementation. Calculate the section name for global.
247const MCSection *
248TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
249                                                 SectionKind Kind,
250                                                 Mangler *Mang,
251                                                 const TargetMachine &TM) const{
252  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
253
254  if (Kind.isText())
255    return getTextSection();
256
257  if (Kind.isBSS() && BSSSection != 0)
258    return BSSSection;
259
260  if (Kind.isReadOnly() && ReadOnlySection != 0)
261    return ReadOnlySection;
262
263  return getDataSection();
264}
265
266/// getSectionForConstant - Given a mergable constant with the
267/// specified size and relocation information, return a section that it
268/// should be placed in.
269const MCSection *
270TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
271  if (Kind.isReadOnly() && ReadOnlySection != 0)
272    return ReadOnlySection;
273
274  return DataSection;
275}
276
277
278
279//===----------------------------------------------------------------------===//
280//                                  ELF
281//===----------------------------------------------------------------------===//
282
283const MCSection *TargetLoweringObjectFileELF::
284getELFSection(const char *Name, bool isDirective, SectionKind Kind) const {
285  if (MCSection *S = getContext().GetSection(Name))
286    return S;
287  return MCSection::Create(Name, isDirective, Kind, getContext());
288}
289
290void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
291                                             const TargetMachine &TM) {
292  TargetLoweringObjectFile::Initialize(Ctx, TM);
293  if (!HasCrazyBSS)
294    BSSSection = getELFSection("\t.bss", true, SectionKind::getBSS());
295  else
296    // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
297    // FIXME: Does .section .bss work everywhere??
298    // FIXME2: this should just be handle by the section printer.  We should get
299    // away from syntactic view of the sections and MCSection should just be a
300    // semantic view.
301    BSSSection = getELFSection("\t.bss", false, SectionKind::getBSS());
302
303
304  TextSection = getELFSection("\t.text", true, SectionKind::getText());
305  DataSection = getELFSection("\t.data", true, SectionKind::getDataRel());
306  ReadOnlySection =
307    getELFSection("\t.rodata", false, SectionKind::getReadOnly());
308  TLSDataSection =
309    getELFSection("\t.tdata", false, SectionKind::getThreadData());
310
311  TLSBSSSection = getELFSection("\t.tbss", false,
312                                     SectionKind::getThreadBSS());
313
314  DataRelSection = getELFSection("\t.data.rel", false,
315                                      SectionKind::getDataRel());
316  DataRelLocalSection = getELFSection("\t.data.rel.local", false,
317                                   SectionKind::getDataRelLocal());
318  DataRelROSection = getELFSection("\t.data.rel.ro", false,
319                                SectionKind::getReadOnlyWithRel());
320  DataRelROLocalSection =
321    getELFSection("\t.data.rel.ro.local", false,
322                       SectionKind::getReadOnlyWithRelLocal());
323
324  MergeableConst4Section = getELFSection(".rodata.cst4", false,
325                                SectionKind::getMergeableConst4());
326  MergeableConst8Section = getELFSection(".rodata.cst8", false,
327                                SectionKind::getMergeableConst8());
328  MergeableConst16Section = getELFSection(".rodata.cst16", false,
329                               SectionKind::getMergeableConst16());
330
331  StaticCtorSection =
332    getELFSection(".ctors", false, SectionKind::getDataRel());
333  StaticDtorSection =
334    getELFSection(".dtors", false, SectionKind::getDataRel());
335
336  // Exception Handling Sections.
337
338  // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
339  // it contains relocatable pointers.  In PIC mode, this is probably a big
340  // runtime hit for C++ apps.  Either the contents of the LSDA need to be
341  // adjusted or this should be a data section.
342  LSDASection =
343    getELFSection(".gcc_except_table", false, SectionKind::getReadOnly());
344  EHFrameSection =
345    getELFSection(".eh_frame", false, SectionKind::getDataRel());
346
347  // Debug Info Sections.
348  DwarfAbbrevSection =
349    getELFSection(".debug_abbrev", false, SectionKind::getMetadata());
350  DwarfInfoSection =
351    getELFSection(".debug_info", false, SectionKind::getMetadata());
352  DwarfLineSection =
353    getELFSection(".debug_line", false, SectionKind::getMetadata());
354  DwarfFrameSection =
355    getELFSection(".debug_frame", false, SectionKind::getMetadata());
356  DwarfPubNamesSection =
357    getELFSection(".debug_pubnames", false, SectionKind::getMetadata());
358  DwarfPubTypesSection =
359    getELFSection(".debug_pubtypes", false, SectionKind::getMetadata());
360  DwarfStrSection =
361    getELFSection(".debug_str", false, SectionKind::getMetadata());
362  DwarfLocSection =
363    getELFSection(".debug_loc", false, SectionKind::getMetadata());
364  DwarfARangesSection =
365    getELFSection(".debug_aranges", false, SectionKind::getMetadata());
366  DwarfRangesSection =
367    getELFSection(".debug_ranges", false, SectionKind::getMetadata());
368  DwarfMacroInfoSection =
369    getELFSection(".debug_macinfo", false, SectionKind::getMetadata());
370}
371
372
373static SectionKind
374getELFKindForNamedSection(const char *Name, SectionKind K) {
375  if (Name[0] != '.') return K;
376
377  // Some lame default implementation based on some magic section names.
378  if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
379      strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
380      strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
381      strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
382    return SectionKind::getBSS();
383
384  if (strcmp(Name, ".tdata") == 0 ||
385      strncmp(Name, ".tdata.", 7) == 0 ||
386      strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
387      strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
388    return SectionKind::getThreadData();
389
390  if (strcmp(Name, ".tbss") == 0 ||
391      strncmp(Name, ".tbss.", 6) == 0 ||
392      strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
393      strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
394    return SectionKind::getThreadBSS();
395
396  return K;
397}
398
399const MCSection *TargetLoweringObjectFileELF::
400getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
401                         Mangler *Mang, const TargetMachine &TM) const {
402  // Infer section flags from the section name if we can.
403  Kind = getELFKindForNamedSection(GV->getSection().c_str(), Kind);
404
405  return getELFSection(GV->getSection().c_str(), false, Kind);
406}
407
408
409
410void TargetLoweringObjectFileELF::
411getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str,
412                        const TargetAsmInfo &TAI) const {
413  // Handle the weird solaris syntax if desired.
414  if (TAI.usesSunStyleELFSectionSwitchSyntax() &&
415      !Kind.isMergeableConst() && !Kind.isMergeableCString()) {
416    // FIXME: Inefficient.
417    std::string Res;
418    if (!Kind.isMetadata())
419      Res += ",#alloc";
420    if (Kind.isText())
421      Res += ",#execinstr";
422    if (Kind.isWriteable())
423      Res += ",#write";
424    if (Kind.isThreadLocal())
425      Res += ",#tls";
426    Str.append(Res.begin(), Res.end());
427    return;
428  }
429
430  Str.push_back(',');
431  Str.push_back('"');
432
433  if (!Kind.isMetadata())
434    Str.push_back('a');
435  if (Kind.isText())
436    Str.push_back('x');
437  if (Kind.isWriteable())
438    Str.push_back('w');
439  if (Kind.isMergeable1ByteCString() ||
440      Kind.isMergeable2ByteCString() ||
441      Kind.isMergeable4ByteCString() ||
442      Kind.isMergeableConst4() ||
443      Kind.isMergeableConst8() ||
444      Kind.isMergeableConst16())
445    Str.push_back('M');
446  if (Kind.isMergeable1ByteCString() ||
447      Kind.isMergeable2ByteCString() ||
448      Kind.isMergeable4ByteCString())
449    Str.push_back('S');
450  if (Kind.isThreadLocal())
451    Str.push_back('T');
452
453  Str.push_back('"');
454  Str.push_back(',');
455
456  // If comment string is '@', e.g. as on ARM - use '%' instead
457  if (AtIsCommentChar)
458    Str.push_back('%');
459  else
460    Str.push_back('@');
461
462  const char *KindStr;
463  if (Kind.isBSS() || Kind.isThreadBSS())
464    KindStr = "nobits";
465  else
466    KindStr = "progbits";
467
468  Str.append(KindStr, KindStr+strlen(KindStr));
469
470  if (Kind.isMergeable1ByteCString()) {
471    Str.push_back(',');
472    Str.push_back('1');
473  } else if (Kind.isMergeable2ByteCString()) {
474    Str.push_back(',');
475    Str.push_back('2');
476  } else if (Kind.isMergeable4ByteCString()) {
477    Str.push_back(',');
478    Str.push_back('4');
479  } else if (Kind.isMergeableConst4()) {
480    Str.push_back(',');
481    Str.push_back('4');
482  } else if (Kind.isMergeableConst8()) {
483    Str.push_back(',');
484    Str.push_back('8');
485  } else if (Kind.isMergeableConst16()) {
486    Str.push_back(',');
487    Str.push_back('1');
488    Str.push_back('6');
489  }
490}
491
492
493static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
494  if (Kind.isText())                 return ".gnu.linkonce.t.";
495  if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
496
497  if (Kind.isThreadData())           return ".gnu.linkonce.td.";
498  if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
499
500  if (Kind.isBSS())                  return ".gnu.linkonce.b.";
501  if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
502  if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
503  if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
504  if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
505
506  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
507  return ".gnu.linkonce.d.rel.ro.";
508}
509
510const MCSection *TargetLoweringObjectFileELF::
511SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
512                       Mangler *Mang, const TargetMachine &TM) const {
513
514  // If this global is linkonce/weak and the target handles this by emitting it
515  // into a 'uniqued' section name, create and return the section now.
516  if (GV->isWeakForLinker()) {
517    const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
518    std::string Name = Mang->makeNameProper(GV->getNameStr());
519    return getELFSection((Prefix+Name).c_str(), false, Kind);
520  }
521
522  if (Kind.isText()) return TextSection;
523
524  if (Kind.isMergeable1ByteCString() ||
525      Kind.isMergeable2ByteCString() ||
526      Kind.isMergeable4ByteCString()) {
527
528    // We also need alignment here.
529    // FIXME: this is getting the alignment of the character, not the
530    // alignment of the global!
531    unsigned Align =
532      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
533
534    const char *SizeSpec = ".rodata.str1.";
535    if (Kind.isMergeable2ByteCString())
536      SizeSpec = ".rodata.str2.";
537    else if (Kind.isMergeable4ByteCString())
538      SizeSpec = ".rodata.str4.";
539    else
540      assert(Kind.isMergeable1ByteCString() && "unknown string width");
541
542
543    std::string Name = SizeSpec + utostr(Align);
544    return getELFSection(Name.c_str(), false, Kind);
545  }
546
547  if (Kind.isMergeableConst()) {
548    if (Kind.isMergeableConst4())
549      return MergeableConst4Section;
550    if (Kind.isMergeableConst8())
551      return MergeableConst8Section;
552    if (Kind.isMergeableConst16())
553      return MergeableConst16Section;
554    return ReadOnlySection;  // .const
555  }
556
557  if (Kind.isReadOnly())             return ReadOnlySection;
558
559  if (Kind.isThreadData())           return TLSDataSection;
560  if (Kind.isThreadBSS())            return TLSBSSSection;
561
562  if (Kind.isBSS())                  return BSSSection;
563
564  if (Kind.isDataNoRel())            return DataSection;
565  if (Kind.isDataRelLocal())         return DataRelLocalSection;
566  if (Kind.isDataRel())              return DataRelSection;
567  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
568
569  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
570  return DataRelROSection;
571}
572
573/// getSectionForConstant - Given a mergeable constant with the
574/// specified size and relocation information, return a section that it
575/// should be placed in.
576const MCSection *TargetLoweringObjectFileELF::
577getSectionForConstant(SectionKind Kind) const {
578  if (Kind.isMergeableConst4())
579    return MergeableConst4Section;
580  if (Kind.isMergeableConst8())
581    return MergeableConst8Section;
582  if (Kind.isMergeableConst16())
583    return MergeableConst16Section;
584  if (Kind.isReadOnly())
585    return ReadOnlySection;
586
587  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
588  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
589  return DataRelROSection;
590}
591
592//===----------------------------------------------------------------------===//
593//                                 MachO
594//===----------------------------------------------------------------------===//
595
596
597const MCSection *TargetLoweringObjectFileMachO::
598getMachOSection(const char *Name, bool isDirective, SectionKind Kind) const {
599  if (MCSection *S = getContext().GetSection(Name))
600    return S;
601  return MCSection::Create(Name, isDirective, Kind, getContext());
602}
603
604
605
606void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
607                                               const TargetMachine &TM) {
608  TargetLoweringObjectFile::Initialize(Ctx, TM);
609  TextSection = getMachOSection("\t.text", true, SectionKind::getText());
610  DataSection = getMachOSection("\t.data", true, SectionKind::getDataRel());
611
612  CStringSection = getMachOSection("\t.cstring", true,
613                                   SectionKind::getMergeable1ByteCString());
614  UStringSection = getMachOSection("__TEXT,__ustring", false,
615                                   SectionKind::getMergeable2ByteCString());
616  FourByteConstantSection = getMachOSection("\t.literal4\n", true,
617                                            SectionKind::getMergeableConst4());
618  EightByteConstantSection = getMachOSection("\t.literal8\n", true,
619                                             SectionKind::getMergeableConst8());
620
621  // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
622  // to using it in -static mode.
623  if (TM.getRelocationModel() != Reloc::Static &&
624      TM.getTargetData()->getPointerSize() == 32)
625    SixteenByteConstantSection =
626      getMachOSection("\t.literal16\n", true,
627                      SectionKind::getMergeableConst16());
628  else
629    SixteenByteConstantSection = 0;
630
631  ReadOnlySection = getMachOSection("\t.const", true,
632                                    SectionKind::getReadOnly());
633
634  TextCoalSection =
635    getMachOSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
636                    false, SectionKind::getText());
637  ConstTextCoalSection = getMachOSection("\t__TEXT,__const_coal,coalesced",
638                                         false, SectionKind::getText());
639  ConstDataCoalSection = getMachOSection("\t__DATA,__const_coal,coalesced",
640                                         false, SectionKind::getText());
641  ConstDataSection = getMachOSection("\t.const_data", true,
642                                     SectionKind::getReadOnlyWithRel());
643  DataCoalSection = getMachOSection("\t__DATA,__datacoal_nt,coalesced",
644                                    false, SectionKind::getDataRel());
645
646  if (TM.getRelocationModel() == Reloc::Static) {
647    StaticCtorSection =
648      getMachOSection(".constructor", true, SectionKind::getDataRel());
649    StaticDtorSection =
650      getMachOSection(".destructor", true, SectionKind::getDataRel());
651  } else {
652    StaticCtorSection =
653      getMachOSection(".mod_init_func", true, SectionKind::getDataRel());
654    StaticDtorSection =
655      getMachOSection(".mod_term_func", true, SectionKind::getDataRel());
656  }
657
658  // Exception Handling.
659  LSDASection = getMachOSection("__DATA,__gcc_except_tab", false,
660                                SectionKind::getDataRel());
661  EHFrameSection =
662    getMachOSection("__TEXT,__eh_frame,coalesced,no_toc+strip_static_syms"
663                    "+live_support", false, SectionKind::getReadOnly());
664
665  // Debug Information.
666  // FIXME: Don't use 'directive' syntax: need flags for debug/regular??
667  // FIXME: Need __DWARF segment.
668  DwarfAbbrevSection =
669    getMachOSection(".section __DWARF,__debug_abbrev,regular,debug", true,
670                    SectionKind::getMetadata());
671  DwarfInfoSection =
672    getMachOSection(".section __DWARF,__debug_info,regular,debug", true,
673                    SectionKind::getMetadata());
674  DwarfLineSection =
675    getMachOSection(".section __DWARF,__debug_line,regular,debug", true,
676                    SectionKind::getMetadata());
677  DwarfFrameSection =
678    getMachOSection(".section __DWARF,__debug_frame,regular,debug", true,
679                    SectionKind::getMetadata());
680  DwarfPubNamesSection =
681    getMachOSection(".section __DWARF,__debug_pubnames,regular,debug", true,
682                    SectionKind::getMetadata());
683  DwarfPubTypesSection =
684    getMachOSection(".section __DWARF,__debug_pubtypes,regular,debug", true,
685                    SectionKind::getMetadata());
686  DwarfStrSection =
687    getMachOSection(".section __DWARF,__debug_str,regular,debug", true,
688                    SectionKind::getMetadata());
689  DwarfLocSection =
690    getMachOSection(".section __DWARF,__debug_loc,regular,debug", true,
691                    SectionKind::getMetadata());
692  DwarfARangesSection =
693    getMachOSection(".section __DWARF,__debug_aranges,regular,debug", true,
694                    SectionKind::getMetadata());
695  DwarfRangesSection =
696    getMachOSection(".section __DWARF,__debug_ranges,regular,debug", true,
697                    SectionKind::getMetadata());
698  DwarfMacroInfoSection =
699    getMachOSection(".section __DWARF,__debug_macinfo,regular,debug", true,
700                    SectionKind::getMetadata());
701  DwarfDebugInlineSection =
702    getMachOSection(".section __DWARF,__debug_inlined,regular,debug", true,
703                    SectionKind::getMetadata());
704}
705
706const MCSection *TargetLoweringObjectFileMachO::
707getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
708                         Mangler *Mang, const TargetMachine &TM) const {
709  return getMachOSection(GV->getSection().c_str(), false, Kind);
710}
711
712const MCSection *TargetLoweringObjectFileMachO::
713SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
714                       Mangler *Mang, const TargetMachine &TM) const {
715  assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
716
717  if (Kind.isText())
718    return GV->isWeakForLinker() ? TextCoalSection : TextSection;
719
720  // If this is weak/linkonce, put this in a coalescable section, either in text
721  // or data depending on if it is writable.
722  if (GV->isWeakForLinker()) {
723    if (Kind.isReadOnly())
724      return ConstTextCoalSection;
725    return DataCoalSection;
726  }
727
728  // FIXME: Alignment check should be handled by section classifier.
729  if (Kind.isMergeable1ByteCString() ||
730      Kind.isMergeable2ByteCString()) {
731    if (TM.getTargetData()->getPreferredAlignment(
732                                              cast<GlobalVariable>(GV)) < 32) {
733      if (Kind.isMergeable1ByteCString())
734        return CStringSection;
735      assert(Kind.isMergeable2ByteCString());
736      return UStringSection;
737    }
738  }
739
740  if (Kind.isMergeableConst()) {
741    if (Kind.isMergeableConst4())
742      return FourByteConstantSection;
743    if (Kind.isMergeableConst8())
744      return EightByteConstantSection;
745    if (Kind.isMergeableConst16() && SixteenByteConstantSection)
746      return SixteenByteConstantSection;
747  }
748
749  // Otherwise, if it is readonly, but not something we can specially optimize,
750  // just drop it in .const.
751  if (Kind.isReadOnly())
752    return ReadOnlySection;
753
754  // If this is marked const, put it into a const section.  But if the dynamic
755  // linker needs to write to it, put it in the data segment.
756  if (Kind.isReadOnlyWithRel())
757    return ConstDataSection;
758
759  // Otherwise, just drop the variable in the normal data section.
760  return DataSection;
761}
762
763const MCSection *
764TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
765  // If this constant requires a relocation, we have to put it in the data
766  // segment, not in the text segment.
767  if (Kind.isDataRel())
768    return ConstDataSection;
769
770  if (Kind.isMergeableConst4())
771    return FourByteConstantSection;
772  if (Kind.isMergeableConst8())
773    return EightByteConstantSection;
774  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
775    return SixteenByteConstantSection;
776  return ReadOnlySection;  // .const
777}
778
779/// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
780/// not to emit the UsedDirective for some symbols in llvm.used.
781// FIXME: REMOVE this (rdar://7071300)
782bool TargetLoweringObjectFileMachO::
783shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
784  /// On Darwin, internally linked data beginning with "L" or "l" does not have
785  /// the directive emitted (this occurs in ObjC metadata).
786  if (!GV) return false;
787
788  // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
789  if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
790    // FIXME: ObjC metadata is currently emitted as internal symbols that have
791    // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
792    // this horrible hack can go away.
793    const std::string &Name = Mang->getMangledName(GV);
794    if (Name[0] == 'L' || Name[0] == 'l')
795      return false;
796  }
797
798  return true;
799}
800
801
802//===----------------------------------------------------------------------===//
803//                                  COFF
804//===----------------------------------------------------------------------===//
805
806
807const MCSection *TargetLoweringObjectFileCOFF::
808getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
809  if (MCSection *S = getContext().GetSection(Name))
810    return S;
811  return MCSection::Create(Name, isDirective, Kind, getContext());
812}
813
814void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
815                                              const TargetMachine &TM) {
816  TargetLoweringObjectFile::Initialize(Ctx, TM);
817  TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
818  DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
819  StaticCtorSection =
820    getCOFFSection(".ctors", false, SectionKind::getDataRel());
821  StaticDtorSection =
822    getCOFFSection(".dtors", false, SectionKind::getDataRel());
823
824
825  // Debug info.
826  // FIXME: Don't use 'directive' mode here.
827  DwarfAbbrevSection =
828    getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
829                   true, SectionKind::getMetadata());
830  DwarfInfoSection =
831    getCOFFSection("\t.section\t.debug_info,\"dr\"",
832                   true, SectionKind::getMetadata());
833  DwarfLineSection =
834    getCOFFSection("\t.section\t.debug_line,\"dr\"",
835                   true, SectionKind::getMetadata());
836  DwarfFrameSection =
837    getCOFFSection("\t.section\t.debug_frame,\"dr\"",
838                   true, SectionKind::getMetadata());
839  DwarfPubNamesSection =
840    getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
841                   true, SectionKind::getMetadata());
842  DwarfPubTypesSection =
843    getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
844                   true, SectionKind::getMetadata());
845  DwarfStrSection =
846    getCOFFSection("\t.section\t.debug_str,\"dr\"",
847                   true, SectionKind::getMetadata());
848  DwarfLocSection =
849    getCOFFSection("\t.section\t.debug_loc,\"dr\"",
850                   true, SectionKind::getMetadata());
851  DwarfARangesSection =
852    getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
853                   true, SectionKind::getMetadata());
854  DwarfRangesSection =
855    getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
856                   true, SectionKind::getMetadata());
857  DwarfMacroInfoSection =
858    getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
859                   true, SectionKind::getMetadata());
860}
861
862const MCSection *TargetLoweringObjectFileCOFF::
863getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
864                         Mangler *Mang, const TargetMachine &TM) const {
865  return getCOFFSection(GV->getSection().c_str(), false, Kind);
866}
867
868
869void TargetLoweringObjectFileCOFF::
870getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str,
871                        const TargetAsmInfo &TAI) const {
872  // FIXME: Inefficient.
873  std::string Res = ",\"";
874  if (Kind.isText())
875    Res += 'x';
876  if (Kind.isWriteable())
877    Res += 'w';
878  Res += "\"";
879
880  Str.append(Res.begin(), Res.end());
881}
882
883static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
884  if (Kind.isText())
885    return ".text$linkonce";
886  if (Kind.isWriteable())
887    return ".data$linkonce";
888  return ".rdata$linkonce";
889}
890
891
892const MCSection *TargetLoweringObjectFileCOFF::
893SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
894                       Mangler *Mang, const TargetMachine &TM) const {
895  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
896
897  // If this global is linkonce/weak and the target handles this by emitting it
898  // into a 'uniqued' section name, create and return the section now.
899  if (GV->isWeakForLinker()) {
900    const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
901    std::string Name = Mang->makeNameProper(GV->getNameStr());
902    return getCOFFSection((Prefix+Name).c_str(), false, Kind);
903  }
904
905  if (Kind.isText())
906    return getTextSection();
907
908  return getDataSection();
909}
910
911