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