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