9125546ff4033a69118b5e2146b7ab403d67ce32
[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/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Target/TargetAsmInfo.h"
21 #include "llvm/Target/TargetOptions.h"
22 #include "llvm/Support/Dwarf.h"
23 #include <cctype>
24 #include <cstring>
25
26 using namespace llvm;
27
28 TargetAsmInfo::TargetAsmInfo() :
29   TextSection("\t.text"),
30   TextSection_(0),
31   DataSection("\t.data"),
32   DataSection_(0),
33   BSSSection("\t.bss"),
34   BSSSection_(0),
35   ReadOnlySection(0),
36   ReadOnlySection_(0),
37   SmallDataSection(0),
38   SmallBSSSection(0),
39   SmallRODataSection(0),
40   TLSDataSection("\t.section .tdata,\"awT\",@progbits"),
41   TLSDataSection_(0),
42   TLSBSSSection("\t.section .tbss,\"awT\",@nobits"),
43   TLSBSSSection_(0),
44   ZeroFillDirective(0),
45   NonexecutableStackDirective(0),
46   NeedsSet(false),
47   MaxInstLength(4),
48   PCSymbol("$"),
49   SeparatorChar(';'),
50   CommentString("#"),
51   GlobalPrefix(""),
52   PrivateGlobalPrefix("."),
53   JumpTableSpecialLabelPrefix(0),
54   GlobalVarAddrPrefix(""),
55   GlobalVarAddrSuffix(""),
56   FunctionAddrPrefix(""),
57   FunctionAddrSuffix(""),
58   PersonalityPrefix(""),
59   PersonalitySuffix(""),
60   NeedsIndirectEncoding(false),
61   InlineAsmStart("#APP"),
62   InlineAsmEnd("#NO_APP"),
63   AssemblerDialect(0),
64   StringConstantPrefix(".str"),
65   ZeroDirective("\t.zero\t"),
66   ZeroDirectiveSuffix(0),
67   AsciiDirective("\t.ascii\t"),
68   AscizDirective("\t.asciz\t"),
69   Data8bitsDirective("\t.byte\t"),
70   Data16bitsDirective("\t.short\t"),
71   Data32bitsDirective("\t.long\t"),
72   Data64bitsDirective("\t.quad\t"),
73   AlignDirective("\t.align\t"),
74   AlignmentIsInBytes(true),
75   TextAlignFillValue(0),
76   SwitchToSectionDirective("\t.section\t"),
77   TextSectionStartSuffix(""),
78   DataSectionStartSuffix(""),
79   SectionEndDirectiveSuffix(0),
80   ConstantPoolSection("\t.section .rodata"),
81   JumpTableDataSection("\t.section .rodata"),
82   JumpTableDirective(0),
83   CStringSection(0),
84   CStringSection_(0),
85   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
86   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
87   FourByteConstantSection(0),
88   FourByteConstantSection_(0),
89   EightByteConstantSection(0),
90   EightByteConstantSection_(0),
91   SixteenByteConstantSection(0),
92   SixteenByteConstantSection_(0),
93   GlobalDirective("\t.globl\t"),
94   SetDirective(0),
95   LCOMMDirective(0),
96   COMMDirective("\t.comm\t"),
97   COMMDirectiveTakesAlignment(true),
98   HasDotTypeDotSizeDirective(true),
99   UsedDirective(0),
100   WeakRefDirective(0),
101   WeakDefDirective(0),
102   HiddenDirective("\t.hidden\t"),
103   ProtectedDirective("\t.protected\t"),
104   AbsoluteDebugSectionOffsets(false),
105   AbsoluteEHSectionOffsets(false),
106   HasLEB128(false),
107   HasDotLocAndDotFile(false),
108   SupportsDebugInformation(false),
109   SupportsExceptionHandling(false),
110   DwarfRequiresFrameSection(true),
111   GlobalEHDirective(0),
112   SupportsWeakOmittedEHFrame(true),
113   DwarfSectionOffsetDirective(0),
114   DwarfAbbrevSection(".debug_abbrev"),
115   DwarfInfoSection(".debug_info"),
116   DwarfLineSection(".debug_line"),
117   DwarfFrameSection(".debug_frame"),
118   DwarfPubNamesSection(".debug_pubnames"),
119   DwarfPubTypesSection(".debug_pubtypes"),
120   DwarfStrSection(".debug_str"),
121   DwarfLocSection(".debug_loc"),
122   DwarfARangesSection(".debug_aranges"),
123   DwarfRangesSection(".debug_ranges"),
124   DwarfMacInfoSection(".debug_macinfo"),
125   DwarfEHFrameSection(".eh_frame"),
126   DwarfExceptionSection(".gcc_except_table"),
127   AsmTransCBE(0) {
128   TextSection_ = getUnnamedSection(TextSection);
129   DataSection_ = getUnnamedSection(DataSection);
130 }
131
132 TargetAsmInfo::~TargetAsmInfo() {
133 }
134
135 /// Measure the specified inline asm to determine an approximation of its
136 /// length.
137 /// Comments (which run till the next SeparatorChar or newline) do not
138 /// count as an instruction.
139 /// Any other non-whitespace text is considered an instruction, with
140 /// multiple instructions separated by SeparatorChar or newlines.
141 /// Variable-length instructions are not handled here; this function
142 /// may be overloaded in the target code to do that.
143 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
144   // Count the number of instructions in the asm.
145   bool atInsnStart = true;
146   unsigned Length = 0;
147   for (; *Str; ++Str) {
148     if (*Str == '\n' || *Str == SeparatorChar)
149       atInsnStart = true;
150     if (atInsnStart && !isspace(*Str)) {
151       Length += MaxInstLength;
152       atInsnStart = false;
153     }
154     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
155       atInsnStart = false;
156   }
157
158   return Length;
159 }
160
161 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
162                                               bool Global) const {
163   return dwarf::DW_EH_PE_absptr;
164 }
165
166 static bool isSuitableForBSS(const GlobalVariable *GV) {
167   if (!GV->hasInitializer())
168     return true;
169
170   // Leave constant zeros in readonly constant sections, so they can be shared
171   Constant *C = GV->getInitializer();
172   return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
173 }
174
175 SectionKind::Kind
176 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
177   // Early exit - functions should be always in text sections.
178   if (isa<Function>(GV))
179     return SectionKind::Text;
180
181   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
182   bool isThreadLocal = GVar->isThreadLocal();
183   assert(GVar && "Invalid global value for section selection");
184
185   if (isSuitableForBSS(GVar)) {
186     // Variable can be easily put to BSS section.
187     return (isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS);
188   } else if (GVar->isConstant() && !isThreadLocal) {
189     // Now we know, that varible has initializer and it is constant. We need to
190     // check its initializer to decide, which section to output it into. Also
191     // note, there is no thread-local r/o section.
192     Constant *C = GVar->getInitializer();
193     if (C->ContainsRelocations())
194       return SectionKind::ROData;
195     else {
196       const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
197       // Check, if initializer is a null-terminated string
198       if (CVA && CVA->isCString())
199         return SectionKind::RODataMergeStr;
200       else
201         return SectionKind::RODataMergeConst;
202     }
203   }
204
205   // Variable is not constant or thread-local - emit to generic data section.
206   return (isThreadLocal ? SectionKind::ThreadData : SectionKind::Data);
207 }
208
209 unsigned
210 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
211                                      const char* Name) const {
212   unsigned Flags = SectionFlags::None;
213
214   // Decode flags from global itself.
215   if (GV) {
216     SectionKind::Kind Kind = SectionKindForGlobal(GV);
217     switch (Kind) {
218      case SectionKind::Text:
219       Flags |= SectionFlags::Code;
220       break;
221      case SectionKind::ThreadData:
222      case SectionKind::ThreadBSS:
223       Flags |= SectionFlags::TLS;
224       // FALLS THROUGH
225      case SectionKind::Data:
226      case SectionKind::BSS:
227       Flags |= SectionFlags::Writeable;
228       break;
229      case SectionKind::ROData:
230      case SectionKind::RODataMergeStr:
231      case SectionKind::RODataMergeConst:
232       // No additional flags here
233       break;
234      default:
235       assert(0 && "Unexpected section kind!");
236     }
237
238     if (GV->isWeakForLinker())
239       Flags |= SectionFlags::Linkonce;
240   }
241
242   // Add flags from sections, if any.
243   if (Name && *Name) {
244     Flags |= SectionFlags::Named;
245
246     // Some lame default implementation based on some magic section names.
247     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
248         strncmp(Name, ".llvm.linkonce.b.", 17) == 0)
249       Flags |= SectionFlags::BSS;
250     else if (strcmp(Name, ".tdata") == 0 ||
251              strncmp(Name, ".tdata.", 7) == 0 ||
252              strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
253              strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
254       Flags |= SectionFlags::TLS;
255     else if (strcmp(Name, ".tbss") == 0 ||
256              strncmp(Name, ".tbss.", 6) == 0 ||
257              strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
258              strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
259       Flags |= SectionFlags::BSS | SectionFlags::TLS;
260   }
261
262   return Flags;
263 }
264
265 std::string
266 TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
267   const Section* S;
268   // Select section name
269   if (GV->hasSection()) {
270     // Honour section already set, if any
271     unsigned Flags = SectionFlagsForGlobal(GV,
272                                            GV->getSection().c_str());
273     S = getNamedSection(GV->getSection().c_str(), Flags);
274   } else {
275     // Use default section depending on the 'type' of global
276     S = SelectSectionForGlobal(GV);
277   }
278
279   if (!S->isNamed())
280     return S->Name;
281
282   // If section is named we need to switch into it via special '.section'
283   // directive and also append funky flags. Otherwise - section name is just
284   // some magic assembler directive.
285   return getSwitchToSectionDirective() + S->Name + PrintSectionFlags(S->Flags);
286 }
287
288 // Lame default implementation. Calculate the section name for global.
289 const Section*
290 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
291   SectionKind::Kind Kind = SectionKindForGlobal(GV);
292
293   if (GV->isWeakForLinker()) {
294     std::string Name = UniqueSectionForGlobal(GV, Kind);
295     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
296     return getNamedSection(Name.c_str(), Flags);
297   } else {
298     if (Kind == SectionKind::Text)
299       return getTextSection_();
300     else if (Kind == SectionKind::BSS && getBSSSection_())
301       return getBSSSection_();
302     else if (getReadOnlySection_() &&
303              (Kind == SectionKind::ROData ||
304               Kind == SectionKind::RODataMergeConst ||
305               Kind == SectionKind::RODataMergeStr))
306       return getReadOnlySection_();
307   }
308
309   return getDataSection_();
310 }
311
312 std::string
313 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
314                                       SectionKind::Kind Kind) const {
315   switch (Kind) {
316    case SectionKind::Text:
317     return ".gnu.linkonce.t." + GV->getName();
318    case SectionKind::Data:
319     return ".gnu.linkonce.d." + GV->getName();
320    case SectionKind::BSS:
321     return ".gnu.linkonce.b." + GV->getName();
322    case SectionKind::ROData:
323    case SectionKind::RODataMergeConst:
324    case SectionKind::RODataMergeStr:
325     return ".gnu.linkonce.r." + GV->getName();
326    case SectionKind::ThreadData:
327     return ".gnu.linkonce.td." + GV->getName();
328    case SectionKind::ThreadBSS:
329     return ".gnu.linkonce.tb." + GV->getName();
330    default:
331     assert(0 && "Unknown section kind");
332   }
333 }
334
335 const Section*
336 TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags) const {
337   Section& S = Sections[Name];
338
339   // This is newly-created section, set it up properly.
340   if (S.Flags == SectionFlags::Invalid) {
341     S.Flags = Flags | SectionFlags::Named;
342     S.Name = Name;
343   }
344
345   return &S;
346 }
347
348 const Section*
349 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags) const {
350   Section& S = Sections[Directive];
351
352   // This is newly-created section, set it up properly.
353   if (S.Flags == SectionFlags::Invalid) {
354     S.Flags = Flags & ~SectionFlags::Named;
355     S.Name = Directive;
356   }
357
358   return &S;
359 }