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