Preliminary patch to improve dwarf EH generation - Hooks to return Personality /...
[oota-llvm.git] / lib / Target / TargetLoweringObjectFile.cpp
1 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Target/Mangler.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                              Generic Code
39 //===----------------------------------------------------------------------===//
40
41 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
42   TextSection = 0;
43   DataSection = 0;
44   BSSSection = 0;
45   ReadOnlySection = 0;
46   StaticCtorSection = 0;
47   StaticDtorSection = 0;
48   LSDASection = 0;
49   EHFrameSection = 0;
50
51   DwarfAbbrevSection = 0;
52   DwarfInfoSection = 0;
53   DwarfLineSection = 0;
54   DwarfFrameSection = 0;
55   DwarfPubNamesSection = 0;
56   DwarfPubTypesSection = 0;
57   DwarfDebugInlineSection = 0;
58   DwarfStrSection = 0;
59   DwarfLocSection = 0;
60   DwarfARangesSection = 0;
61   DwarfRangesSection = 0;
62   DwarfMacroInfoSection = 0;
63 }
64
65 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
66 }
67
68 static bool isSuitableForBSS(const GlobalVariable *GV) {
69   Constant *C = GV->getInitializer();
70
71   // Must have zero initializer.
72   if (!C->isNullValue())
73     return false;
74
75   // Leave constant zeros in readonly constant sections, so they can be shared.
76   if (GV->isConstant())
77     return false;
78
79   // If the global has an explicit section specified, don't put it in BSS.
80   if (!GV->getSection().empty())
81     return false;
82
83   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
84   if (NoZerosInBSS)
85     return false;
86
87   // Otherwise, put it in BSS!
88   return true;
89 }
90
91 /// IsNullTerminatedString - Return true if the specified constant (which is
92 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
93 /// nul value and contains no other nuls in it.
94 static bool IsNullTerminatedString(const Constant *C) {
95   const ArrayType *ATy = cast<ArrayType>(C->getType());
96
97   // First check: is we have constant array of i8 terminated with zero
98   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
99     if (ATy->getNumElements() == 0) return false;
100
101     ConstantInt *Null =
102       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
103     if (Null == 0 || Null->getZExtValue() != 0)
104       return false; // Not null terminated.
105
106     // Verify that the null doesn't occur anywhere else in the string.
107     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
108       // Reject constantexpr elements etc.
109       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
110           CVA->getOperand(i) == Null)
111         return false;
112     return true;
113   }
114
115   // Another possibility: [1 x i8] zeroinitializer
116   if (isa<ConstantAggregateZero>(C))
117     return ATy->getNumElements() == 1;
118
119   return false;
120 }
121
122 /// getKindForGlobal - This is a top-level target-independent classifier for
123 /// a global variable.  Given an global variable and information from TM, it
124 /// classifies the global in a variety of ways that make various target
125 /// implementations simpler.  The target implementation is free to ignore this
126 /// extra info of course.
127 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
128                                                        const TargetMachine &TM){
129   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
130          "Can only be used for global definitions");
131
132   Reloc::Model ReloModel = TM.getRelocationModel();
133
134   // Early exit - functions should be always in text sections.
135   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
136   if (GVar == 0)
137     return SectionKind::getText();
138
139   // Handle thread-local data first.
140   if (GVar->isThreadLocal()) {
141     if (isSuitableForBSS(GVar))
142       return SectionKind::getThreadBSS();
143     return SectionKind::getThreadData();
144   }
145
146   // Variables with common linkage always get classified as common.
147   if (GVar->hasCommonLinkage())
148     return SectionKind::getCommon();
149
150   // Variable can be easily put to BSS section.
151   if (isSuitableForBSS(GVar)) {
152     if (GVar->hasLocalLinkage())
153       return SectionKind::getBSSLocal();
154     else if (GVar->hasExternalLinkage())
155       return SectionKind::getBSSExtern();
156     return SectionKind::getBSS();
157   }
158
159   Constant *C = GVar->getInitializer();
160
161   // If the global is marked constant, we can put it into a mergable section,
162   // a mergable string section, or general .data if it contains relocations.
163   if (GVar->isConstant()) {
164     // If the initializer for the global contains something that requires a
165     // relocation, then we may have to drop this into a wriable data section
166     // even though it is marked const.
167     switch (C->getRelocationInfo()) {
168     default: assert(0 && "unknown relocation info kind");
169     case Constant::NoRelocation:
170       // If initializer is a null-terminated string, put it in a "cstring"
171       // section of the right width.
172       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
173         if (const IntegerType *ITy =
174               dyn_cast<IntegerType>(ATy->getElementType())) {
175           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
176                ITy->getBitWidth() == 32) &&
177               IsNullTerminatedString(C)) {
178             if (ITy->getBitWidth() == 8)
179               return SectionKind::getMergeable1ByteCString();
180             if (ITy->getBitWidth() == 16)
181               return SectionKind::getMergeable2ByteCString();
182
183             assert(ITy->getBitWidth() == 32 && "Unknown width");
184             return SectionKind::getMergeable4ByteCString();
185           }
186         }
187       }
188
189       // Otherwise, just drop it into a mergable constant section.  If we have
190       // a section for this size, use it, otherwise use the arbitrary sized
191       // mergable section.
192       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
193       case 4:  return SectionKind::getMergeableConst4();
194       case 8:  return SectionKind::getMergeableConst8();
195       case 16: return SectionKind::getMergeableConst16();
196       default: return SectionKind::getMergeableConst();
197       }
198
199     case Constant::LocalRelocation:
200       // In static relocation model, the linker will resolve all addresses, so
201       // the relocation entries will actually be constants by the time the app
202       // starts up.  However, we can't put this into a mergable section, because
203       // the linker doesn't take relocations into consideration when it tries to
204       // merge entries in the section.
205       if (ReloModel == Reloc::Static)
206         return SectionKind::getReadOnly();
207
208       // Otherwise, the dynamic linker needs to fix it up, put it in the
209       // writable data.rel.local section.
210       return SectionKind::getReadOnlyWithRelLocal();
211
212     case Constant::GlobalRelocations:
213       // In static relocation model, the linker will resolve all addresses, so
214       // the relocation entries will actually be constants by the time the app
215       // starts up.  However, we can't put this into a mergable section, because
216       // the linker doesn't take relocations into consideration when it tries to
217       // merge entries in the section.
218       if (ReloModel == Reloc::Static)
219         return SectionKind::getReadOnly();
220
221       // Otherwise, the dynamic linker needs to fix it up, put it in the
222       // writable data.rel section.
223       return SectionKind::getReadOnlyWithRel();
224     }
225   }
226
227   // Okay, this isn't a constant.  If the initializer for the global is going
228   // to require a runtime relocation by the dynamic linker, put it into a more
229   // specific section to improve startup time of the app.  This coalesces these
230   // globals together onto fewer pages, improving the locality of the dynamic
231   // linker.
232   if (ReloModel == Reloc::Static)
233     return SectionKind::getDataNoRel();
234
235   switch (C->getRelocationInfo()) {
236   default: assert(0 && "unknown relocation info kind");
237   case Constant::NoRelocation:
238     return SectionKind::getDataNoRel();
239   case Constant::LocalRelocation:
240     return SectionKind::getDataRelLocal();
241   case Constant::GlobalRelocations:
242     return SectionKind::getDataRel();
243   }
244 }
245
246 /// SectionForGlobal - This method computes the appropriate section to emit
247 /// the specified global variable or function definition.  This should not
248 /// be passed external (or available externally) globals.
249 const MCSection *TargetLoweringObjectFile::
250 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
251                  const TargetMachine &TM) const {
252   // Select section name.
253   if (GV->hasSection())
254     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
255
256
257   // Use default section depending on the 'type' of global
258   return SelectSectionForGlobal(GV, Kind, Mang, TM);
259 }
260
261
262 // Lame default implementation. Calculate the section name for global.
263 const MCSection *
264 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
265                                                  SectionKind Kind,
266                                                  Mangler *Mang,
267                                                  const TargetMachine &TM) const{
268   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
269
270   if (Kind.isText())
271     return getTextSection();
272
273   if (Kind.isBSS() && BSSSection != 0)
274     return BSSSection;
275
276   if (Kind.isReadOnly() && ReadOnlySection != 0)
277     return ReadOnlySection;
278
279   return getDataSection();
280 }
281
282 /// getSectionForConstant - Given a mergable constant with the
283 /// specified size and relocation information, return a section that it
284 /// should be placed in.
285 const MCSection *
286 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
287   if (Kind.isReadOnly() && ReadOnlySection != 0)
288     return ReadOnlySection;
289
290   return DataSection;
291 }
292
293 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
294 /// reference to the specified global variable from exception
295 /// handling information.
296 const MCExpr *TargetLoweringObjectFile::
297 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
298                              MachineModuleInfo *MMI, unsigned Encoding) const {
299   // FIXME: Use GetGlobalValueSymbol.
300   SmallString<128> Name;
301   Mang->getNameWithPrefix(Name, GV, false);
302   const MCSymbol *Sym = getContext().GetOrCreateSymbol(Name.str());
303
304   return getSymbolForDwarfReference(Sym, MMI, Encoding);
305 }
306
307 const MCExpr *TargetLoweringObjectFile::
308 getSymbolForDwarfReference(const MCSymbol *Sym, MachineModuleInfo *MMI,
309                            unsigned Encoding) const {
310   const MCExpr *Res = MCSymbolRefExpr::Create(Sym, getContext());
311
312   switch (Encoding & 0xF0) {
313   default:
314     llvm_report_error("Do not support this DWARF encoding yet!");
315     break;
316   case dwarf::DW_EH_PE_absptr:
317     // Do nothing special
318     break;
319   case dwarf::DW_EH_PE_pcrel:
320     // FIXME: PCSymbol
321     const MCExpr *PC = MCSymbolRefExpr::Create(".", getContext());
322     Res = MCBinaryExpr::CreateSub(Res, PC, getContext());
323     break;
324   }
325
326   return Res;
327 }
328
329 unsigned TargetLoweringObjectFile::getPersonalityEncoding() const {
330   return dwarf::DW_EH_PE_absptr;
331 }
332
333 unsigned TargetLoweringObjectFile::getLSDAEncoding() const {
334   return dwarf::DW_EH_PE_absptr;
335 }
336
337 unsigned TargetLoweringObjectFile::getFDEEncoding() const {
338   return dwarf::DW_EH_PE_absptr;
339 }
340
341 unsigned TargetLoweringObjectFile::getTTypeEncoding() const {
342   return dwarf::DW_EH_PE_absptr;
343 }
344
345 //===----------------------------------------------------------------------===//
346 //                                  ELF
347 //===----------------------------------------------------------------------===//
348 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
349
350 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
351   // If we have the section uniquing map, free it.
352   delete (ELFUniqueMapTy*)UniquingMap;
353 }
354
355 const MCSection *TargetLoweringObjectFileELF::
356 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
357               SectionKind Kind, bool IsExplicit) const {
358   if (UniquingMap == 0)
359     UniquingMap = new ELFUniqueMapTy();
360   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
361
362   // Do the lookup, if we have a hit, return it.
363   const MCSectionELF *&Entry = Map[Section];
364   if (Entry) return Entry;
365
366   return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
367                                       getContext());
368 }
369
370 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
371                                              const TargetMachine &TM) {
372   if (UniquingMap != 0)
373     ((ELFUniqueMapTy*)UniquingMap)->clear();
374   TargetLoweringObjectFile::Initialize(Ctx, TM);
375
376   BSSSection =
377     getELFSection(".bss", MCSectionELF::SHT_NOBITS,
378                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
379                   SectionKind::getBSS());
380
381   TextSection =
382     getELFSection(".text", MCSectionELF::SHT_PROGBITS,
383                   MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
384                   SectionKind::getText());
385
386   DataSection =
387     getELFSection(".data", MCSectionELF::SHT_PROGBITS,
388                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
389                   SectionKind::getDataRel());
390
391   ReadOnlySection =
392     getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
393                   MCSectionELF::SHF_ALLOC,
394                   SectionKind::getReadOnly());
395
396   TLSDataSection =
397     getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
398                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
399                   MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
400
401   TLSBSSSection =
402     getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
403                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
404                   MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
405
406   DataRelSection =
407     getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
408                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
409                   SectionKind::getDataRel());
410
411   DataRelLocalSection =
412     getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
413                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
414                   SectionKind::getDataRelLocal());
415
416   DataRelROSection =
417     getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
418                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
419                   SectionKind::getReadOnlyWithRel());
420
421   DataRelROLocalSection =
422     getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
423                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
424                   SectionKind::getReadOnlyWithRelLocal());
425
426   MergeableConst4Section =
427     getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
428                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
429                   SectionKind::getMergeableConst4());
430
431   MergeableConst8Section =
432     getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
433                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
434                   SectionKind::getMergeableConst8());
435
436   MergeableConst16Section =
437     getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
438                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
439                   SectionKind::getMergeableConst16());
440
441   StaticCtorSection =
442     getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
443                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
444                   SectionKind::getDataRel());
445
446   StaticDtorSection =
447     getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
448                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
449                   SectionKind::getDataRel());
450
451   // Exception Handling Sections.
452
453   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
454   // it contains relocatable pointers.  In PIC mode, this is probably a big
455   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
456   // adjusted or this should be a data section.
457   LSDASection =
458     getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
459                   MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
460   EHFrameSection =
461     getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
462                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
463                   SectionKind::getDataRel());
464
465   // Debug Info Sections.
466   DwarfAbbrevSection =
467     getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
468                   SectionKind::getMetadata());
469   DwarfInfoSection =
470     getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
471                   SectionKind::getMetadata());
472   DwarfLineSection =
473     getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
474                   SectionKind::getMetadata());
475   DwarfFrameSection =
476     getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
477                   SectionKind::getMetadata());
478   DwarfPubNamesSection =
479     getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
480                   SectionKind::getMetadata());
481   DwarfPubTypesSection =
482     getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
483                   SectionKind::getMetadata());
484   DwarfStrSection =
485     getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
486                   SectionKind::getMetadata());
487   DwarfLocSection =
488     getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
489                   SectionKind::getMetadata());
490   DwarfARangesSection =
491     getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
492                   SectionKind::getMetadata());
493   DwarfRangesSection =
494     getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
495                   SectionKind::getMetadata());
496   DwarfMacroInfoSection =
497     getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
498                   SectionKind::getMetadata());
499 }
500
501
502 static SectionKind
503 getELFKindForNamedSection(StringRef Name, SectionKind K) {
504   if (Name.empty() || Name[0] != '.') return K;
505
506   // Some lame default implementation based on some magic section names.
507   if (Name == ".bss" ||
508       Name.startswith(".bss.") ||
509       Name.startswith(".gnu.linkonce.b.") ||
510       Name.startswith(".llvm.linkonce.b.") ||
511       Name == ".sbss" ||
512       Name.startswith(".sbss.") ||
513       Name.startswith(".gnu.linkonce.sb.") ||
514       Name.startswith(".llvm.linkonce.sb."))
515     return SectionKind::getBSS();
516
517   if (Name == ".tdata" ||
518       Name.startswith(".tdata.") ||
519       Name.startswith(".gnu.linkonce.td.") ||
520       Name.startswith(".llvm.linkonce.td."))
521     return SectionKind::getThreadData();
522
523   if (Name == ".tbss" ||
524       Name.startswith(".tbss.") ||
525       Name.startswith(".gnu.linkonce.tb.") ||
526       Name.startswith(".llvm.linkonce.tb."))
527     return SectionKind::getThreadBSS();
528
529   return K;
530 }
531
532
533 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
534
535   if (Name == ".init_array")
536     return MCSectionELF::SHT_INIT_ARRAY;
537
538   if (Name == ".fini_array")
539     return MCSectionELF::SHT_FINI_ARRAY;
540
541   if (Name == ".preinit_array")
542     return MCSectionELF::SHT_PREINIT_ARRAY;
543
544   if (K.isBSS() || K.isThreadBSS())
545     return MCSectionELF::SHT_NOBITS;
546
547   return MCSectionELF::SHT_PROGBITS;
548 }
549
550
551 static unsigned
552 getELFSectionFlags(SectionKind K) {
553   unsigned Flags = 0;
554
555   if (!K.isMetadata())
556     Flags |= MCSectionELF::SHF_ALLOC;
557
558   if (K.isText())
559     Flags |= MCSectionELF::SHF_EXECINSTR;
560
561   if (K.isWriteable())
562     Flags |= MCSectionELF::SHF_WRITE;
563
564   if (K.isThreadLocal())
565     Flags |= MCSectionELF::SHF_TLS;
566
567   // K.isMergeableConst() is left out to honour PR4650
568   if (K.isMergeableCString() || K.isMergeableConst4() ||
569       K.isMergeableConst8() || K.isMergeableConst16())
570     Flags |= MCSectionELF::SHF_MERGE;
571
572   if (K.isMergeableCString())
573     Flags |= MCSectionELF::SHF_STRINGS;
574
575   return Flags;
576 }
577
578
579 const MCSection *TargetLoweringObjectFileELF::
580 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
581                          Mangler *Mang, const TargetMachine &TM) const {
582   StringRef SectionName = GV->getSection();
583
584   // Infer section flags from the section name if we can.
585   Kind = getELFKindForNamedSection(SectionName, Kind);
586
587   return getELFSection(SectionName,
588                        getELFSectionType(SectionName, Kind),
589                        getELFSectionFlags(Kind), Kind, true);
590 }
591
592 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
593   if (Kind.isText())                 return ".gnu.linkonce.t.";
594   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
595
596   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
597   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
598
599   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
600   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
601   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
602   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
603
604   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
605   return ".gnu.linkonce.d.rel.ro.";
606 }
607
608 const MCSection *TargetLoweringObjectFileELF::
609 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
610                        Mangler *Mang, const TargetMachine &TM) const {
611
612   // If this global is linkonce/weak and the target handles this by emitting it
613   // into a 'uniqued' section name, create and return the section now.
614   if (GV->isWeakForLinker() && !Kind.isCommon() && !Kind.isBSS()) {
615     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
616     SmallString<128> Name;
617     Name.append(Prefix, Prefix+strlen(Prefix));
618     Mang->getNameWithPrefix(Name, GV, false);
619     return getELFSection(Name.str(), getELFSectionType(Name.str(), Kind),
620                          getELFSectionFlags(Kind), Kind);
621   }
622
623   if (Kind.isText()) return TextSection;
624
625   if (Kind.isMergeable1ByteCString() ||
626       Kind.isMergeable2ByteCString() ||
627       Kind.isMergeable4ByteCString()) {
628
629     // We also need alignment here.
630     // FIXME: this is getting the alignment of the character, not the
631     // alignment of the global!
632     unsigned Align =
633       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
634
635     const char *SizeSpec = ".rodata.str1.";
636     if (Kind.isMergeable2ByteCString())
637       SizeSpec = ".rodata.str2.";
638     else if (Kind.isMergeable4ByteCString())
639       SizeSpec = ".rodata.str4.";
640     else
641       assert(Kind.isMergeable1ByteCString() && "unknown string width");
642
643
644     std::string Name = SizeSpec + utostr(Align);
645     return getELFSection(Name, MCSectionELF::SHT_PROGBITS,
646                          MCSectionELF::SHF_ALLOC |
647                          MCSectionELF::SHF_MERGE |
648                          MCSectionELF::SHF_STRINGS,
649                          Kind);
650   }
651
652   if (Kind.isMergeableConst()) {
653     if (Kind.isMergeableConst4() && MergeableConst4Section)
654       return MergeableConst4Section;
655     if (Kind.isMergeableConst8() && MergeableConst8Section)
656       return MergeableConst8Section;
657     if (Kind.isMergeableConst16() && MergeableConst16Section)
658       return MergeableConst16Section;
659     return ReadOnlySection;  // .const
660   }
661
662   if (Kind.isReadOnly())             return ReadOnlySection;
663
664   if (Kind.isThreadData())           return TLSDataSection;
665   if (Kind.isThreadBSS())            return TLSBSSSection;
666
667   // Note: we claim that common symbols are put in BSSSection, but they are
668   // really emitted with the magic .comm directive, which creates a symbol table
669   // entry but not a section.
670   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
671
672   if (Kind.isDataNoRel())            return DataSection;
673   if (Kind.isDataRelLocal())         return DataRelLocalSection;
674   if (Kind.isDataRel())              return DataRelSection;
675   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
676
677   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
678   return DataRelROSection;
679 }
680
681 /// getSectionForConstant - Given a mergeable constant with the
682 /// specified size and relocation information, return a section that it
683 /// should be placed in.
684 const MCSection *TargetLoweringObjectFileELF::
685 getSectionForConstant(SectionKind Kind) const {
686   if (Kind.isMergeableConst4() && MergeableConst4Section)
687     return MergeableConst4Section;
688   if (Kind.isMergeableConst8() && MergeableConst8Section)
689     return MergeableConst8Section;
690   if (Kind.isMergeableConst16() && MergeableConst16Section)
691     return MergeableConst16Section;
692   if (Kind.isReadOnly())
693     return ReadOnlySection;
694
695   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
696   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
697   return DataRelROSection;
698 }
699
700 const MCExpr *TargetLoweringObjectFileELF::
701 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
702                              MachineModuleInfo *MMI, unsigned Encoding) const {
703
704   if (Encoding & dwarf::DW_EH_PE_indirect) {
705     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
706
707     SmallString<128> Name;
708     Mang->getNameWithPrefix(Name, GV, true);
709
710     // Add information about the stub reference to ELFMMI so that the stub
711     // gets emitted by the asmprinter.
712     MCSymbol *Sym = getContext().GetOrCreateSymbol(Name.str());
713     MCSymbol *&StubSym = ELFMMI.getGVStubEntry(Sym);
714     if (StubSym == 0) {
715       Name.clear();
716       Mang->getNameWithPrefix(Name, GV, false);
717       StubSym = getContext().GetOrCreateSymbol(Name.str());
718     }
719
720     return TargetLoweringObjectFile::
721       getSymbolForDwarfReference(Sym, MMI,
722                                  Encoding & ~dwarf::DW_EH_PE_indirect);
723   }
724
725   return TargetLoweringObjectFile::
726     getSymbolForDwarfGlobalReference(GV, Mang, MMI, Encoding);
727 }
728
729 //===----------------------------------------------------------------------===//
730 //                                 MachO
731 //===----------------------------------------------------------------------===//
732
733 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
734
735 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
736   // If we have the MachO uniquing map, free it.
737   delete (MachOUniqueMapTy*)UniquingMap;
738 }
739
740
741 const MCSectionMachO *TargetLoweringObjectFileMachO::
742 getMachOSection(StringRef Segment, StringRef Section,
743                 unsigned TypeAndAttributes,
744                 unsigned Reserved2, SectionKind Kind) const {
745   // We unique sections by their segment/section pair.  The returned section
746   // may not have the same flags as the requested section, if so this should be
747   // diagnosed by the client as an error.
748
749   // Create the map if it doesn't already exist.
750   if (UniquingMap == 0)
751     UniquingMap = new MachOUniqueMapTy();
752   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
753
754   // Form the name to look up.
755   SmallString<64> Name;
756   Name += Segment;
757   Name.push_back(',');
758   Name += Section;
759
760   // Do the lookup, if we have a hit, return it.
761   const MCSectionMachO *&Entry = Map[Name.str()];
762   if (Entry) return Entry;
763
764   // Otherwise, return a new section.
765   return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
766                                         Reserved2, Kind, getContext());
767 }
768
769
770 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
771                                                const TargetMachine &TM) {
772   if (UniquingMap != 0)
773     ((MachOUniqueMapTy*)UniquingMap)->clear();
774   TargetLoweringObjectFile::Initialize(Ctx, TM);
775
776   TextSection // .text
777     = getMachOSection("__TEXT", "__text",
778                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
779                       SectionKind::getText());
780   DataSection // .data
781     = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
782
783   CStringSection // .cstring
784     = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
785                       SectionKind::getMergeable1ByteCString());
786   UStringSection
787     = getMachOSection("__TEXT","__ustring", 0,
788                       SectionKind::getMergeable2ByteCString());
789   FourByteConstantSection // .literal4
790     = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
791                       SectionKind::getMergeableConst4());
792   EightByteConstantSection // .literal8
793     = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
794                       SectionKind::getMergeableConst8());
795
796   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
797   // to using it in -static mode.
798   SixteenByteConstantSection = 0;
799   if (TM.getRelocationModel() != Reloc::Static &&
800       TM.getTargetData()->getPointerSize() == 32)
801     SixteenByteConstantSection =   // .literal16
802       getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
803                       SectionKind::getMergeableConst16());
804
805   ReadOnlySection  // .const
806     = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
807
808   TextCoalSection
809     = getMachOSection("__TEXT", "__textcoal_nt",
810                       MCSectionMachO::S_COALESCED |
811                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
812                       SectionKind::getText());
813   ConstTextCoalSection
814     = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
815                       SectionKind::getText());
816   ConstDataCoalSection
817     = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
818                       SectionKind::getText());
819   ConstDataSection  // .const_data
820     = getMachOSection("__DATA", "__const", 0,
821                       SectionKind::getReadOnlyWithRel());
822   DataCoalSection
823     = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
824                       SectionKind::getDataRel());
825   DataCommonSection
826     = getMachOSection("__DATA","__common", MCSectionMachO::S_ZEROFILL,
827                       SectionKind::getBSS());
828   DataBSSSection
829     = getMachOSection("__DATA","__bss", MCSectionMachO::S_ZEROFILL,
830                     SectionKind::getBSS());
831   
832
833   LazySymbolPointerSection
834     = getMachOSection("__DATA", "__la_symbol_ptr",
835                       MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
836                       SectionKind::getMetadata());
837   NonLazySymbolPointerSection
838     = getMachOSection("__DATA", "__nl_symbol_ptr",
839                       MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
840                       SectionKind::getMetadata());
841
842   if (TM.getRelocationModel() == Reloc::Static) {
843     StaticCtorSection
844       = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
845     StaticDtorSection
846       = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
847   } else {
848     StaticCtorSection
849       = getMachOSection("__DATA", "__mod_init_func",
850                         MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
851                         SectionKind::getDataRel());
852     StaticDtorSection
853       = getMachOSection("__DATA", "__mod_term_func",
854                         MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
855                         SectionKind::getDataRel());
856   }
857
858   // Exception Handling.
859   LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
860                                 SectionKind::getDataRel());
861   EHFrameSection =
862     getMachOSection("__TEXT", "__eh_frame",
863                     MCSectionMachO::S_COALESCED |
864                     MCSectionMachO::S_ATTR_NO_TOC |
865                     MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
866                     MCSectionMachO::S_ATTR_LIVE_SUPPORT,
867                     SectionKind::getReadOnly());
868
869   // Debug Information.
870   DwarfAbbrevSection =
871     getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
872                     SectionKind::getMetadata());
873   DwarfInfoSection =
874     getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
875                     SectionKind::getMetadata());
876   DwarfLineSection =
877     getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
878                     SectionKind::getMetadata());
879   DwarfFrameSection =
880     getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
881                     SectionKind::getMetadata());
882   DwarfPubNamesSection =
883     getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
884                     SectionKind::getMetadata());
885   DwarfPubTypesSection =
886     getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
887                     SectionKind::getMetadata());
888   DwarfStrSection =
889     getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
890                     SectionKind::getMetadata());
891   DwarfLocSection =
892     getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
893                     SectionKind::getMetadata());
894   DwarfARangesSection =
895     getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
896                     SectionKind::getMetadata());
897   DwarfRangesSection =
898     getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
899                     SectionKind::getMetadata());
900   DwarfMacroInfoSection =
901     getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
902                     SectionKind::getMetadata());
903   DwarfDebugInlineSection =
904     getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
905                     SectionKind::getMetadata());
906 }
907
908 const MCSection *TargetLoweringObjectFileMachO::
909 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
910                          Mangler *Mang, const TargetMachine &TM) const {
911   // Parse the section specifier and create it if valid.
912   StringRef Segment, Section;
913   unsigned TAA, StubSize;
914   std::string ErrorCode =
915     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
916                                           TAA, StubSize);
917   if (!ErrorCode.empty()) {
918     // If invalid, report the error with llvm_report_error.
919     llvm_report_error("Global variable '" + GV->getNameStr() +
920                       "' has an invalid section specifier '" + GV->getSection()+
921                       "': " + ErrorCode + ".");
922     // Fall back to dropping it into the data section.
923     return DataSection;
924   }
925
926   // Get the section.
927   const MCSectionMachO *S =
928     getMachOSection(Segment, Section, TAA, StubSize, Kind);
929
930   // Okay, now that we got the section, verify that the TAA & StubSize agree.
931   // If the user declared multiple globals with different section flags, we need
932   // to reject it here.
933   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
934     // If invalid, report the error with llvm_report_error.
935     llvm_report_error("Global variable '" + GV->getNameStr() +
936                       "' section type or attributes does not match previous"
937                       " section specifier");
938   }
939
940   return S;
941 }
942
943 const MCSection *TargetLoweringObjectFileMachO::
944 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
945                        Mangler *Mang, const TargetMachine &TM) const {
946   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
947
948   if (Kind.isText())
949     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
950
951   // If this is weak/linkonce, put this in a coalescable section, either in text
952   // or data depending on if it is writable.
953   if (GV->isWeakForLinker()) {
954     if (Kind.isReadOnly())
955       return ConstTextCoalSection;
956     return DataCoalSection;
957   }
958
959   // FIXME: Alignment check should be handled by section classifier.
960   if (Kind.isMergeable1ByteCString() ||
961       Kind.isMergeable2ByteCString()) {
962     if (TM.getTargetData()->getPreferredAlignment(
963                                               cast<GlobalVariable>(GV)) < 32) {
964       if (Kind.isMergeable1ByteCString())
965         return CStringSection;
966       assert(Kind.isMergeable2ByteCString());
967       return UStringSection;
968     }
969   }
970
971   if (Kind.isMergeableConst()) {
972     if (Kind.isMergeableConst4())
973       return FourByteConstantSection;
974     if (Kind.isMergeableConst8())
975       return EightByteConstantSection;
976     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
977       return SixteenByteConstantSection;
978   }
979
980   // Otherwise, if it is readonly, but not something we can specially optimize,
981   // just drop it in .const.
982   if (Kind.isReadOnly())
983     return ReadOnlySection;
984
985   // If this is marked const, put it into a const section.  But if the dynamic
986   // linker needs to write to it, put it in the data segment.
987   if (Kind.isReadOnlyWithRel())
988     return ConstDataSection;
989
990   // Put zero initialized globals with strong external linkage in the
991   // DATA, __common section with the .zerofill directive.
992   if (Kind.isBSSExtern())
993     return DataCommonSection;
994
995   // Put zero initialized globals with local linkage in __DATA,__bss directive
996   // with the .zerofill directive (aka .lcomm).
997   if (Kind.isBSSLocal())
998     return DataBSSSection;
999   
1000   // Otherwise, just drop the variable in the normal data section.
1001   return DataSection;
1002 }
1003
1004 const MCSection *
1005 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
1006   // If this constant requires a relocation, we have to put it in the data
1007   // segment, not in the text segment.
1008   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
1009     return ConstDataSection;
1010
1011   if (Kind.isMergeableConst4())
1012     return FourByteConstantSection;
1013   if (Kind.isMergeableConst8())
1014     return EightByteConstantSection;
1015   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
1016     return SixteenByteConstantSection;
1017   return ReadOnlySection;  // .const
1018 }
1019
1020 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
1021 /// not to emit the UsedDirective for some symbols in llvm.used.
1022 // FIXME: REMOVE this (rdar://7071300)
1023 bool TargetLoweringObjectFileMachO::
1024 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
1025   /// On Darwin, internally linked data beginning with "L" or "l" does not have
1026   /// the directive emitted (this occurs in ObjC metadata).
1027   if (!GV) return false;
1028
1029   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
1030   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
1031     // FIXME: ObjC metadata is currently emitted as internal symbols that have
1032     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
1033     // this horrible hack can go away.
1034     SmallString<64> Name;
1035     Mang->getNameWithPrefix(Name, GV, false);
1036     if (Name[0] == 'L' || Name[0] == 'l')
1037       return false;
1038   }
1039
1040   return true;
1041 }
1042
1043 const MCExpr *TargetLoweringObjectFileMachO::
1044 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
1045                              MachineModuleInfo *MMI, unsigned Encoding) const {
1046   // The mach-o version of this method defaults to returning a stub reference.
1047
1048   if (Encoding & dwarf::DW_EH_PE_indirect) {
1049     SmallString<128> Name;
1050     Mang->getNameWithPrefix(Name, GV, true);
1051     Name += "$non_lazy_ptr";
1052     MCSymbol *Sym = getContext().GetOrCreateSymbol(Name.str());
1053
1054     return TargetLoweringObjectFile::
1055       getSymbolForDwarfReference(Sym, MMI,
1056                                  Encoding & ~dwarf::DW_EH_PE_indirect);
1057   }
1058
1059   return TargetLoweringObjectFile::
1060     getSymbolForDwarfGlobalReference(GV, Mang, MMI, Encoding);
1061 }
1062
1063
1064 //===----------------------------------------------------------------------===//
1065 //                                  COFF
1066 //===----------------------------------------------------------------------===//
1067
1068 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
1069
1070 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
1071   delete (COFFUniqueMapTy*)UniquingMap;
1072 }
1073
1074
1075 const MCSection *TargetLoweringObjectFileCOFF::
1076 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const {
1077   // Create the map if it doesn't already exist.
1078   if (UniquingMap == 0)
1079     UniquingMap = new MachOUniqueMapTy();
1080   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
1081
1082   // Do the lookup, if we have a hit, return it.
1083   const MCSectionCOFF *&Entry = Map[Name];
1084   if (Entry) return Entry;
1085
1086   return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
1087 }
1088
1089 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1090                                               const TargetMachine &TM) {
1091   if (UniquingMap != 0)
1092     ((COFFUniqueMapTy*)UniquingMap)->clear();
1093   TargetLoweringObjectFile::Initialize(Ctx, TM);
1094   TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1095   DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1096   StaticCtorSection =
1097     getCOFFSection(".ctors", false, SectionKind::getDataRel());
1098   StaticDtorSection =
1099     getCOFFSection(".dtors", false, SectionKind::getDataRel());
1100
1101   // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1102   // though it contains relocatable pointers.  In PIC mode, this is probably a
1103   // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
1104   // adjusted or this should be a data section.
1105   LSDASection =
1106     getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1107   EHFrameSection =
1108     getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1109
1110   // Debug info.
1111   // FIXME: Don't use 'directive' mode here.
1112   DwarfAbbrevSection =
1113     getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1114                    true, SectionKind::getMetadata());
1115   DwarfInfoSection =
1116     getCOFFSection("\t.section\t.debug_info,\"dr\"",
1117                    true, SectionKind::getMetadata());
1118   DwarfLineSection =
1119     getCOFFSection("\t.section\t.debug_line,\"dr\"",
1120                    true, SectionKind::getMetadata());
1121   DwarfFrameSection =
1122     getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1123                    true, SectionKind::getMetadata());
1124   DwarfPubNamesSection =
1125     getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1126                    true, SectionKind::getMetadata());
1127   DwarfPubTypesSection =
1128     getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1129                    true, SectionKind::getMetadata());
1130   DwarfStrSection =
1131     getCOFFSection("\t.section\t.debug_str,\"dr\"",
1132                    true, SectionKind::getMetadata());
1133   DwarfLocSection =
1134     getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1135                    true, SectionKind::getMetadata());
1136   DwarfARangesSection =
1137     getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1138                    true, SectionKind::getMetadata());
1139   DwarfRangesSection =
1140     getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1141                    true, SectionKind::getMetadata());
1142   DwarfMacroInfoSection =
1143     getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1144                    true, SectionKind::getMetadata());
1145 }
1146
1147 const MCSection *TargetLoweringObjectFileCOFF::
1148 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1149                          Mangler *Mang, const TargetMachine &TM) const {
1150   return getCOFFSection(GV->getSection(), false, Kind);
1151 }
1152
1153 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1154   if (Kind.isText())
1155     return ".text$linkonce";
1156   if (Kind.isWriteable())
1157     return ".data$linkonce";
1158   return ".rdata$linkonce";
1159 }
1160
1161
1162 const MCSection *TargetLoweringObjectFileCOFF::
1163 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1164                        Mangler *Mang, const TargetMachine &TM) const {
1165   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1166
1167   // If this global is linkonce/weak and the target handles this by emitting it
1168   // into a 'uniqued' section name, create and return the section now.
1169   if (GV->isWeakForLinker()) {
1170     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1171     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1172     Mang->getNameWithPrefix(Name, GV, false);
1173     return getCOFFSection(Name.str(), false, Kind);
1174   }
1175
1176   if (Kind.isText())
1177     return getTextSection();
1178
1179   return getDataSection();
1180 }
1181