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