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