make SectionKind keep track of whether a global had an explicit
[oota-llvm.git] / lib / Target / TargetAsmInfo.cpp
1 //===-- TargetAsmInfo.cpp - Asm 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 defines target asm properties related what form asm statements
11 // should take.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Function.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/Target/TargetAsmInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <cctype>
28 #include <cstring>
29 using namespace llvm;
30
31 TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) {
32   BSSSection = "\t.bss";
33   BSSSection_ = 0;
34   ReadOnlySection = 0;
35   TLSDataSection = 0;
36   TLSBSSSection = 0;
37   ZeroFillDirective = 0;
38   NonexecutableStackDirective = 0;
39   NeedsSet = false;
40   MaxInstLength = 4;
41   PCSymbol = "$";
42   SeparatorChar = ';';
43   CommentColumn = 60;
44   CommentString = "#";
45   FirstOperandColumn = 0;
46   MaxOperandLength = 0;
47   GlobalPrefix = "";
48   PrivateGlobalPrefix = ".";
49   LinkerPrivateGlobalPrefix = "";
50   JumpTableSpecialLabelPrefix = 0;
51   GlobalVarAddrPrefix = "";
52   GlobalVarAddrSuffix = "";
53   FunctionAddrPrefix = "";
54   FunctionAddrSuffix = "";
55   PersonalityPrefix = "";
56   PersonalitySuffix = "";
57   NeedsIndirectEncoding = false;
58   InlineAsmStart = "#APP";
59   InlineAsmEnd = "#NO_APP";
60   AssemblerDialect = 0;
61   AllowQuotesInName = false;
62   ZeroDirective = "\t.zero\t";
63   ZeroDirectiveSuffix = 0;
64   AsciiDirective = "\t.ascii\t";
65   AscizDirective = "\t.asciz\t";
66   Data8bitsDirective = "\t.byte\t";
67   Data16bitsDirective = "\t.short\t";
68   Data32bitsDirective = "\t.long\t";
69   Data64bitsDirective = "\t.quad\t";
70   AlignDirective = "\t.align\t";
71   AlignmentIsInBytes = true;
72   TextAlignFillValue = 0;
73   SwitchToSectionDirective = "\t.section\t";
74   TextSectionStartSuffix = "";
75   DataSectionStartSuffix = "";
76   SectionEndDirectiveSuffix = 0;
77   ConstantPoolSection = "\t.section .rodata";
78   JumpTableDataSection = "\t.section .rodata";
79   JumpTableDirective = 0;
80   CStringSection = 0;
81   CStringSection_ = 0;
82   // FIXME: Flags are ELFish - replace with normal section stuff.
83   StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
84   StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
85   GlobalDirective = "\t.globl\t";
86   SetDirective = 0;
87   LCOMMDirective = 0;
88   COMMDirective = "\t.comm\t";
89   COMMDirectiveTakesAlignment = true;
90   HasDotTypeDotSizeDirective = true;
91   HasSingleParameterDotFile = true;
92   UsedDirective = 0;
93   WeakRefDirective = 0;
94   WeakDefDirective = 0;
95   // FIXME: These are ELFish - move to ELFTAI.
96   HiddenDirective = "\t.hidden\t";
97   ProtectedDirective = "\t.protected\t";
98   AbsoluteDebugSectionOffsets = false;
99   AbsoluteEHSectionOffsets = false;
100   HasLEB128 = false;
101   HasDotLocAndDotFile = false;
102   SupportsDebugInformation = false;
103   SupportsExceptionHandling = false;
104   DwarfRequiresFrameSection = true;
105   DwarfUsesInlineInfoSection = false;
106   Is_EHSymbolPrivate = true;
107   GlobalEHDirective = 0;
108   SupportsWeakOmittedEHFrame = true;
109   DwarfSectionOffsetDirective = 0;
110   DwarfAbbrevSection = ".debug_abbrev";
111   DwarfInfoSection = ".debug_info";
112   DwarfLineSection = ".debug_line";
113   DwarfFrameSection = ".debug_frame";
114   DwarfPubNamesSection = ".debug_pubnames";
115   DwarfPubTypesSection = ".debug_pubtypes";
116   DwarfDebugInlineSection = ".debug_inlined";
117   DwarfStrSection = ".debug_str";
118   DwarfLocSection = ".debug_loc";
119   DwarfARangesSection = ".debug_aranges";
120   DwarfRangesSection = ".debug_ranges";
121   DwarfMacroInfoSection = ".debug_macinfo";
122   DwarfEHFrameSection = ".eh_frame";
123   DwarfExceptionSection = ".gcc_except_table";
124   AsmTransCBE = 0;
125   TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
126   DataSection = getUnnamedSection("\t.data", SectionFlags::Writable);
127 }
128
129 TargetAsmInfo::~TargetAsmInfo() {
130 }
131
132 /// Measure the specified inline asm to determine an approximation of its
133 /// length.
134 /// Comments (which run till the next SeparatorChar or newline) do not
135 /// count as an instruction.
136 /// Any other non-whitespace text is considered an instruction, with
137 /// multiple instructions separated by SeparatorChar or newlines.
138 /// Variable-length instructions are not handled here; this function
139 /// may be overloaded in the target code to do that.
140 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
141   // Count the number of instructions in the asm.
142   bool atInsnStart = true;
143   unsigned Length = 0;
144   for (; *Str; ++Str) {
145     if (*Str == '\n' || *Str == SeparatorChar)
146       atInsnStart = true;
147     if (atInsnStart && !isspace(*Str)) {
148       Length += MaxInstLength;
149       atInsnStart = false;
150     }
151     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
152       atInsnStart = false;
153   }
154
155   return Length;
156 }
157
158 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
159                                               bool Global) const {
160   return dwarf::DW_EH_PE_absptr;
161 }
162
163 static bool isSuitableForBSS(const GlobalVariable *GV) {
164   Constant *C = GV->getInitializer();
165   
166   // Must have zero initializer.
167   if (!C->isNullValue())
168     return false;
169   
170   // Leave constant zeros in readonly constant sections, so they can be shared.
171   if (GV->isConstant())
172     return false;
173   
174   // If the global has an explicit section specified, don't put it in BSS.
175   if (!GV->getSection().empty())
176     return false;
177   
178   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
179   if (NoZerosInBSS)
180     return false;
181   
182   // Otherwise, put it in BSS!
183   return true;
184 }
185
186 static bool isConstantString(const Constant *C) {
187   // First check: is we have constant array of i8 terminated with zero
188   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
189   // Check, if initializer is a null-terminated string
190   if (CVA && CVA->isCString())
191     return true;
192
193   // Another possibility: [1 x i8] zeroinitializer
194   if (isa<ConstantAggregateZero>(C))
195     if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
196       return (Ty->getElementType() == Type::Int8Ty &&
197               Ty->getNumElements() == 1);
198
199   return false;
200 }
201
202 static unsigned SectionFlagsForGlobal(const GlobalValue *GV,
203                                       SectionKind Kind) {
204   // Decode flags from global and section kind.
205   unsigned Flags = SectionFlags::None;
206   if (GV->isWeakForLinker())
207     Flags |= SectionFlags::Linkonce;
208   if (Kind.isBSS() || Kind.isThreadBSS())
209     Flags |= SectionFlags::BSS;
210   if (Kind.isThreadLocal())
211     Flags |= SectionFlags::TLS;
212   if (Kind.isText())
213     Flags |= SectionFlags::Code;
214   if (Kind.isWriteable())
215     Flags |= SectionFlags::Writable;
216
217   return Flags;
218 }
219
220 static SectionKind::Kind SectionKindForGlobal(const GlobalValue *GV,
221                                               const TargetMachine &TM) {
222   Reloc::Model ReloModel = TM.getRelocationModel();
223   
224   // Early exit - functions should be always in text sections.
225   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
226   if (GVar == 0)
227     return SectionKind::Text;
228
229   
230   // Handle thread-local data first.
231   if (GVar->isThreadLocal()) {
232     if (isSuitableForBSS(GVar))
233       return SectionKind::ThreadBSS;
234     return SectionKind::ThreadData;
235   }
236
237   // Variable can be easily put to BSS section.
238   if (isSuitableForBSS(GVar))
239     return SectionKind::BSS;
240
241   Constant *C = GVar->getInitializer();
242   
243   // If the global is marked constant, we can put it into a mergable section,
244   // a mergable string section, or general .data if it contains relocations.
245   if (GVar->isConstant()) {
246     // If the initializer for the global contains something that requires a
247     // relocation, then we may have to drop this into a wriable data section
248     // even though it is marked const.
249     switch (C->getRelocationInfo()) {
250     default: llvm_unreachable("unknown relocation info kind");
251     case Constant::NoRelocation:
252       // If initializer is a null-terminated string, put it in a "cstring"
253       // section if the target has it.
254       if (isConstantString(C))
255         return SectionKind::MergeableCString;
256       
257       // Otherwise, just drop it into a mergable constant section.  If we have
258       // a section for this size, use it, otherwise use the arbitrary sized
259       // mergable section.
260       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
261       case 4:  return SectionKind::MergeableConst4;
262       case 8:  return SectionKind::MergeableConst8;
263       case 16: return SectionKind::MergeableConst16;
264       default: return SectionKind::MergeableConst;
265       }
266       
267     case Constant::LocalRelocation:
268       // In static relocation model, the linker will resolve all addresses, so
269       // the relocation entries will actually be constants by the time the app
270       // starts up.
271       if (ReloModel == Reloc::Static)
272         return SectionKind::ReadOnly;
273               
274       // Otherwise, the dynamic linker needs to fix it up, put it in the
275       // writable data.rel.local section.
276       return SectionKind::ReadOnlyWithRelLocal;
277               
278     case Constant::GlobalRelocations:
279       // In static relocation model, the linker will resolve all addresses, so
280       // the relocation entries will actually be constants by the time the app
281       // starts up.
282       if (ReloModel == Reloc::Static)
283         return SectionKind::ReadOnly;
284       
285       // Otherwise, the dynamic linker needs to fix it up, put it in the
286       // writable data.rel section.
287       return SectionKind::ReadOnlyWithRel;
288     }
289   }
290
291   // Okay, this isn't a constant.  If the initializer for the global is going
292   // to require a runtime relocation by the dynamic linker, put it into a more
293   // specific section to improve startup time of the app.  This coalesces these
294   // globals together onto fewer pages, improving the locality of the dynamic
295   // linker.
296   if (ReloModel == Reloc::Static)
297     return SectionKind::DataNoRel;
298
299   switch (C->getRelocationInfo()) {
300   default: llvm_unreachable("unknown relocation info kind");
301   case Constant::NoRelocation:
302     return SectionKind::DataNoRel;
303   case Constant::LocalRelocation:
304     return SectionKind::DataRelLocal;
305   case Constant::GlobalRelocations:
306     return SectionKind::DataRel;
307   }
308 }
309
310 /// SectionForGlobal - This method computes the appropriate section to emit
311 /// the specified global variable or function definition.  This should not
312 /// be passed external (or available externally) globals.
313 const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
314   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
315          "Can only be used for global definitions");
316   
317   SectionKind::Kind GVKind = SectionKindForGlobal(GV, TM);
318   
319   SectionKind Kind = SectionKind::get(GVKind, GV->isWeakForLinker(),
320                                       GV->hasSection());
321
322
323   // Select section name.
324   if (GV->hasSection()) {
325     // If the target has special section hacks for specifically named globals,
326     // return them now.
327     if (const Section *TS = getSpecialCasedSectionGlobals(GV, Kind))
328       return TS;
329     
330     // Honour section already set, if any.
331     unsigned Flags = SectionFlagsForGlobal(GV, Kind);
332
333     // This is an explicitly named section.
334     Flags |= SectionFlags::Named;
335     
336     // If the target has magic semantics for certain section names, make sure to
337     // pick up the flags.  This allows the user to write things with attribute
338     // section and still get the appropriate section flags printed.
339     Flags |= getFlagsForNamedSection(GV->getSection().c_str());
340     
341     return getNamedSection(GV->getSection().c_str(), Flags);
342   }
343
344   // If this global is linkonce/weak and the target handles this by emitting it
345   // into a 'uniqued' section name, create and return the section now.
346   if (GV->isWeakForLinker()) {
347     if (const char *Prefix = getSectionPrefixForUniqueGlobal(Kind)) {
348       unsigned Flags = SectionFlagsForGlobal(GV, Kind);
349
350       // FIXME: Use mangler interface (PR4584).
351       std::string Name = Prefix+GV->getNameStr();
352       return getNamedSection(Name.c_str(), Flags);
353     }
354   }
355   
356   // Use default section depending on the 'type' of global
357   return SelectSectionForGlobal(GV, Kind);
358 }
359
360 // Lame default implementation. Calculate the section name for global.
361 const Section*
362 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV,
363                                       SectionKind Kind) const {
364   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
365   
366   if (Kind.isText())
367     return getTextSection();
368   
369   if (Kind.isBSS())
370     if (const Section *S = getBSSSection_())
371       return S;
372   
373   if (Kind.isReadOnly())
374     if (const Section *S = getReadOnlySection())
375       return S;
376
377   return getDataSection();
378 }
379
380 /// getSectionForMergableConstant - Given a mergable constant with the
381 /// specified size and relocation information, return a section that it
382 /// should be placed in.
383 const Section *
384 TargetAsmInfo::getSectionForMergeableConstant(SectionKind Kind) const {
385   if (Kind.isReadOnly())
386     if (const Section *S = getReadOnlySection())
387       return S;
388   
389   return getDataSection();
390 }
391
392
393 const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
394                                               bool Override) const {
395   Section &S = Sections[Name];
396
397   // This is newly-created section, set it up properly.
398   if (S.Flags == SectionFlags::Invalid || Override) {
399     S.Flags = Flags | SectionFlags::Named;
400     S.Name = Name;
401   }
402
403   return &S;
404 }
405
406 const Section*
407 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
408                                  bool Override) const {
409   Section& S = Sections[Directive];
410
411   // This is newly-created section, set it up properly.
412   if (S.Flags == SectionFlags::Invalid || Override) {
413     S.Flags = Flags & ~SectionFlags::Named;
414     S.Name = Directive;
415   }
416
417   return &S;
418 }
419
420 const std::string&
421 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
422   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
423
424   // We didn't print these flags yet, print and save them to map. This reduces
425   // amount of heap trashing due to std::string construction / concatenation.
426   if (I == FlagsStrings.end())
427     I = FlagsStrings.insert(std::make_pair(Flags,
428                                            printSectionFlags(Flags))).first;
429
430   return I->second;
431 }
432
433 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
434   unsigned Size = 0;
435   do {
436     Value >>= 7;
437     Size += sizeof(int8_t);
438   } while (Value);
439   return Size;
440 }
441
442 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
443   unsigned Size = 0;
444   int Sign = Value >> (8 * sizeof(Value) - 1);
445   bool IsMore;
446
447   do {
448     unsigned Byte = Value & 0x7f;
449     Value >>= 7;
450     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
451     Size += sizeof(int8_t);
452   } while (IsMore);
453   return Size;
454 }