e4d9ee02e7ca15d4c387fa6fc567a9884e4bac7b
[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/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"
38 using namespace llvm;
39 using namespace dwarf;
40
41 //===----------------------------------------------------------------------===//
42 //                                  ELF
43 //===----------------------------------------------------------------------===//
44
45 void 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
173 const MCSection *TargetLoweringObjectFileELF::getEHFrameSection() const {
174   return getContext().getELFSection(".eh_frame", ELF::SHT_PROGBITS,
175                                     ELF::SHF_ALLOC,
176                                     SectionKind::getDataRel());
177 }
178
179 static SectionKind
180 getELFKindForNamedSection(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
210 static 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
228 static unsigned
229 getELFSectionFlags(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
256 const MCSection *TargetLoweringObjectFileELF::
257 getExplicitSectionGlobal(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.
271 static 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
288 const MCSection *TargetLoweringObjectFileELF::
289 SelectSectionForGlobal(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.
382 const MCSection *TargetLoweringObjectFileELF::
383 getSectionForConstant(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
398 const MCExpr *TargetLoweringObjectFileELF::
399 getExprForDwarfGlobalReference(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
432 void 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     switch (T.getDarwinMajorNumber()) {
445     case 7:  // 10.3 Panther.
446     case 8:  // 10.4 Tiger.
447       CommDirectiveSupportsAlignment = false;
448       break;
449     case 9:   // 10.5 Leopard.
450     case 10:  // 10.6 SnowLeopard.
451       break;
452     }
453   }
454
455   TargetLoweringObjectFile::Initialize(Ctx, TM);
456
457   TextSection // .text
458     = getContext().getMachOSection("__TEXT", "__text",
459                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
460                                    SectionKind::getText());
461   DataSection // .data
462     = getContext().getMachOSection("__DATA", "__data", 0,
463                                    SectionKind::getDataRel());
464
465   TLSDataSection // .tdata
466     = getContext().getMachOSection("__DATA", "__thread_data",
467                                    MCSectionMachO::S_THREAD_LOCAL_REGULAR,
468                                    SectionKind::getDataRel());
469   TLSBSSSection // .tbss
470     = getContext().getMachOSection("__DATA", "__thread_bss",
471                                    MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
472                                    SectionKind::getThreadBSS());
473
474   // TODO: Verify datarel below.
475   TLSTLVSection // .tlv
476     = getContext().getMachOSection("__DATA", "__thread_vars",
477                                    MCSectionMachO::S_THREAD_LOCAL_VARIABLES,
478                                    SectionKind::getDataRel());
479
480   TLSThreadInitSection
481     = getContext().getMachOSection("__DATA", "__thread_init",
482                           MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS,
483                           SectionKind::getDataRel());
484
485   CStringSection // .cstring
486     = getContext().getMachOSection("__TEXT", "__cstring",
487                                    MCSectionMachO::S_CSTRING_LITERALS,
488                                    SectionKind::getMergeable1ByteCString());
489   UStringSection
490     = getContext().getMachOSection("__TEXT","__ustring", 0,
491                                    SectionKind::getMergeable2ByteCString());
492   FourByteConstantSection // .literal4
493     = getContext().getMachOSection("__TEXT", "__literal4",
494                                    MCSectionMachO::S_4BYTE_LITERALS,
495                                    SectionKind::getMergeableConst4());
496   EightByteConstantSection // .literal8
497     = getContext().getMachOSection("__TEXT", "__literal8",
498                                    MCSectionMachO::S_8BYTE_LITERALS,
499                                    SectionKind::getMergeableConst8());
500
501   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
502   // to using it in -static mode.
503   SixteenByteConstantSection = 0;
504   if (TM.getRelocationModel() != Reloc::Static &&
505       TM.getTargetData()->getPointerSize() == 32)
506     SixteenByteConstantSection =   // .literal16
507       getContext().getMachOSection("__TEXT", "__literal16",
508                                    MCSectionMachO::S_16BYTE_LITERALS,
509                                    SectionKind::getMergeableConst16());
510
511   ReadOnlySection  // .const
512     = getContext().getMachOSection("__TEXT", "__const", 0,
513                                    SectionKind::getReadOnly());
514
515   TextCoalSection
516     = getContext().getMachOSection("__TEXT", "__textcoal_nt",
517                                    MCSectionMachO::S_COALESCED |
518                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
519                                    SectionKind::getText());
520   ConstTextCoalSection
521     = getContext().getMachOSection("__TEXT", "__const_coal",
522                                    MCSectionMachO::S_COALESCED,
523                                    SectionKind::getReadOnly());
524   ConstDataSection  // .const_data
525     = getContext().getMachOSection("__DATA", "__const", 0,
526                                    SectionKind::getReadOnlyWithRel());
527   DataCoalSection
528     = getContext().getMachOSection("__DATA","__datacoal_nt",
529                                    MCSectionMachO::S_COALESCED,
530                                    SectionKind::getDataRel());
531   DataCommonSection
532     = getContext().getMachOSection("__DATA","__common",
533                                    MCSectionMachO::S_ZEROFILL,
534                                    SectionKind::getBSS());
535   DataBSSSection
536     = getContext().getMachOSection("__DATA","__bss", MCSectionMachO::S_ZEROFILL,
537                                    SectionKind::getBSS());
538
539
540   LazySymbolPointerSection
541     = getContext().getMachOSection("__DATA", "__la_symbol_ptr",
542                                    MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
543                                    SectionKind::getMetadata());
544   NonLazySymbolPointerSection
545     = getContext().getMachOSection("__DATA", "__nl_symbol_ptr",
546                                    MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
547                                    SectionKind::getMetadata());
548
549   if (TM.getRelocationModel() == Reloc::Static) {
550     StaticCtorSection
551       = getContext().getMachOSection("__TEXT", "__constructor", 0,
552                                      SectionKind::getDataRel());
553     StaticDtorSection
554       = getContext().getMachOSection("__TEXT", "__destructor", 0,
555                                      SectionKind::getDataRel());
556   } else {
557     StaticCtorSection
558       = getContext().getMachOSection("__DATA", "__mod_init_func",
559                                      MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
560                                      SectionKind::getDataRel());
561     StaticDtorSection
562       = getContext().getMachOSection("__DATA", "__mod_term_func",
563                                      MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
564                                      SectionKind::getDataRel());
565   }
566
567   // Exception Handling.
568   LSDASection = getContext().getMachOSection("__TEXT", "__gcc_except_tab", 0,
569                                              SectionKind::getReadOnlyWithRel());
570   // Debug Information.
571   DwarfAbbrevSection =
572     getContext().getMachOSection("__DWARF", "__debug_abbrev",
573                                  MCSectionMachO::S_ATTR_DEBUG,
574                                  SectionKind::getMetadata());
575   DwarfInfoSection =
576     getContext().getMachOSection("__DWARF", "__debug_info",
577                                  MCSectionMachO::S_ATTR_DEBUG,
578                                  SectionKind::getMetadata());
579   DwarfLineSection =
580     getContext().getMachOSection("__DWARF", "__debug_line",
581                                  MCSectionMachO::S_ATTR_DEBUG,
582                                  SectionKind::getMetadata());
583   DwarfFrameSection =
584     getContext().getMachOSection("__DWARF", "__debug_frame",
585                                  MCSectionMachO::S_ATTR_DEBUG,
586                                  SectionKind::getMetadata());
587   DwarfPubNamesSection =
588     getContext().getMachOSection("__DWARF", "__debug_pubnames",
589                                  MCSectionMachO::S_ATTR_DEBUG,
590                                  SectionKind::getMetadata());
591   DwarfPubTypesSection =
592     getContext().getMachOSection("__DWARF", "__debug_pubtypes",
593                                  MCSectionMachO::S_ATTR_DEBUG,
594                                  SectionKind::getMetadata());
595   DwarfStrSection =
596     getContext().getMachOSection("__DWARF", "__debug_str",
597                                  MCSectionMachO::S_ATTR_DEBUG,
598                                  SectionKind::getMetadata());
599   DwarfLocSection =
600     getContext().getMachOSection("__DWARF", "__debug_loc",
601                                  MCSectionMachO::S_ATTR_DEBUG,
602                                  SectionKind::getMetadata());
603   DwarfARangesSection =
604     getContext().getMachOSection("__DWARF", "__debug_aranges",
605                                  MCSectionMachO::S_ATTR_DEBUG,
606                                  SectionKind::getMetadata());
607   DwarfRangesSection =
608     getContext().getMachOSection("__DWARF", "__debug_ranges",
609                                  MCSectionMachO::S_ATTR_DEBUG,
610                                  SectionKind::getMetadata());
611   DwarfMacroInfoSection =
612     getContext().getMachOSection("__DWARF", "__debug_macinfo",
613                                  MCSectionMachO::S_ATTR_DEBUG,
614                                  SectionKind::getMetadata());
615   DwarfDebugInlineSection =
616     getContext().getMachOSection("__DWARF", "__debug_inlined",
617                                  MCSectionMachO::S_ATTR_DEBUG,
618                                  SectionKind::getMetadata());
619
620   TLSExtraDataSection = TLSTLVSection;
621 }
622
623 const MCSection *TargetLoweringObjectFileMachO::getEHFrameSection() const {
624   return getContext().getMachOSection("__TEXT", "__eh_frame",
625                                       MCSectionMachO::S_COALESCED |
626                                       MCSectionMachO::S_ATTR_NO_TOC |
627                                       MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
628                                       MCSectionMachO::S_ATTR_LIVE_SUPPORT,
629                                       SectionKind::getReadOnly());
630 }
631
632 const MCSection *TargetLoweringObjectFileMachO::
633 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
634                          Mangler *Mang, const TargetMachine &TM) const {
635   // Parse the section specifier and create it if valid.
636   StringRef Segment, Section;
637   unsigned TAA = (unsigned)MCSectionMachO::SECTION_ATTRIBUTES, StubSize = 0;
638   std::string ErrorCode =
639     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
640                                           TAA, StubSize);
641   if (!ErrorCode.empty()) {
642     // If invalid, report the error with report_fatal_error.
643     report_fatal_error("Global variable '" + GV->getNameStr() +
644                       "' has an invalid section specifier '" + GV->getSection()+
645                       "': " + ErrorCode + ".");
646     // Fall back to dropping it into the data section.
647     return DataSection;
648   }
649
650   bool TAAWasSet = (TAA != MCSectionMachO::SECTION_ATTRIBUTES);
651   if (!TAAWasSet)
652     TAA = 0;      // Sensible default if this is a new section.
653     
654   // Get the section.
655   const MCSectionMachO *S =
656     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
657
658   // If TAA wasn't set by ParseSectionSpecifier() above,
659   // use the value returned by getMachOSection() as a default.
660   if (!TAAWasSet)
661     TAA = S->getTypeAndAttributes();
662
663   // Okay, now that we got the section, verify that the TAA & StubSize agree.
664   // If the user declared multiple globals with different section flags, we need
665   // to reject it here.
666   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
667     // If invalid, report the error with report_fatal_error.
668     report_fatal_error("Global variable '" + GV->getNameStr() +
669                       "' section type or attributes does not match previous"
670                       " section specifier");
671   }
672
673   return S;
674 }
675
676 const MCSection *TargetLoweringObjectFileMachO::
677 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
678                        Mangler *Mang, const TargetMachine &TM) const {
679
680   // Handle thread local data.
681   if (Kind.isThreadBSS()) return TLSBSSSection;
682   if (Kind.isThreadData()) return TLSDataSection;
683
684   if (Kind.isText())
685     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
686
687   // If this is weak/linkonce, put this in a coalescable section, either in text
688   // or data depending on if it is writable.
689   if (GV->isWeakForLinker()) {
690     if (Kind.isReadOnly())
691       return ConstTextCoalSection;
692     return DataCoalSection;
693   }
694
695   // FIXME: Alignment check should be handled by section classifier.
696   if (Kind.isMergeable1ByteCString() &&
697       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
698     return CStringSection;
699
700   // Do not put 16-bit arrays in the UString section if they have an
701   // externally visible label, this runs into issues with certain linker
702   // versions.
703   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
704       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
705     return UStringSection;
706
707   if (Kind.isMergeableConst()) {
708     if (Kind.isMergeableConst4())
709       return FourByteConstantSection;
710     if (Kind.isMergeableConst8())
711       return EightByteConstantSection;
712     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
713       return SixteenByteConstantSection;
714   }
715
716   // Otherwise, if it is readonly, but not something we can specially optimize,
717   // just drop it in .const.
718   if (Kind.isReadOnly())
719     return ReadOnlySection;
720
721   // If this is marked const, put it into a const section.  But if the dynamic
722   // linker needs to write to it, put it in the data segment.
723   if (Kind.isReadOnlyWithRel())
724     return ConstDataSection;
725
726   // Put zero initialized globals with strong external linkage in the
727   // DATA, __common section with the .zerofill directive.
728   if (Kind.isBSSExtern())
729     return DataCommonSection;
730
731   // Put zero initialized globals with local linkage in __DATA,__bss directive
732   // with the .zerofill directive (aka .lcomm).
733   if (Kind.isBSSLocal())
734     return DataBSSSection;
735
736   // Otherwise, just drop the variable in the normal data section.
737   return DataSection;
738 }
739
740 const MCSection *
741 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
742   // If this constant requires a relocation, we have to put it in the data
743   // segment, not in the text segment.
744   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
745     return ConstDataSection;
746
747   if (Kind.isMergeableConst4())
748     return FourByteConstantSection;
749   if (Kind.isMergeableConst8())
750     return EightByteConstantSection;
751   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
752     return SixteenByteConstantSection;
753   return ReadOnlySection;  // .const
754 }
755
756 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
757 /// not to emit the UsedDirective for some symbols in llvm.used.
758 // FIXME: REMOVE this (rdar://7071300)
759 bool TargetLoweringObjectFileMachO::
760 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
761   /// On Darwin, internally linked data beginning with "L" or "l" does not have
762   /// the directive emitted (this occurs in ObjC metadata).
763   if (!GV) return false;
764
765   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
766   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
767     // FIXME: ObjC metadata is currently emitted as internal symbols that have
768     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
769     // this horrible hack can go away.
770     MCSymbol *Sym = Mang->getSymbol(GV);
771     if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
772       return false;
773   }
774
775   return true;
776 }
777
778 const MCExpr *TargetLoweringObjectFileMachO::
779 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
780                                MachineModuleInfo *MMI, unsigned Encoding,
781                                MCStreamer &Streamer) const {
782   // The mach-o version of this method defaults to returning a stub reference.
783
784   if (Encoding & DW_EH_PE_indirect) {
785     MachineModuleInfoMachO &MachOMMI =
786       MMI->getObjFileInfo<MachineModuleInfoMachO>();
787
788     SmallString<128> Name;
789     Mang->getNameWithPrefix(Name, GV, true);
790     Name += "$non_lazy_ptr";
791
792     // Add information about the stub reference to MachOMMI so that the stub
793     // gets emitted by the asmprinter.
794     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
795     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
796     if (StubSym.getPointer() == 0) {
797       MCSymbol *Sym = Mang->getSymbol(GV);
798       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
799     }
800
801     return TargetLoweringObjectFile::
802       getExprForDwarfReference(SSym, Mang, MMI,
803                                Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
804   }
805
806   return TargetLoweringObjectFile::
807     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
808 }
809
810 unsigned TargetLoweringObjectFileMachO::getPersonalityEncoding() const {
811   return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
812 }
813
814 unsigned TargetLoweringObjectFileMachO::getLSDAEncoding() const {
815   return DW_EH_PE_pcrel;
816 }
817
818 unsigned TargetLoweringObjectFileMachO::getFDEEncoding() const {
819   return DW_EH_PE_pcrel;
820 }
821
822 unsigned TargetLoweringObjectFileMachO::getTTypeEncoding() const {
823   return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
824 }
825
826 //===----------------------------------------------------------------------===//
827 //                                  COFF
828 //===----------------------------------------------------------------------===//
829
830 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
831                                               const TargetMachine &TM) {
832   TargetLoweringObjectFile::Initialize(Ctx, TM);
833   TextSection =
834     getContext().getCOFFSection(".text",
835                                 COFF::IMAGE_SCN_CNT_CODE |
836                                 COFF::IMAGE_SCN_MEM_EXECUTE |
837                                 COFF::IMAGE_SCN_MEM_READ,
838                                 SectionKind::getText());
839   DataSection =
840     getContext().getCOFFSection(".data",
841                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
842                                 COFF::IMAGE_SCN_MEM_READ |
843                                 COFF::IMAGE_SCN_MEM_WRITE,
844                                 SectionKind::getDataRel());
845   ReadOnlySection =
846     getContext().getCOFFSection(".rdata",
847                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
848                                 COFF::IMAGE_SCN_MEM_READ,
849                                 SectionKind::getReadOnly());
850   StaticCtorSection =
851     getContext().getCOFFSection(".ctors",
852                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
853                                 COFF::IMAGE_SCN_MEM_READ |
854                                 COFF::IMAGE_SCN_MEM_WRITE,
855                                 SectionKind::getDataRel());
856   StaticDtorSection =
857     getContext().getCOFFSection(".dtors",
858                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
859                                 COFF::IMAGE_SCN_MEM_READ |
860                                 COFF::IMAGE_SCN_MEM_WRITE,
861                                 SectionKind::getDataRel());
862
863   // FIXME: We're emitting LSDA info into a readonly section on COFF, even
864   // though it contains relocatable pointers.  In PIC mode, this is probably a
865   // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
866   // adjusted or this should be a data section.
867   LSDASection =
868     getContext().getCOFFSection(".gcc_except_table",
869                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
870                                 COFF::IMAGE_SCN_MEM_READ,
871                                 SectionKind::getReadOnly());
872   // Debug info.
873   DwarfAbbrevSection =
874     getContext().getCOFFSection(".debug_abbrev",
875                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
876                                 COFF::IMAGE_SCN_MEM_READ,
877                                 SectionKind::getMetadata());
878   DwarfInfoSection =
879     getContext().getCOFFSection(".debug_info",
880                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
881                                 COFF::IMAGE_SCN_MEM_READ,
882                                 SectionKind::getMetadata());
883   DwarfLineSection =
884     getContext().getCOFFSection(".debug_line",
885                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
886                                 COFF::IMAGE_SCN_MEM_READ,
887                                 SectionKind::getMetadata());
888   DwarfFrameSection =
889     getContext().getCOFFSection(".debug_frame",
890                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
891                                 COFF::IMAGE_SCN_MEM_READ,
892                                 SectionKind::getMetadata());
893   DwarfPubNamesSection =
894     getContext().getCOFFSection(".debug_pubnames",
895                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
896                                 COFF::IMAGE_SCN_MEM_READ,
897                                 SectionKind::getMetadata());
898   DwarfPubTypesSection =
899     getContext().getCOFFSection(".debug_pubtypes",
900                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
901                                 COFF::IMAGE_SCN_MEM_READ,
902                                 SectionKind::getMetadata());
903   DwarfStrSection =
904     getContext().getCOFFSection(".debug_str",
905                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
906                                 COFF::IMAGE_SCN_MEM_READ,
907                                 SectionKind::getMetadata());
908   DwarfLocSection =
909     getContext().getCOFFSection(".debug_loc",
910                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
911                                 COFF::IMAGE_SCN_MEM_READ,
912                                 SectionKind::getMetadata());
913   DwarfARangesSection =
914     getContext().getCOFFSection(".debug_aranges",
915                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
916                                 COFF::IMAGE_SCN_MEM_READ,
917                                 SectionKind::getMetadata());
918   DwarfRangesSection =
919     getContext().getCOFFSection(".debug_ranges",
920                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
921                                 COFF::IMAGE_SCN_MEM_READ,
922                                 SectionKind::getMetadata());
923   DwarfMacroInfoSection =
924     getContext().getCOFFSection(".debug_macinfo",
925                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
926                                 COFF::IMAGE_SCN_MEM_READ,
927                                 SectionKind::getMetadata());
928
929   DrectveSection =
930     getContext().getCOFFSection(".drectve",
931                                 COFF::IMAGE_SCN_LNK_INFO,
932                                 SectionKind::getMetadata());
933 }
934
935 const MCSection *TargetLoweringObjectFileCOFF::getEHFrameSection() const {
936   return getContext().getCOFFSection(".eh_frame",
937                                      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
938                                      COFF::IMAGE_SCN_MEM_READ |
939                                      COFF::IMAGE_SCN_MEM_WRITE,
940                                      SectionKind::getDataRel());
941 }
942
943
944 static unsigned
945 getCOFFSectionFlags(SectionKind K) {
946   unsigned Flags = 0;
947
948   if (K.isMetadata())
949     Flags |=
950       COFF::IMAGE_SCN_MEM_DISCARDABLE;
951   else if (K.isText())
952     Flags |=
953       COFF::IMAGE_SCN_MEM_EXECUTE |
954       COFF::IMAGE_SCN_MEM_READ |
955       COFF::IMAGE_SCN_CNT_CODE;
956   else if (K.isBSS ())
957     Flags |=
958       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
959       COFF::IMAGE_SCN_MEM_READ |
960       COFF::IMAGE_SCN_MEM_WRITE;
961   else if (K.isReadOnly())
962     Flags |=
963       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
964       COFF::IMAGE_SCN_MEM_READ;
965   else if (K.isWriteable())
966     Flags |=
967       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
968       COFF::IMAGE_SCN_MEM_READ |
969       COFF::IMAGE_SCN_MEM_WRITE;
970
971   return Flags;
972 }
973
974 const MCSection *TargetLoweringObjectFileCOFF::
975 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
976                          Mangler *Mang, const TargetMachine &TM) const {
977   return getContext().getCOFFSection(GV->getSection(),
978                                      getCOFFSectionFlags(Kind),
979                                      Kind);
980 }
981
982 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
983   if (Kind.isText())
984     return ".text$";
985   if (Kind.isBSS ())
986     return ".bss$";
987   if (Kind.isWriteable())
988     return ".data$";
989   return ".rdata$";
990 }
991
992
993 const MCSection *TargetLoweringObjectFileCOFF::
994 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
995                        Mangler *Mang, const TargetMachine &TM) const {
996   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
997
998   // If this global is linkonce/weak and the target handles this by emitting it
999   // into a 'uniqued' section name, create and return the section now.
1000   if (GV->isWeakForLinker()) {
1001     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1002     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1003     MCSymbol *Sym = Mang->getSymbol(GV);
1004     Name.append(Sym->getName().begin() + 1, Sym->getName().end());
1005
1006     unsigned Characteristics = getCOFFSectionFlags(Kind);
1007
1008     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1009
1010     return getContext().getCOFFSection(Name.str(), Characteristics,
1011                           COFF::IMAGE_COMDAT_SELECT_ANY, Kind);
1012   }
1013
1014   if (Kind.isText())
1015     return getTextSection();
1016
1017   return getDataSection();
1018 }
1019