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