TargetLoweringObjectFileImpl.cpp revision 4edab1a9e8fd28a60b2d09cc38333652155c0a20
1//===-- llvm/CodeGen/TargetLoweringObjectFileImpl.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/CodeGen/TargetLoweringObjectFileImpl.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/CodeGen/MachineModuleInfoImpls.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCSectionMachO.h"
24#include "llvm/MC/MCSectionELF.h"
25#include "llvm/MC/MCSectionCOFF.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/Target/Mangler.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetOptions.h"
31#include "llvm/Support/Dwarf.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/ADT/Triple.h"
37using namespace llvm;
38using namespace dwarf;
39
40//===----------------------------------------------------------------------===//
41//                                  ELF
42//===----------------------------------------------------------------------===//
43
44void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
45                                             const TargetMachine &TM) {
46  TargetLoweringObjectFile::Initialize(Ctx, TM);
47
48  BSSSection =
49    getContext().getELFSection(".bss", MCSectionELF::SHT_NOBITS,
50                               MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
51                               SectionKind::getBSS());
52
53  TextSection =
54    getContext().getELFSection(".text", MCSectionELF::SHT_PROGBITS,
55                               MCSectionELF::SHF_EXECINSTR |
56                               MCSectionELF::SHF_ALLOC,
57                               SectionKind::getText());
58
59  DataSection =
60    getContext().getELFSection(".data", MCSectionELF::SHT_PROGBITS,
61                               MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
62                               SectionKind::getDataRel());
63
64  ReadOnlySection =
65    getContext().getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
66                               MCSectionELF::SHF_ALLOC,
67                               SectionKind::getReadOnly());
68
69  TLSDataSection =
70    getContext().getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
71                               MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
72                               MCSectionELF::SHF_WRITE,
73                               SectionKind::getThreadData());
74
75  TLSBSSSection =
76    getContext().getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
77                               MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
78                               MCSectionELF::SHF_WRITE,
79                               SectionKind::getThreadBSS());
80
81  DataRelSection =
82    getContext().getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
83                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
84                               SectionKind::getDataRel());
85
86  DataRelLocalSection =
87    getContext().getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
88                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
89                               SectionKind::getDataRelLocal());
90
91  DataRelROSection =
92    getContext().getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
93                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
94                               SectionKind::getReadOnlyWithRel());
95
96  DataRelROLocalSection =
97    getContext().getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
98                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
99                               SectionKind::getReadOnlyWithRelLocal());
100
101  MergeableConst4Section =
102    getContext().getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
103                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_MERGE,
104                               SectionKind::getMergeableConst4());
105
106  MergeableConst8Section =
107    getContext().getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
108                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_MERGE,
109                               SectionKind::getMergeableConst8());
110
111  MergeableConst16Section =
112    getContext().getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
113                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_MERGE,
114                               SectionKind::getMergeableConst16());
115
116  StaticCtorSection =
117    getContext().getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
118                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
119                               SectionKind::getDataRel());
120
121  StaticDtorSection =
122    getContext().getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
123                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
124                               SectionKind::getDataRel());
125
126  // Exception Handling Sections.
127
128  // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
129  // it contains relocatable pointers.  In PIC mode, this is probably a big
130  // runtime hit for C++ apps.  Either the contents of the LSDA need to be
131  // adjusted or this should be a data section.
132  LSDASection =
133    getContext().getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
134                               MCSectionELF::SHF_ALLOC,
135                               SectionKind::getReadOnly());
136  EHFrameSection =
137    getContext().getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
138                               MCSectionELF::SHF_ALLOC |MCSectionELF::SHF_WRITE,
139                               SectionKind::getDataRel());
140
141  // Debug Info Sections.
142  DwarfAbbrevSection =
143    getContext().getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
144                               SectionKind::getMetadata());
145  DwarfInfoSection =
146    getContext().getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
147                               SectionKind::getMetadata());
148  DwarfLineSection =
149    getContext().getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
150                               SectionKind::getMetadata());
151  DwarfFrameSection =
152    getContext().getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
153                               SectionKind::getMetadata());
154  DwarfPubNamesSection =
155    getContext().getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
156                               SectionKind::getMetadata());
157  DwarfPubTypesSection =
158    getContext().getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
159                               SectionKind::getMetadata());
160  DwarfStrSection =
161    getContext().getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
162                               SectionKind::getMetadata());
163  DwarfLocSection =
164    getContext().getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
165                               SectionKind::getMetadata());
166  DwarfARangesSection =
167    getContext().getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
168                               SectionKind::getMetadata());
169  DwarfRangesSection =
170    getContext().getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
171                               SectionKind::getMetadata());
172  DwarfMacroInfoSection =
173    getContext().getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
174                               SectionKind::getMetadata());
175}
176
177
178static SectionKind
179getELFKindForNamedSection(StringRef Name, SectionKind K) {
180  if (Name.empty() || Name[0] != '.') return K;
181
182  // Some lame default implementation based on some magic section names.
183  if (Name == ".bss" ||
184      Name.startswith(".bss.") ||
185      Name.startswith(".gnu.linkonce.b.") ||
186      Name.startswith(".llvm.linkonce.b.") ||
187      Name == ".sbss" ||
188      Name.startswith(".sbss.") ||
189      Name.startswith(".gnu.linkonce.sb.") ||
190      Name.startswith(".llvm.linkonce.sb."))
191    return SectionKind::getBSS();
192
193  if (Name == ".tdata" ||
194      Name.startswith(".tdata.") ||
195      Name.startswith(".gnu.linkonce.td.") ||
196      Name.startswith(".llvm.linkonce.td."))
197    return SectionKind::getThreadData();
198
199  if (Name == ".tbss" ||
200      Name.startswith(".tbss.") ||
201      Name.startswith(".gnu.linkonce.tb.") ||
202      Name.startswith(".llvm.linkonce.tb."))
203    return SectionKind::getThreadBSS();
204
205  return K;
206}
207
208
209static unsigned getELFSectionType(StringRef Name, SectionKind K) {
210
211  if (Name == ".init_array")
212    return MCSectionELF::SHT_INIT_ARRAY;
213
214  if (Name == ".fini_array")
215    return MCSectionELF::SHT_FINI_ARRAY;
216
217  if (Name == ".preinit_array")
218    return MCSectionELF::SHT_PREINIT_ARRAY;
219
220  if (K.isBSS() || K.isThreadBSS())
221    return MCSectionELF::SHT_NOBITS;
222
223  return MCSectionELF::SHT_PROGBITS;
224}
225
226
227static unsigned
228getELFSectionFlags(SectionKind K) {
229  unsigned Flags = 0;
230
231  if (!K.isMetadata())
232    Flags |= MCSectionELF::SHF_ALLOC;
233
234  if (K.isText())
235    Flags |= MCSectionELF::SHF_EXECINSTR;
236
237  if (K.isWriteable())
238    Flags |= MCSectionELF::SHF_WRITE;
239
240  if (K.isThreadLocal())
241    Flags |= MCSectionELF::SHF_TLS;
242
243  // K.isMergeableConst() is left out to honour PR4650
244  if (K.isMergeableCString() || K.isMergeableConst4() ||
245      K.isMergeableConst8() || K.isMergeableConst16())
246    Flags |= MCSectionELF::SHF_MERGE;
247
248  if (K.isMergeableCString())
249    Flags |= MCSectionELF::SHF_STRINGS;
250
251  return Flags;
252}
253
254
255const MCSection *TargetLoweringObjectFileELF::
256getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
257                         Mangler *Mang, const TargetMachine &TM) const {
258  StringRef SectionName = GV->getSection();
259
260  // Infer section flags from the section name if we can.
261  Kind = getELFKindForNamedSection(SectionName, Kind);
262
263  return getContext().getELFSection(SectionName,
264                                    getELFSectionType(SectionName, Kind),
265                                    getELFSectionFlags(Kind), Kind, true);
266}
267
268static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
269  if (Kind.isText())                 return ".gnu.linkonce.t.";
270  if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
271
272  if (Kind.isThreadData())           return ".gnu.linkonce.td.";
273  if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
274
275  if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
276  if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
277  if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
278  if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
279
280  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
281  return ".gnu.linkonce.d.rel.ro.";
282}
283
284/// getSectionPrefixForGlobal - Return the section prefix name used by options
285/// FunctionsSections and DataSections.
286static const char *getSectionPrefixForGlobal(SectionKind Kind) {
287  if (Kind.isText())                 return ".text.";
288  if (Kind.isReadOnly())             return ".rodata.";
289
290  if (Kind.isThreadData())           return ".tdata.";
291  if (Kind.isThreadBSS())            return ".tbss.";
292
293  if (Kind.isDataNoRel())            return ".data.";
294  if (Kind.isDataRelLocal())         return ".data.rel.local.";
295  if (Kind.isDataRel())              return ".data.rel.";
296  if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
297
298  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
299  return ".data.rel.ro.";
300}
301
302
303const MCSection *TargetLoweringObjectFileELF::
304SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
305                       Mangler *Mang, const TargetMachine &TM) const {
306  // If we have -ffunction-section or -fdata-section then we should emit the
307  // global value to a uniqued section specifically for it.
308  bool EmitUniquedSection;
309  if (Kind.isText())
310    EmitUniquedSection = TM.getFunctionSections();
311  else
312    EmitUniquedSection = TM.getDataSections();
313
314  // If this global is linkonce/weak and the target handles this by emitting it
315  // into a 'uniqued' section name, create and return the section now.
316  if ((GV->isWeakForLinker() || EmitUniquedSection) &&
317      !Kind.isCommon() && !Kind.isBSS()) {
318    const char *Prefix;
319    if (GV->isWeakForLinker())
320      Prefix = getSectionPrefixForUniqueGlobal(Kind);
321    else {
322      assert(EmitUniquedSection);
323      Prefix = getSectionPrefixForGlobal(Kind);
324    }
325
326    SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
327    MCSymbol *Sym = Mang->getSymbol(GV);
328    Name.append(Sym->getName().begin(), Sym->getName().end());
329    return getContext().getELFSection(Name.str(),
330                                      getELFSectionType(Name.str(), Kind),
331                                      getELFSectionFlags(Kind), Kind);
332  }
333
334  if (Kind.isText()) return TextSection;
335
336  if (Kind.isMergeable1ByteCString() ||
337      Kind.isMergeable2ByteCString() ||
338      Kind.isMergeable4ByteCString()) {
339
340    // We also need alignment here.
341    // FIXME: this is getting the alignment of the character, not the
342    // alignment of the global!
343    unsigned Align =
344      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
345
346    const char *SizeSpec = ".rodata.str1.";
347    if (Kind.isMergeable2ByteCString())
348      SizeSpec = ".rodata.str2.";
349    else if (Kind.isMergeable4ByteCString())
350      SizeSpec = ".rodata.str4.";
351    else
352      assert(Kind.isMergeable1ByteCString() && "unknown string width");
353
354
355    std::string Name = SizeSpec + utostr(Align);
356    return getContext().getELFSection(Name, MCSectionELF::SHT_PROGBITS,
357                                      MCSectionELF::SHF_ALLOC |
358                                      MCSectionELF::SHF_MERGE |
359                                      MCSectionELF::SHF_STRINGS,
360                                      Kind);
361  }
362
363  if (Kind.isMergeableConst()) {
364    if (Kind.isMergeableConst4() && MergeableConst4Section)
365      return MergeableConst4Section;
366    if (Kind.isMergeableConst8() && MergeableConst8Section)
367      return MergeableConst8Section;
368    if (Kind.isMergeableConst16() && MergeableConst16Section)
369      return MergeableConst16Section;
370    return ReadOnlySection;  // .const
371  }
372
373  if (Kind.isReadOnly())             return ReadOnlySection;
374
375  if (Kind.isThreadData())           return TLSDataSection;
376  if (Kind.isThreadBSS())            return TLSBSSSection;
377
378  // Note: we claim that common symbols are put in BSSSection, but they are
379  // really emitted with the magic .comm directive, which creates a symbol table
380  // entry but not a section.
381  if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
382
383  if (Kind.isDataNoRel())            return DataSection;
384  if (Kind.isDataRelLocal())         return DataRelLocalSection;
385  if (Kind.isDataRel())              return DataRelSection;
386  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
387
388  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
389  return DataRelROSection;
390}
391
392/// getSectionForConstant - Given a mergeable constant with the
393/// specified size and relocation information, return a section that it
394/// should be placed in.
395const MCSection *TargetLoweringObjectFileELF::
396getSectionForConstant(SectionKind Kind) const {
397  if (Kind.isMergeableConst4() && MergeableConst4Section)
398    return MergeableConst4Section;
399  if (Kind.isMergeableConst8() && MergeableConst8Section)
400    return MergeableConst8Section;
401  if (Kind.isMergeableConst16() && MergeableConst16Section)
402    return MergeableConst16Section;
403  if (Kind.isReadOnly())
404    return ReadOnlySection;
405
406  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
407  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
408  return DataRelROSection;
409}
410
411const MCExpr *TargetLoweringObjectFileELF::
412getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
413                               MachineModuleInfo *MMI,
414                               unsigned Encoding, MCStreamer &Streamer) const {
415
416  if (Encoding & dwarf::DW_EH_PE_indirect) {
417    MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
418
419    SmallString<128> Name;
420    Mang->getNameWithPrefix(Name, GV, true);
421    Name += ".DW.stub";
422
423    // Add information about the stub reference to ELFMMI so that the stub
424    // gets emitted by the asmprinter.
425    MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
426    MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
427    if (StubSym.getPointer() == 0) {
428      MCSymbol *Sym = Mang->getSymbol(GV);
429      StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
430    }
431
432    return TargetLoweringObjectFile::
433      getExprForDwarfReference(SSym, Mang, MMI,
434                               Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
435  }
436
437  return TargetLoweringObjectFile::
438    getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
439}
440
441//===----------------------------------------------------------------------===//
442//                                 MachO
443//===----------------------------------------------------------------------===//
444
445void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
446                                               const TargetMachine &TM) {
447  IsFunctionEHSymbolGlobal = true;
448  IsFunctionEHFrameSymbolPrivate = false;
449  SupportsWeakOmittedEHFrame = false;
450
451  Triple T(((LLVMTargetMachine&)TM).getTargetTriple());
452  if (T.getOS() == Triple::Darwin) {
453    unsigned MajNum = T.getDarwinMajorNumber();
454    if (MajNum == 7 || MajNum == 8) // 10.3 Panther, 10.4 Tiger
455      CommDirectiveSupportsAlignment = false;
456    if (MajNum > 9)                 // 10.6 SnowLeopard
457      IsFunctionEHSymbolGlobal = false;
458  }
459
460  TargetLoweringObjectFile::Initialize(Ctx, TM);
461
462  TextSection // .text
463    = getContext().getMachOSection("__TEXT", "__text",
464                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
465                                   SectionKind::getText());
466  DataSection // .data
467    = getContext().getMachOSection("__DATA", "__data", 0,
468                                   SectionKind::getDataRel());
469
470  TLSDataSection // .tdata
471    = getContext().getMachOSection("__DATA", "__thread_data",
472                                   MCSectionMachO::S_THREAD_LOCAL_REGULAR,
473                                   SectionKind::getDataRel());
474  TLSBSSSection // .tbss
475    = getContext().getMachOSection("__DATA", "__thread_bss",
476                                   MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
477                                   SectionKind::getThreadBSS());
478
479  // TODO: Verify datarel below.
480  TLSTLVSection // .tlv
481    = getContext().getMachOSection("__DATA", "__thread_vars",
482                                   MCSectionMachO::S_THREAD_LOCAL_VARIABLES,
483                                   SectionKind::getDataRel());
484
485  TLSThreadInitSection
486    = getContext().getMachOSection("__DATA", "__thread_init",
487                          MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS,
488                          SectionKind::getDataRel());
489
490  CStringSection // .cstring
491    = getContext().getMachOSection("__TEXT", "__cstring",
492                                   MCSectionMachO::S_CSTRING_LITERALS,
493                                   SectionKind::getMergeable1ByteCString());
494  UStringSection
495    = getContext().getMachOSection("__TEXT","__ustring", 0,
496                                   SectionKind::getMergeable2ByteCString());
497  FourByteConstantSection // .literal4
498    = getContext().getMachOSection("__TEXT", "__literal4",
499                                   MCSectionMachO::S_4BYTE_LITERALS,
500                                   SectionKind::getMergeableConst4());
501  EightByteConstantSection // .literal8
502    = getContext().getMachOSection("__TEXT", "__literal8",
503                                   MCSectionMachO::S_8BYTE_LITERALS,
504                                   SectionKind::getMergeableConst8());
505
506  // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
507  // to using it in -static mode.
508  SixteenByteConstantSection = 0;
509  if (TM.getRelocationModel() != Reloc::Static &&
510      TM.getTargetData()->getPointerSize() == 32)
511    SixteenByteConstantSection =   // .literal16
512      getContext().getMachOSection("__TEXT", "__literal16",
513                                   MCSectionMachO::S_16BYTE_LITERALS,
514                                   SectionKind::getMergeableConst16());
515
516  ReadOnlySection  // .const
517    = getContext().getMachOSection("__TEXT", "__const", 0,
518                                   SectionKind::getReadOnly());
519
520  TextCoalSection
521    = getContext().getMachOSection("__TEXT", "__textcoal_nt",
522                                   MCSectionMachO::S_COALESCED |
523                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
524                                   SectionKind::getText());
525  ConstTextCoalSection
526    = getContext().getMachOSection("__TEXT", "__const_coal",
527                                   MCSectionMachO::S_COALESCED,
528                                   SectionKind::getReadOnly());
529  ConstDataSection  // .const_data
530    = getContext().getMachOSection("__DATA", "__const", 0,
531                                   SectionKind::getReadOnlyWithRel());
532  DataCoalSection
533    = getContext().getMachOSection("__DATA","__datacoal_nt",
534                                   MCSectionMachO::S_COALESCED,
535                                   SectionKind::getDataRel());
536  DataCommonSection
537    = getContext().getMachOSection("__DATA","__common",
538                                   MCSectionMachO::S_ZEROFILL,
539                                   SectionKind::getBSS());
540  DataBSSSection
541    = getContext().getMachOSection("__DATA","__bss", MCSectionMachO::S_ZEROFILL,
542                                   SectionKind::getBSS());
543
544
545  LazySymbolPointerSection
546    = getContext().getMachOSection("__DATA", "__la_symbol_ptr",
547                                   MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
548                                   SectionKind::getMetadata());
549  NonLazySymbolPointerSection
550    = getContext().getMachOSection("__DATA", "__nl_symbol_ptr",
551                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
552                                   SectionKind::getMetadata());
553
554  if (TM.getRelocationModel() == Reloc::Static) {
555    StaticCtorSection
556      = getContext().getMachOSection("__TEXT", "__constructor", 0,
557                                     SectionKind::getDataRel());
558    StaticDtorSection
559      = getContext().getMachOSection("__TEXT", "__destructor", 0,
560                                     SectionKind::getDataRel());
561  } else {
562    StaticCtorSection
563      = getContext().getMachOSection("__DATA", "__mod_init_func",
564                                     MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
565                                     SectionKind::getDataRel());
566    StaticDtorSection
567      = getContext().getMachOSection("__DATA", "__mod_term_func",
568                                     MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
569                                     SectionKind::getDataRel());
570  }
571
572  // Exception Handling.
573  LSDASection = getContext().getMachOSection("__TEXT", "__gcc_except_tab", 0,
574                                             SectionKind::getReadOnlyWithRel());
575  EHFrameSection =
576    getContext().getMachOSection("__TEXT", "__eh_frame",
577                                 MCSectionMachO::S_COALESCED |
578                                 MCSectionMachO::S_ATTR_NO_TOC |
579                                 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
580                                 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
581                                 SectionKind::getReadOnly());
582
583  // Debug Information.
584  DwarfAbbrevSection =
585    getContext().getMachOSection("__DWARF", "__debug_abbrev",
586                                 MCSectionMachO::S_ATTR_DEBUG,
587                                 SectionKind::getMetadata());
588  DwarfInfoSection =
589    getContext().getMachOSection("__DWARF", "__debug_info",
590                                 MCSectionMachO::S_ATTR_DEBUG,
591                                 SectionKind::getMetadata());
592  DwarfLineSection =
593    getContext().getMachOSection("__DWARF", "__debug_line",
594                                 MCSectionMachO::S_ATTR_DEBUG,
595                                 SectionKind::getMetadata());
596  DwarfFrameSection =
597    getContext().getMachOSection("__DWARF", "__debug_frame",
598                                 MCSectionMachO::S_ATTR_DEBUG,
599                                 SectionKind::getMetadata());
600  DwarfPubNamesSection =
601    getContext().getMachOSection("__DWARF", "__debug_pubnames",
602                                 MCSectionMachO::S_ATTR_DEBUG,
603                                 SectionKind::getMetadata());
604  DwarfPubTypesSection =
605    getContext().getMachOSection("__DWARF", "__debug_pubtypes",
606                                 MCSectionMachO::S_ATTR_DEBUG,
607                                 SectionKind::getMetadata());
608  DwarfStrSection =
609    getContext().getMachOSection("__DWARF", "__debug_str",
610                                 MCSectionMachO::S_ATTR_DEBUG,
611                                 SectionKind::getMetadata());
612  DwarfLocSection =
613    getContext().getMachOSection("__DWARF", "__debug_loc",
614                                 MCSectionMachO::S_ATTR_DEBUG,
615                                 SectionKind::getMetadata());
616  DwarfARangesSection =
617    getContext().getMachOSection("__DWARF", "__debug_aranges",
618                                 MCSectionMachO::S_ATTR_DEBUG,
619                                 SectionKind::getMetadata());
620  DwarfRangesSection =
621    getContext().getMachOSection("__DWARF", "__debug_ranges",
622                                 MCSectionMachO::S_ATTR_DEBUG,
623                                 SectionKind::getMetadata());
624  DwarfMacroInfoSection =
625    getContext().getMachOSection("__DWARF", "__debug_macinfo",
626                                 MCSectionMachO::S_ATTR_DEBUG,
627                                 SectionKind::getMetadata());
628  DwarfDebugInlineSection =
629    getContext().getMachOSection("__DWARF", "__debug_inlined",
630                                 MCSectionMachO::S_ATTR_DEBUG,
631                                 SectionKind::getMetadata());
632
633  TLSExtraDataSection = TLSTLVSection;
634}
635
636const MCSection *TargetLoweringObjectFileMachO::
637getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
638                         Mangler *Mang, const TargetMachine &TM) const {
639  // Parse the section specifier and create it if valid.
640  StringRef Segment, Section;
641  unsigned TAA, StubSize;
642  std::string ErrorCode =
643    MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
644                                          TAA, StubSize);
645  if (!ErrorCode.empty()) {
646    // If invalid, report the error with report_fatal_error.
647    report_fatal_error("Global variable '" + GV->getNameStr() +
648                      "' has an invalid section specifier '" + GV->getSection()+
649                      "': " + ErrorCode + ".");
650    // Fall back to dropping it into the data section.
651    return DataSection;
652  }
653
654  // Get the section.
655  const MCSectionMachO *S =
656    getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
657
658  // Okay, now that we got the section, verify that the TAA & StubSize agree.
659  // If the user declared multiple globals with different section flags, we need
660  // to reject it here.
661  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
662    // If invalid, report the error with report_fatal_error.
663    report_fatal_error("Global variable '" + GV->getNameStr() +
664                      "' section type or attributes does not match previous"
665                      " section specifier");
666  }
667
668  return S;
669}
670
671const MCSection *TargetLoweringObjectFileMachO::
672SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
673                       Mangler *Mang, const TargetMachine &TM) const {
674
675  // Handle thread local data.
676  if (Kind.isThreadBSS()) return TLSBSSSection;
677  if (Kind.isThreadData()) return TLSDataSection;
678
679  if (Kind.isText())
680    return GV->isWeakForLinker() ? TextCoalSection : TextSection;
681
682  // If this is weak/linkonce, put this in a coalescable section, either in text
683  // or data depending on if it is writable.
684  if (GV->isWeakForLinker()) {
685    if (Kind.isReadOnly())
686      return ConstTextCoalSection;
687    return DataCoalSection;
688  }
689
690  // FIXME: Alignment check should be handled by section classifier.
691  if (Kind.isMergeable1ByteCString() &&
692      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
693    return CStringSection;
694
695  // Do not put 16-bit arrays in the UString section if they have an
696  // externally visible label, this runs into issues with certain linker
697  // versions.
698  if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
699      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
700    return UStringSection;
701
702  if (Kind.isMergeableConst()) {
703    if (Kind.isMergeableConst4())
704      return FourByteConstantSection;
705    if (Kind.isMergeableConst8())
706      return EightByteConstantSection;
707    if (Kind.isMergeableConst16() && SixteenByteConstantSection)
708      return SixteenByteConstantSection;
709  }
710
711  // Otherwise, if it is readonly, but not something we can specially optimize,
712  // just drop it in .const.
713  if (Kind.isReadOnly())
714    return ReadOnlySection;
715
716  // If this is marked const, put it into a const section.  But if the dynamic
717  // linker needs to write to it, put it in the data segment.
718  if (Kind.isReadOnlyWithRel())
719    return ConstDataSection;
720
721  // Put zero initialized globals with strong external linkage in the
722  // DATA, __common section with the .zerofill directive.
723  if (Kind.isBSSExtern())
724    return DataCommonSection;
725
726  // Put zero initialized globals with local linkage in __DATA,__bss directive
727  // with the .zerofill directive (aka .lcomm).
728  if (Kind.isBSSLocal())
729    return DataBSSSection;
730
731  // Otherwise, just drop the variable in the normal data section.
732  return DataSection;
733}
734
735const MCSection *
736TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
737  // If this constant requires a relocation, we have to put it in the data
738  // segment, not in the text segment.
739  if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
740    return ConstDataSection;
741
742  if (Kind.isMergeableConst4())
743    return FourByteConstantSection;
744  if (Kind.isMergeableConst8())
745    return EightByteConstantSection;
746  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
747    return SixteenByteConstantSection;
748  return ReadOnlySection;  // .const
749}
750
751/// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
752/// not to emit the UsedDirective for some symbols in llvm.used.
753// FIXME: REMOVE this (rdar://7071300)
754bool TargetLoweringObjectFileMachO::
755shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
756  /// On Darwin, internally linked data beginning with "L" or "l" does not have
757  /// the directive emitted (this occurs in ObjC metadata).
758  if (!GV) return false;
759
760  // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
761  if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
762    // FIXME: ObjC metadata is currently emitted as internal symbols that have
763    // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
764    // this horrible hack can go away.
765    MCSymbol *Sym = Mang->getSymbol(GV);
766    if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
767      return false;
768  }
769
770  return true;
771}
772
773const MCExpr *TargetLoweringObjectFileMachO::
774getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
775                               MachineModuleInfo *MMI, unsigned Encoding,
776                               MCStreamer &Streamer) const {
777  // The mach-o version of this method defaults to returning a stub reference.
778
779  if (Encoding & DW_EH_PE_indirect) {
780    MachineModuleInfoMachO &MachOMMI =
781      MMI->getObjFileInfo<MachineModuleInfoMachO>();
782
783    SmallString<128> Name;
784    Mang->getNameWithPrefix(Name, GV, true);
785    Name += "$non_lazy_ptr";
786
787    // Add information about the stub reference to MachOMMI so that the stub
788    // gets emitted by the asmprinter.
789    MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
790    MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
791    if (StubSym.getPointer() == 0) {
792      MCSymbol *Sym = Mang->getSymbol(GV);
793      StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
794    }
795
796    return TargetLoweringObjectFile::
797      getExprForDwarfReference(SSym, Mang, MMI,
798                               Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
799  }
800
801  return TargetLoweringObjectFile::
802    getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
803}
804
805unsigned TargetLoweringObjectFileMachO::getPersonalityEncoding() const {
806  return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
807}
808
809unsigned TargetLoweringObjectFileMachO::getLSDAEncoding() const {
810  return DW_EH_PE_pcrel;
811}
812
813unsigned TargetLoweringObjectFileMachO::getFDEEncoding() const {
814  return DW_EH_PE_pcrel;
815}
816
817unsigned TargetLoweringObjectFileMachO::getTTypeEncoding() const {
818  return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
819}
820
821//===----------------------------------------------------------------------===//
822//                                  COFF
823//===----------------------------------------------------------------------===//
824
825void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
826                                              const TargetMachine &TM) {
827  TargetLoweringObjectFile::Initialize(Ctx, TM);
828  TextSection =
829    getContext().getCOFFSection(".text",
830                                COFF::IMAGE_SCN_CNT_CODE |
831                                COFF::IMAGE_SCN_MEM_EXECUTE |
832                                COFF::IMAGE_SCN_MEM_READ,
833                                SectionKind::getText());
834  DataSection =
835    getContext().getCOFFSection(".data",
836                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
837                                COFF::IMAGE_SCN_MEM_READ |
838                                COFF::IMAGE_SCN_MEM_WRITE,
839                                SectionKind::getDataRel());
840  ReadOnlySection =
841    getContext().getCOFFSection(".rdata",
842                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
843                                COFF::IMAGE_SCN_MEM_READ,
844                                SectionKind::getReadOnly());
845  StaticCtorSection =
846    getContext().getCOFFSection(".ctors",
847                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
848                                COFF::IMAGE_SCN_MEM_READ |
849                                COFF::IMAGE_SCN_MEM_WRITE,
850                                SectionKind::getDataRel());
851  StaticDtorSection =
852    getContext().getCOFFSection(".dtors",
853                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
854                                COFF::IMAGE_SCN_MEM_READ |
855                                COFF::IMAGE_SCN_MEM_WRITE,
856                                SectionKind::getDataRel());
857
858  // FIXME: We're emitting LSDA info into a readonly section on COFF, even
859  // though it contains relocatable pointers.  In PIC mode, this is probably a
860  // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
861  // adjusted or this should be a data section.
862  LSDASection =
863    getContext().getCOFFSection(".gcc_except_table",
864                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
865                                COFF::IMAGE_SCN_MEM_READ,
866                                SectionKind::getReadOnly());
867  EHFrameSection =
868    getContext().getCOFFSection(".eh_frame",
869                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
870                                COFF::IMAGE_SCN_MEM_READ |
871                                COFF::IMAGE_SCN_MEM_WRITE,
872                                SectionKind::getDataRel());
873
874  // Debug info.
875  DwarfAbbrevSection =
876    getContext().getCOFFSection(".debug_abbrev",
877                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
878                                COFF::IMAGE_SCN_MEM_READ,
879                                SectionKind::getMetadata());
880  DwarfInfoSection =
881    getContext().getCOFFSection(".debug_info",
882                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
883                                COFF::IMAGE_SCN_MEM_READ,
884                                SectionKind::getMetadata());
885  DwarfLineSection =
886    getContext().getCOFFSection(".debug_line",
887                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
888                                COFF::IMAGE_SCN_MEM_READ,
889                                SectionKind::getMetadata());
890  DwarfFrameSection =
891    getContext().getCOFFSection(".debug_frame",
892                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
893                                COFF::IMAGE_SCN_MEM_READ,
894                                SectionKind::getMetadata());
895  DwarfPubNamesSection =
896    getContext().getCOFFSection(".debug_pubnames",
897                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
898                                COFF::IMAGE_SCN_MEM_READ,
899                                SectionKind::getMetadata());
900  DwarfPubTypesSection =
901    getContext().getCOFFSection(".debug_pubtypes",
902                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
903                                COFF::IMAGE_SCN_MEM_READ,
904                                SectionKind::getMetadata());
905  DwarfStrSection =
906    getContext().getCOFFSection(".debug_str",
907                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
908                                COFF::IMAGE_SCN_MEM_READ,
909                                SectionKind::getMetadata());
910  DwarfLocSection =
911    getContext().getCOFFSection(".debug_loc",
912                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
913                                COFF::IMAGE_SCN_MEM_READ,
914                                SectionKind::getMetadata());
915  DwarfARangesSection =
916    getContext().getCOFFSection(".debug_aranges",
917                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
918                                COFF::IMAGE_SCN_MEM_READ,
919                                SectionKind::getMetadata());
920  DwarfRangesSection =
921    getContext().getCOFFSection(".debug_ranges",
922                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
923                                COFF::IMAGE_SCN_MEM_READ,
924                                SectionKind::getMetadata());
925  DwarfMacroInfoSection =
926    getContext().getCOFFSection(".debug_macinfo",
927                                COFF::IMAGE_SCN_MEM_DISCARDABLE |
928                                COFF::IMAGE_SCN_MEM_READ,
929                                SectionKind::getMetadata());
930
931  DrectveSection =
932    getContext().getCOFFSection(".drectve",
933                                COFF::IMAGE_SCN_LNK_INFO,
934                                SectionKind::getMetadata());
935}
936
937static unsigned
938getCOFFSectionFlags(SectionKind K) {
939  unsigned Flags = 0;
940
941  if (K.isMetadata())
942    Flags |=
943      COFF::IMAGE_SCN_MEM_DISCARDABLE;
944  else if (K.isText())
945    Flags |=
946      COFF::IMAGE_SCN_MEM_EXECUTE |
947      COFF::IMAGE_SCN_CNT_CODE;
948  else if (K.isBSS ())
949    Flags |=
950      COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
951      COFF::IMAGE_SCN_MEM_READ |
952      COFF::IMAGE_SCN_MEM_WRITE;
953  else if (K.isReadOnly())
954    Flags |=
955      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
956      COFF::IMAGE_SCN_MEM_READ;
957  else if (K.isWriteable())
958    Flags |=
959      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
960      COFF::IMAGE_SCN_MEM_READ |
961      COFF::IMAGE_SCN_MEM_WRITE;
962
963  return Flags;
964}
965
966const MCSection *TargetLoweringObjectFileCOFF::
967getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
968                         Mangler *Mang, const TargetMachine &TM) const {
969  return getContext().getCOFFSection(GV->getSection(),
970                                     getCOFFSectionFlags(Kind),
971                                     Kind);
972}
973
974static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
975  if (Kind.isText())
976    return ".text$linkonce";
977  if (Kind.isBSS ())
978    return ".bss$linkonce";
979  if (Kind.isWriteable())
980    return ".data$linkonce";
981  return ".rdata$linkonce";
982}
983
984
985const MCSection *TargetLoweringObjectFileCOFF::
986SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
987                       Mangler *Mang, const TargetMachine &TM) const {
988  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
989
990  // If this global is linkonce/weak and the target handles this by emitting it
991  // into a 'uniqued' section name, create and return the section now.
992  if (GV->isWeakForLinker()) {
993    const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
994    SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
995    MCSymbol *Sym = Mang->getSymbol(GV);
996    Name.append(Sym->getName().begin(), Sym->getName().end());
997
998    unsigned Characteristics = getCOFFSectionFlags(Kind);
999
1000    Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1001
1002    return getContext().getCOFFSection(Name.str(), Characteristics,
1003                          COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH, Kind);
1004  }
1005
1006  if (Kind.isText())
1007    return getTextSection();
1008
1009  return getDataSection();
1010}
1011
1012