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