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