reject invalid code like:
[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/MC/MCContext.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/Target/TargetAsmInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 //                              Generic Code
33 //===----------------------------------------------------------------------===//
34
35 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
36   TextSection = 0;
37   DataSection = 0;
38   BSSSection = 0;
39   ReadOnlySection = 0;
40   StaticCtorSection = 0;
41   StaticDtorSection = 0;
42   LSDASection = 0;
43   EHFrameSection = 0;
44
45   DwarfAbbrevSection = 0;
46   DwarfInfoSection = 0;
47   DwarfLineSection = 0;
48   DwarfFrameSection = 0;
49   DwarfPubNamesSection = 0;
50   DwarfPubTypesSection = 0;
51   DwarfDebugInlineSection = 0;
52   DwarfStrSection = 0;
53   DwarfLocSection = 0;
54   DwarfARangesSection = 0;
55   DwarfRangesSection = 0;
56   DwarfMacroInfoSection = 0;
57 }
58
59 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
60 }
61
62 static bool isSuitableForBSS(const GlobalVariable *GV) {
63   Constant *C = GV->getInitializer();
64   
65   // Must have zero initializer.
66   if (!C->isNullValue())
67     return false;
68   
69   // Leave constant zeros in readonly constant sections, so they can be shared.
70   if (GV->isConstant())
71     return false;
72   
73   // If the global has an explicit section specified, don't put it in BSS.
74   if (!GV->getSection().empty())
75     return false;
76   
77   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
78   if (NoZerosInBSS)
79     return false;
80   
81   // Otherwise, put it in BSS!
82   return true;
83 }
84
85 /// IsNullTerminatedString - Return true if the specified constant (which is
86 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
87 /// nul value and contains no other nuls in it.
88 static bool IsNullTerminatedString(const Constant *C) {
89   const ArrayType *ATy = cast<ArrayType>(C->getType());
90   
91   // First check: is we have constant array of i8 terminated with zero
92   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
93     if (ATy->getNumElements() == 0) return false;
94
95     ConstantInt *Null =
96       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
97     if (Null == 0 || Null->getZExtValue() != 0)
98       return false; // Not null terminated.
99     
100     // Verify that the null doesn't occur anywhere else in the string.
101     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
102       // Reject constantexpr elements etc.
103       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
104           CVA->getOperand(i) == Null)
105         return false;
106     return true;
107   }
108
109   // Another possibility: [1 x i8] zeroinitializer
110   if (isa<ConstantAggregateZero>(C))
111     return ATy->getNumElements() == 1;
112
113   return false;
114 }
115
116 /// getKindForGlobal - This is a top-level target-independent classifier for
117 /// a global variable.  Given an global variable and information from TM, it
118 /// classifies the global in a variety of ways that make various target
119 /// implementations simpler.  The target implementation is free to ignore this
120 /// extra info of course.
121 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
122                                                        const TargetMachine &TM){
123   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
124          "Can only be used for global definitions");
125   
126   Reloc::Model ReloModel = TM.getRelocationModel();
127   
128   // Early exit - functions should be always in text sections.
129   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
130   if (GVar == 0)
131     return SectionKind::getText();
132   
133   // Handle thread-local data first.
134   if (GVar->isThreadLocal()) {
135     if (isSuitableForBSS(GVar))
136       return SectionKind::getThreadBSS();
137     return SectionKind::getThreadData();
138   }
139
140   // Variable can be easily put to BSS section.
141   if (isSuitableForBSS(GVar))
142     return SectionKind::getBSS();
143
144   Constant *C = GVar->getInitializer();
145   
146   // If the global is marked constant, we can put it into a mergable section,
147   // a mergable string section, or general .data if it contains relocations.
148   if (GVar->isConstant()) {
149     // If the initializer for the global contains something that requires a
150     // relocation, then we may have to drop this into a wriable data section
151     // even though it is marked const.
152     switch (C->getRelocationInfo()) {
153     default: llvm_unreachable("unknown relocation info kind");
154     case Constant::NoRelocation:
155       // If initializer is a null-terminated string, put it in a "cstring"
156       // section of the right width.
157       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
158         if (const IntegerType *ITy = 
159               dyn_cast<IntegerType>(ATy->getElementType())) {
160           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
161                ITy->getBitWidth() == 32) &&
162               IsNullTerminatedString(C)) {
163             if (ITy->getBitWidth() == 8)
164               return SectionKind::getMergeable1ByteCString();
165             if (ITy->getBitWidth() == 16)
166               return SectionKind::getMergeable2ByteCString();
167                                          
168             assert(ITy->getBitWidth() == 32 && "Unknown width");
169             return SectionKind::getMergeable4ByteCString();
170           }
171         }
172       }
173         
174       // Otherwise, just drop it into a mergable constant section.  If we have
175       // a section for this size, use it, otherwise use the arbitrary sized
176       // mergable section.
177       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
178       case 4:  return SectionKind::getMergeableConst4();
179       case 8:  return SectionKind::getMergeableConst8();
180       case 16: return SectionKind::getMergeableConst16();
181       default: return SectionKind::getMergeableConst();
182       }
183       
184     case Constant::LocalRelocation:
185       // In static relocation model, the linker will resolve all addresses, so
186       // the relocation entries will actually be constants by the time the app
187       // starts up.  However, we can't put this into a mergable section, because
188       // the linker doesn't take relocations into consideration when it tries to
189       // merge entries in the section.
190       if (ReloModel == Reloc::Static)
191         return SectionKind::getReadOnly();
192               
193       // Otherwise, the dynamic linker needs to fix it up, put it in the
194       // writable data.rel.local section.
195       return SectionKind::getReadOnlyWithRelLocal();
196               
197     case Constant::GlobalRelocations:
198       // In static relocation model, the linker will resolve all addresses, so
199       // the relocation entries will actually be constants by the time the app
200       // starts up.  However, we can't put this into a mergable section, because
201       // the linker doesn't take relocations into consideration when it tries to
202       // merge entries in the section.
203       if (ReloModel == Reloc::Static)
204         return SectionKind::getReadOnly();
205       
206       // Otherwise, the dynamic linker needs to fix it up, put it in the
207       // writable data.rel section.
208       return SectionKind::getReadOnlyWithRel();
209     }
210   }
211
212   // Okay, this isn't a constant.  If the initializer for the global is going
213   // to require a runtime relocation by the dynamic linker, put it into a more
214   // specific section to improve startup time of the app.  This coalesces these
215   // globals together onto fewer pages, improving the locality of the dynamic
216   // linker.
217   if (ReloModel == Reloc::Static)
218     return SectionKind::getDataNoRel();
219
220   switch (C->getRelocationInfo()) {
221   default: llvm_unreachable("unknown relocation info kind");
222   case Constant::NoRelocation:
223     return SectionKind::getDataNoRel();
224   case Constant::LocalRelocation:
225     return SectionKind::getDataRelLocal();
226   case Constant::GlobalRelocations:
227     return SectionKind::getDataRel();
228   }
229 }
230
231 /// SectionForGlobal - This method computes the appropriate section to emit
232 /// the specified global variable or function definition.  This should not
233 /// be passed external (or available externally) globals.
234 const MCSection *TargetLoweringObjectFile::
235 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
236                  const TargetMachine &TM) const {
237   // Select section name.
238   if (GV->hasSection())
239     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
240   
241   
242   // Use default section depending on the 'type' of global
243   return SelectSectionForGlobal(GV, Kind, Mang, TM);
244 }
245
246
247 // Lame default implementation. Calculate the section name for global.
248 const MCSection *
249 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
250                                                  SectionKind Kind,
251                                                  Mangler *Mang,
252                                                  const TargetMachine &TM) const{
253   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
254   
255   if (Kind.isText())
256     return getTextSection();
257   
258   if (Kind.isBSS() && BSSSection != 0)
259     return BSSSection;
260   
261   if (Kind.isReadOnly() && ReadOnlySection != 0)
262     return ReadOnlySection;
263
264   return getDataSection();
265 }
266
267 /// getSectionForConstant - Given a mergable constant with the
268 /// specified size and relocation information, return a section that it
269 /// should be placed in.
270 const MCSection *
271 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
272   if (Kind.isReadOnly() && ReadOnlySection != 0)
273     return ReadOnlySection;
274   
275   return DataSection;
276 }
277
278
279
280 //===----------------------------------------------------------------------===//
281 //                                  ELF
282 //===----------------------------------------------------------------------===//
283
284 const MCSection *TargetLoweringObjectFileELF::
285 getELFSection(const char *Name, bool isDirective, SectionKind Kind) const {
286   if (MCSection *S = getContext().GetSection(Name))
287     return S;
288   return MCSectionELF::Create(Name, isDirective, Kind, getContext());
289 }
290
291 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
292                                              const TargetMachine &TM) {
293   TargetLoweringObjectFile::Initialize(Ctx, TM);
294   if (!HasCrazyBSS)
295     BSSSection = getELFSection("\t.bss", true, SectionKind::getBSS());
296   else
297     // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
298     // FIXME: Does .section .bss work everywhere??
299     // FIXME2: this should just be handle by the section printer.  We should get
300     // away from syntactic view of the sections and MCSection should just be a
301     // semantic view.
302     BSSSection = getELFSection("\t.bss", false, SectionKind::getBSS());
303
304     
305   TextSection = getELFSection("\t.text", true, SectionKind::getText());
306   DataSection = getELFSection("\t.data", true, SectionKind::getDataRel());
307   ReadOnlySection =
308     getELFSection("\t.rodata", false, SectionKind::getReadOnly());
309   TLSDataSection =
310     getELFSection("\t.tdata", false, SectionKind::getThreadData());
311   
312   TLSBSSSection = getELFSection("\t.tbss", false, 
313                                      SectionKind::getThreadBSS());
314
315   DataRelSection = getELFSection("\t.data.rel", false,
316                                       SectionKind::getDataRel());
317   DataRelLocalSection = getELFSection("\t.data.rel.local", false,
318                                    SectionKind::getDataRelLocal());
319   DataRelROSection = getELFSection("\t.data.rel.ro", false,
320                                 SectionKind::getReadOnlyWithRel());
321   DataRelROLocalSection =
322     getELFSection("\t.data.rel.ro.local", false,
323                        SectionKind::getReadOnlyWithRelLocal());
324     
325   MergeableConst4Section = getELFSection(".rodata.cst4", false,
326                                 SectionKind::getMergeableConst4());
327   MergeableConst8Section = getELFSection(".rodata.cst8", false,
328                                 SectionKind::getMergeableConst8());
329   MergeableConst16Section = getELFSection(".rodata.cst16", false,
330                                SectionKind::getMergeableConst16());
331
332   StaticCtorSection =
333     getELFSection(".ctors", false, SectionKind::getDataRel());
334   StaticDtorSection =
335     getELFSection(".dtors", false, SectionKind::getDataRel());
336   
337   // Exception Handling Sections.
338   
339   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
340   // it contains relocatable pointers.  In PIC mode, this is probably a big
341   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
342   // adjusted or this should be a data section.
343   LSDASection =
344     getELFSection(".gcc_except_table", false, SectionKind::getReadOnly());
345   EHFrameSection =
346     getELFSection(".eh_frame", false, SectionKind::getDataRel());
347   
348   // Debug Info Sections.
349   DwarfAbbrevSection = 
350     getELFSection(".debug_abbrev", false, SectionKind::getMetadata());
351   DwarfInfoSection = 
352     getELFSection(".debug_info", false, SectionKind::getMetadata());
353   DwarfLineSection = 
354     getELFSection(".debug_line", false, SectionKind::getMetadata());
355   DwarfFrameSection = 
356     getELFSection(".debug_frame", false, SectionKind::getMetadata());
357   DwarfPubNamesSection = 
358     getELFSection(".debug_pubnames", false, SectionKind::getMetadata());
359   DwarfPubTypesSection = 
360     getELFSection(".debug_pubtypes", false, SectionKind::getMetadata());
361   DwarfStrSection = 
362     getELFSection(".debug_str", false, SectionKind::getMetadata());
363   DwarfLocSection = 
364     getELFSection(".debug_loc", false, SectionKind::getMetadata());
365   DwarfARangesSection = 
366     getELFSection(".debug_aranges", false, SectionKind::getMetadata());
367   DwarfRangesSection = 
368     getELFSection(".debug_ranges", false, SectionKind::getMetadata());
369   DwarfMacroInfoSection = 
370     getELFSection(".debug_macinfo", false, SectionKind::getMetadata());
371 }
372
373
374 static SectionKind 
375 getELFKindForNamedSection(const char *Name, SectionKind K) {
376   if (Name[0] != '.') return K;
377   
378   // Some lame default implementation based on some magic section names.
379   if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
380       strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
381       strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
382       strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
383     return SectionKind::getBSS();
384   
385   if (strcmp(Name, ".tdata") == 0 ||
386       strncmp(Name, ".tdata.", 7) == 0 ||
387       strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
388       strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
389     return SectionKind::getThreadData();
390   
391   if (strcmp(Name, ".tbss") == 0 ||
392       strncmp(Name, ".tbss.", 6) == 0 ||
393       strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
394       strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
395     return SectionKind::getThreadBSS();
396   
397   return K;
398 }
399
400 const MCSection *TargetLoweringObjectFileELF::
401 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
402                          Mangler *Mang, const TargetMachine &TM) const {
403   // Infer section flags from the section name if we can.
404   Kind = getELFKindForNamedSection(GV->getSection().c_str(), Kind);
405   
406   return getELFSection(GV->getSection().c_str(), false, Kind);
407 }
408
409 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
410   if (Kind.isText())                 return ".gnu.linkonce.t.";
411   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
412   
413   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
414   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
415   
416   if (Kind.isBSS())                  return ".gnu.linkonce.b.";
417   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
418   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
419   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
420   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
421   
422   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
423   return ".gnu.linkonce.d.rel.ro.";
424 }
425
426 const MCSection *TargetLoweringObjectFileELF::
427 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
428                        Mangler *Mang, const TargetMachine &TM) const {
429   
430   // If this global is linkonce/weak and the target handles this by emitting it
431   // into a 'uniqued' section name, create and return the section now.
432   if (GV->isWeakForLinker()) {
433     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
434     std::string Name = Mang->makeNameProper(GV->getNameStr());
435     return getELFSection((Prefix+Name).c_str(), false, Kind);
436   }
437   
438   if (Kind.isText()) return TextSection;
439   
440   if (Kind.isMergeable1ByteCString() ||
441       Kind.isMergeable2ByteCString() ||
442       Kind.isMergeable4ByteCString()) {
443     
444     // We also need alignment here.
445     // FIXME: this is getting the alignment of the character, not the
446     // alignment of the global!
447     unsigned Align = 
448       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
449     
450     const char *SizeSpec = ".rodata.str1.";
451     if (Kind.isMergeable2ByteCString())
452       SizeSpec = ".rodata.str2.";
453     else if (Kind.isMergeable4ByteCString())
454       SizeSpec = ".rodata.str4.";
455     else
456       assert(Kind.isMergeable1ByteCString() && "unknown string width");
457     
458     
459     std::string Name = SizeSpec + utostr(Align);
460     return getELFSection(Name.c_str(), false, Kind);
461   }
462   
463   if (Kind.isMergeableConst()) {
464     if (Kind.isMergeableConst4())
465       return MergeableConst4Section;
466     if (Kind.isMergeableConst8())
467       return MergeableConst8Section;
468     if (Kind.isMergeableConst16())
469       return MergeableConst16Section;
470     return ReadOnlySection;  // .const
471   }
472   
473   if (Kind.isReadOnly())             return ReadOnlySection;
474   
475   if (Kind.isThreadData())           return TLSDataSection;
476   if (Kind.isThreadBSS())            return TLSBSSSection;
477   
478   if (Kind.isBSS())                  return BSSSection;
479   
480   if (Kind.isDataNoRel())            return DataSection;
481   if (Kind.isDataRelLocal())         return DataRelLocalSection;
482   if (Kind.isDataRel())              return DataRelSection;
483   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
484   
485   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
486   return DataRelROSection;
487 }
488
489 /// getSectionForConstant - Given a mergeable constant with the
490 /// specified size and relocation information, return a section that it
491 /// should be placed in.
492 const MCSection *TargetLoweringObjectFileELF::
493 getSectionForConstant(SectionKind Kind) const {
494   if (Kind.isMergeableConst4())
495     return MergeableConst4Section;
496   if (Kind.isMergeableConst8())
497     return MergeableConst8Section;
498   if (Kind.isMergeableConst16())
499     return MergeableConst16Section;
500   if (Kind.isReadOnly())
501     return ReadOnlySection;
502   
503   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
504   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
505   return DataRelROSection;
506 }
507
508 //===----------------------------------------------------------------------===//
509 //                                 MachO
510 //===----------------------------------------------------------------------===//
511
512 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
513
514 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
515   // If we have the MachO uniquing map, free it.
516   delete (MachOUniqueMapTy*)UniquingMap;
517 }
518
519
520 const MCSectionMachO *TargetLoweringObjectFileMachO::
521 getMachOSection(const StringRef &Segment, const StringRef &Section,
522                 unsigned TypeAndAttributes,
523                 unsigned Reserved2, SectionKind Kind) const {
524   // We unique sections by their segment/section pair.  The returned section
525   // may not have the same flags as the requested section, if so this should be
526   // diagnosed by the client as an error.
527   
528   // Create the map if it doesn't already exist.
529   if (UniquingMap == 0)
530     UniquingMap = new MachOUniqueMapTy();
531   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
532   
533   // Form the name to look up.
534   SmallString<64> Name;
535   Name.append(Segment.begin(), Segment.end());
536   Name.push_back(',');
537   Name.append(Section.begin(), Section.end());
538   
539   // Do the lookup, if we have a hit, return it.
540   const MCSectionMachO *&Entry = Map[StringRef(Name.data(), Name.size())];
541   if (Entry) return Entry;
542
543   // Otherwise, return a new section.
544   return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
545                                         Reserved2, Kind, getContext());
546 }
547
548
549 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
550                                                const TargetMachine &TM) {
551   TargetLoweringObjectFile::Initialize(Ctx, TM);
552   
553   TextSection // .text
554     = getMachOSection("__TEXT", "__text",
555                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
556                       SectionKind::getText());
557   DataSection // .data
558     = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
559   
560   CStringSection // .cstring
561     = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
562                       SectionKind::getMergeable1ByteCString());
563   UStringSection
564     = getMachOSection("__TEXT","__ustring", 0,
565                       SectionKind::getMergeable2ByteCString());
566   FourByteConstantSection // .literal4
567     = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
568                       SectionKind::getMergeableConst4());
569   EightByteConstantSection // .literal8
570     = getMachOSection("__TEXT", "__literal8", 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       getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
580                       SectionKind::getMergeableConst16());
581   
582   ReadOnlySection  // .const
583     = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
584   
585   TextCoalSection
586     = getMachOSection("__TEXT", "__textcoal_nt",
587                       MCSectionMachO::S_COALESCED |
588                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
589                       SectionKind::getText());
590   ConstTextCoalSection
591     = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
592                       SectionKind::getText());
593   ConstDataCoalSection
594     = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
595                       SectionKind::getText());
596   ConstDataSection  // .const_data
597     = getMachOSection("__DATA", "__const", 0,
598                       SectionKind::getReadOnlyWithRel());
599   DataCoalSection
600     = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
601                       SectionKind::getDataRel());
602
603   
604   LazySymbolPointerSection
605     = getMachOSection("__DATA", "__la_symbol_ptr",
606                       MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
607                       SectionKind::getMetadata());
608   NonLazySymbolPointerSection
609     = getMachOSection("__DATA", "__nl_symbol_ptr",
610                       MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
611                       SectionKind::getMetadata());
612   
613   if (TM.getRelocationModel() == Reloc::Static) {
614     StaticCtorSection
615       = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
616     StaticDtorSection
617       = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
618   } else {
619     StaticCtorSection
620       = getMachOSection("__DATA", "__mod_init_func",
621                         MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
622                         SectionKind::getDataRel());
623     StaticDtorSection
624       = getMachOSection("__DATA", "__mod_term_func", 
625                         MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
626                         SectionKind::getDataRel());
627   }
628   
629   // Exception Handling.
630   LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
631                                 SectionKind::getDataRel());
632   EHFrameSection =
633     getMachOSection("__TEXT", "__eh_frame",
634                     MCSectionMachO::S_COALESCED |
635                     MCSectionMachO::S_ATTR_NO_TOC |
636                     MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
637                     MCSectionMachO::S_ATTR_LIVE_SUPPORT,
638                     SectionKind::getReadOnly());
639
640   // Debug Information.
641   DwarfAbbrevSection = 
642     getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
643                     SectionKind::getMetadata());
644   DwarfInfoSection =  
645     getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
646                     SectionKind::getMetadata());
647   DwarfLineSection =  
648     getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
649                     SectionKind::getMetadata());
650   DwarfFrameSection =  
651     getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
652                     SectionKind::getMetadata());
653   DwarfPubNamesSection =  
654     getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
655                     SectionKind::getMetadata());
656   DwarfPubTypesSection =  
657     getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
658                     SectionKind::getMetadata());
659   DwarfStrSection =  
660     getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
661                     SectionKind::getMetadata());
662   DwarfLocSection =  
663     getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
664                     SectionKind::getMetadata());
665   DwarfARangesSection =  
666     getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
667                     SectionKind::getMetadata());
668   DwarfRangesSection =  
669     getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
670                     SectionKind::getMetadata());
671   DwarfMacroInfoSection =  
672     getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
673                     SectionKind::getMetadata());
674   DwarfDebugInlineSection = 
675     getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
676                     SectionKind::getMetadata());
677 }
678
679 const MCSection *TargetLoweringObjectFileMachO::
680 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
681                          Mangler *Mang, const TargetMachine &TM) const {
682   // Parse the section specifier and create it if valid.
683   StringRef Segment, Section;
684   unsigned TAA, StubSize;
685   std::string ErrorCode =
686     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
687                                           TAA, StubSize);
688   if (!ErrorCode.empty()) {
689     // If invalid, report the error with llvm_report_error.
690     llvm_report_error("Global variable '" + GV->getNameStr() +
691                       "' has an invalid section specifier '" + GV->getSection()+
692                       "': " + ErrorCode + ".");
693     // Fall back to dropping it into the data section.
694     return DataSection;
695   }
696   
697   // Get the section.
698   const MCSectionMachO *S =
699     getMachOSection(Segment, Section, TAA, StubSize, Kind);
700   
701   // Okay, now that we got the section, verify that the TAA & StubSize agree.
702   // If the user declared multiple globals with different section flags, we need
703   // to reject it here.
704   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
705     // If invalid, report the error with llvm_report_error.
706     llvm_report_error("Global variable '" + GV->getNameStr() +
707                       "' section type or attributes does not match previous"
708                       " section specifier");
709   }
710   
711   
712   
713   return S;
714 }
715
716 const MCSection *TargetLoweringObjectFileMachO::
717 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
718                        Mangler *Mang, const TargetMachine &TM) const {
719   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
720   
721   if (Kind.isText())
722     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
723   
724   // If this is weak/linkonce, put this in a coalescable section, either in text
725   // or data depending on if it is writable.
726   if (GV->isWeakForLinker()) {
727     if (Kind.isReadOnly())
728       return ConstTextCoalSection;
729     return DataCoalSection;
730   }
731   
732   // FIXME: Alignment check should be handled by section classifier.
733   if (Kind.isMergeable1ByteCString() ||
734       Kind.isMergeable2ByteCString()) {
735     if (TM.getTargetData()->getPreferredAlignment(
736                                               cast<GlobalVariable>(GV)) < 32) {
737       if (Kind.isMergeable1ByteCString())
738         return CStringSection;
739       assert(Kind.isMergeable2ByteCString());
740       return UStringSection;
741     }
742   }
743   
744   if (Kind.isMergeableConst()) {
745     if (Kind.isMergeableConst4())
746       return FourByteConstantSection;
747     if (Kind.isMergeableConst8())
748       return EightByteConstantSection;
749     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
750       return SixteenByteConstantSection;
751   }
752
753   // Otherwise, if it is readonly, but not something we can specially optimize,
754   // just drop it in .const.
755   if (Kind.isReadOnly())
756     return ReadOnlySection;
757
758   // If this is marked const, put it into a const section.  But if the dynamic
759   // linker needs to write to it, put it in the data segment.
760   if (Kind.isReadOnlyWithRel())
761     return ConstDataSection;
762   
763   // Otherwise, just drop the variable in the normal data section.
764   return DataSection;
765 }
766
767 const MCSection *
768 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
769   // If this constant requires a relocation, we have to put it in the data
770   // segment, not in the text segment.
771   if (Kind.isDataRel())
772     return ConstDataSection;
773   
774   if (Kind.isMergeableConst4())
775     return FourByteConstantSection;
776   if (Kind.isMergeableConst8())
777     return EightByteConstantSection;
778   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
779     return SixteenByteConstantSection;
780   return ReadOnlySection;  // .const
781 }
782
783 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
784 /// not to emit the UsedDirective for some symbols in llvm.used.
785 // FIXME: REMOVE this (rdar://7071300)
786 bool TargetLoweringObjectFileMachO::
787 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
788   /// On Darwin, internally linked data beginning with "L" or "l" does not have
789   /// the directive emitted (this occurs in ObjC metadata).
790   if (!GV) return false;
791     
792   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
793   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
794     // FIXME: ObjC metadata is currently emitted as internal symbols that have
795     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
796     // this horrible hack can go away.
797     const std::string &Name = Mang->getMangledName(GV);
798     if (Name[0] == 'L' || Name[0] == 'l')
799       return false;
800   }
801   
802   return true;
803 }
804
805
806 //===----------------------------------------------------------------------===//
807 //                                  COFF
808 //===----------------------------------------------------------------------===//
809
810
811 const MCSection *TargetLoweringObjectFileCOFF::
812 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
813   if (MCSection *S = getContext().GetSection(Name))
814     return S;
815   return MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
816 }
817
818 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
819                                               const TargetMachine &TM) {
820   TargetLoweringObjectFile::Initialize(Ctx, TM);
821   TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
822   DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
823   StaticCtorSection =
824     getCOFFSection(".ctors", false, SectionKind::getDataRel());
825   StaticDtorSection =
826     getCOFFSection(".dtors", false, SectionKind::getDataRel());
827   
828   
829   // Debug info.
830   // FIXME: Don't use 'directive' mode here.
831   DwarfAbbrevSection =  
832     getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
833                    true, SectionKind::getMetadata());
834   DwarfInfoSection =    
835     getCOFFSection("\t.section\t.debug_info,\"dr\"",
836                    true, SectionKind::getMetadata());
837   DwarfLineSection =    
838     getCOFFSection("\t.section\t.debug_line,\"dr\"",
839                    true, SectionKind::getMetadata());
840   DwarfFrameSection =   
841     getCOFFSection("\t.section\t.debug_frame,\"dr\"",
842                    true, SectionKind::getMetadata());
843   DwarfPubNamesSection =
844     getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
845                    true, SectionKind::getMetadata());
846   DwarfPubTypesSection =
847     getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
848                    true, SectionKind::getMetadata());
849   DwarfStrSection =     
850     getCOFFSection("\t.section\t.debug_str,\"dr\"",
851                    true, SectionKind::getMetadata());
852   DwarfLocSection =     
853     getCOFFSection("\t.section\t.debug_loc,\"dr\"",
854                    true, SectionKind::getMetadata());
855   DwarfARangesSection = 
856     getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
857                    true, SectionKind::getMetadata());
858   DwarfRangesSection =  
859     getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
860                    true, SectionKind::getMetadata());
861   DwarfMacroInfoSection = 
862     getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
863                    true, SectionKind::getMetadata());
864 }
865
866 const MCSection *TargetLoweringObjectFileCOFF::
867 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
868                          Mangler *Mang, const TargetMachine &TM) const {
869   return getCOFFSection(GV->getSection().c_str(), false, Kind);
870 }
871
872 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
873   if (Kind.isText())
874     return ".text$linkonce";
875   if (Kind.isWriteable())
876     return ".data$linkonce";
877   return ".rdata$linkonce";
878 }
879
880
881 const MCSection *TargetLoweringObjectFileCOFF::
882 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
883                        Mangler *Mang, const TargetMachine &TM) const {
884   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
885   
886   // If this global is linkonce/weak and the target handles this by emitting it
887   // into a 'uniqued' section name, create and return the section now.
888   if (GV->isWeakForLinker()) {
889     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
890     std::string Name = Mang->makeNameProper(GV->getNameStr());
891     return getCOFFSection((Prefix+Name).c_str(), false, Kind);
892   }
893   
894   if (Kind.isText())
895     return getTextSection();
896   
897   return getDataSection();
898 }
899