ab4db2af3ee71b25d897f479815cf11e7b0b0d52
[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(0),
30   DataSection(0),
31   BSSSection("\t.bss"),
32   BSSSection_(0),
33   ReadOnlySection(0),
34   ReadOnlySection_(0),
35   SmallDataSection(0),
36   SmallBSSSection(0),
37   SmallRODataSection(0),
38   TLSDataSection(0),
39   TLSBSSSection(0),
40   ZeroFillDirective(0),
41   NonexecutableStackDirective(0),
42   NeedsSet(false),
43   MaxInstLength(4),
44   PCSymbol("$"),
45   SeparatorChar(';'),
46   CommentString("#"),
47   GlobalPrefix(""),
48   PrivateGlobalPrefix("."),
49   LessPrivateGlobalPrefix(""),
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   StringConstantPrefix(".str"),
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   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
83   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
84   GlobalDirective("\t.globl\t"),
85   SetDirective(0),
86   LCOMMDirective(0),
87   COMMDirective("\t.comm\t"),
88   COMMDirectiveTakesAlignment(true),
89   HasDotTypeDotSizeDirective(true),
90   UsedDirective(0),
91   WeakRefDirective(0),
92   WeakDefDirective(0),
93   HiddenDirective("\t.hidden\t"),
94   ProtectedDirective("\t.protected\t"),
95   AbsoluteDebugSectionOffsets(false),
96   AbsoluteEHSectionOffsets(false),
97   HasLEB128(false),
98   HasDotLocAndDotFile(false),
99   SupportsDebugInformation(false),
100   SupportsExceptionHandling(false),
101   DwarfRequiresFrameSection(true),
102   GlobalEHDirective(0),
103   SupportsWeakOmittedEHFrame(true),
104   DwarfSectionOffsetDirective(0),
105   DwarfAbbrevSection(".debug_abbrev"),
106   DwarfInfoSection(".debug_info"),
107   DwarfLineSection(".debug_line"),
108   DwarfFrameSection(".debug_frame"),
109   DwarfPubNamesSection(".debug_pubnames"),
110   DwarfPubTypesSection(".debug_pubtypes"),
111   DwarfStrSection(".debug_str"),
112   DwarfLocSection(".debug_loc"),
113   DwarfARangesSection(".debug_aranges"),
114   DwarfRangesSection(".debug_ranges"),
115   DwarfMacInfoSection(".debug_macinfo"),
116   DwarfEHFrameSection(".eh_frame"),
117   DwarfExceptionSection(".gcc_except_table"),
118   AsmTransCBE(0) {
119   TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
120   DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
121 }
122
123 TargetAsmInfo::~TargetAsmInfo() {
124 }
125
126 /// Measure the specified inline asm to determine an approximation of its
127 /// length.
128 /// Comments (which run till the next SeparatorChar or newline) do not
129 /// count as an instruction.
130 /// Any other non-whitespace text is considered an instruction, with
131 /// multiple instructions separated by SeparatorChar or newlines.
132 /// Variable-length instructions are not handled here; this function
133 /// may be overloaded in the target code to do that.
134 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
135   // Count the number of instructions in the asm.
136   bool atInsnStart = true;
137   unsigned Length = 0;
138   for (; *Str; ++Str) {
139     if (*Str == '\n' || *Str == SeparatorChar)
140       atInsnStart = true;
141     if (atInsnStart && !isspace(*Str)) {
142       Length += MaxInstLength;
143       atInsnStart = false;
144     }
145     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
146       atInsnStart = false;
147   }
148
149   return Length;
150 }
151
152 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
153                                               bool Global) const {
154   return dwarf::DW_EH_PE_absptr;
155 }
156
157 static bool isSuitableForBSS(const GlobalVariable *GV) {
158   if (!GV->hasInitializer())
159     return true;
160
161   // Leave constant zeros in readonly constant sections, so they can be shared
162   Constant *C = GV->getInitializer();
163   return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
164 }
165
166 SectionKind::Kind
167 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
168   // Early exit - functions should be always in text sections.
169   if (isa<Function>(GV))
170     return SectionKind::Text;
171
172   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
173   bool isThreadLocal = GVar->isThreadLocal();
174   assert(GVar && "Invalid global value for section selection");
175
176   if (isSuitableForBSS(GVar)) {
177     // Variable can be easily put to BSS section.
178     return (isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS);
179   } else if (GVar->isConstant() && !isThreadLocal) {
180     // Now we know, that varible has initializer and it is constant. We need to
181     // check its initializer to decide, which section to output it into. Also
182     // note, there is no thread-local r/o section.
183     Constant *C = GVar->getInitializer();
184     if (C->ContainsRelocations())
185       return SectionKind::ROData;
186     else {
187       const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
188       // Check, if initializer is a null-terminated string
189       if (CVA && CVA->isCString())
190         return SectionKind::RODataMergeStr;
191       else
192         return SectionKind::RODataMergeConst;
193     }
194   }
195
196   // Variable is not constant or thread-local - emit to generic data section.
197   return (isThreadLocal ? SectionKind::ThreadData : SectionKind::Data);
198 }
199
200 unsigned
201 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
202                                      const char* Name) const {
203   unsigned Flags = SectionFlags::None;
204
205   // Decode flags from global itself.
206   if (GV) {
207     SectionKind::Kind Kind = SectionKindForGlobal(GV);
208     switch (Kind) {
209      case SectionKind::Text:
210       Flags |= SectionFlags::Code;
211       break;
212      case SectionKind::ThreadData:
213      case SectionKind::ThreadBSS:
214       Flags |= SectionFlags::TLS;
215       // FALLS THROUGH
216      case SectionKind::Data:
217      case SectionKind::BSS:
218       Flags |= SectionFlags::Writeable;
219       break;
220      case SectionKind::ROData:
221      case SectionKind::RODataMergeStr:
222      case SectionKind::RODataMergeConst:
223       // No additional flags here
224       break;
225      case SectionKind::SmallData:
226      case SectionKind::SmallBSS:
227       Flags |= SectionFlags::Writeable;
228       // FALLS THROUGH
229      case SectionKind::SmallROData:
230       Flags |= SectionFlags::Small;
231       break;
232      default:
233       assert(0 && "Unexpected section kind!");
234     }
235
236     if (GV->isWeakForLinker())
237       Flags |= SectionFlags::Linkonce;
238   }
239
240   // Add flags from sections, if any.
241   if (Name && *Name) {
242     Flags |= SectionFlags::Named;
243
244     // Some lame default implementation based on some magic section names.
245     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
246         strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
247         strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
248         strncmp(Name, ".llvm.linkonce.sb.", 18) == 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 const Section*
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   return S;
280 }
281
282 // Lame default implementation. Calculate the section name for global.
283 const Section*
284 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
285   SectionKind::Kind Kind = SectionKindForGlobal(GV);
286
287   if (GV->isWeakForLinker()) {
288     std::string Name = UniqueSectionForGlobal(GV, Kind);
289     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
290     return getNamedSection(Name.c_str(), Flags);
291   } else {
292     if (Kind == SectionKind::Text)
293       return getTextSection();
294     else if (isBSS(Kind) && getBSSSection_())
295       return getBSSSection_();
296     else if (getReadOnlySection_() && SectionKind::isReadOnly(Kind))
297       return getReadOnlySection_();
298   }
299
300   return getDataSection();
301 }
302
303 // Lame default implementation. Calculate the section name for machine const.
304 const Section*
305 TargetAsmInfo::SelectSectionForMachineConst(const Type *Ty) const {
306   // FIXME: Support data.rel stuff someday
307   return getDataSection();
308 }
309
310 std::string
311 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
312                                       SectionKind::Kind Kind) const {
313   switch (Kind) {
314    case SectionKind::Text:
315     return ".gnu.linkonce.t." + GV->getName();
316    case SectionKind::Data:
317     return ".gnu.linkonce.d." + GV->getName();
318    case SectionKind::SmallData:
319     return ".gnu.linkonce.s." + GV->getName();
320    case SectionKind::BSS:
321     return ".gnu.linkonce.b." + GV->getName();
322    case SectionKind::SmallBSS:
323     return ".gnu.linkonce.sb." + GV->getName();
324    case SectionKind::ROData:
325    case SectionKind::RODataMergeConst:
326    case SectionKind::RODataMergeStr:
327     return ".gnu.linkonce.r." + GV->getName();
328    case SectionKind::SmallROData:
329     return ".gnu.linkonce.s2." + GV->getName();
330    case SectionKind::ThreadData:
331     return ".gnu.linkonce.td." + GV->getName();
332    case SectionKind::ThreadBSS:
333     return ".gnu.linkonce.tb." + GV->getName();
334    default:
335     assert(0 && "Unknown section kind");
336   }
337 }
338
339 const Section*
340 TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
341                                bool Override) const {
342   Section& S = Sections[Name];
343
344   // This is newly-created section, set it up properly.
345   if (S.Flags == SectionFlags::Invalid || Override) {
346     S.Flags = Flags | SectionFlags::Named;
347     S.Name = Name;
348   }
349
350   return &S;
351 }
352
353 const Section*
354 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
355                                  bool Override) const {
356   Section& S = Sections[Directive];
357
358   // This is newly-created section, set it up properly.
359   if (S.Flags == SectionFlags::Invalid || Override) {
360     S.Flags = Flags & ~SectionFlags::Named;
361     S.Name = Directive;
362   }
363
364   return &S;
365 }
366
367 const std::string&
368 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
369   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
370
371   // We didn't print these flags yet, print and save them to map. This reduces
372   // amount of heap trashing due to std::string construction / concatenation.
373   if (I == FlagsStrings.end())
374     I = FlagsStrings.insert(std::make_pair(Flags,
375                                            printSectionFlags(Flags))).first;
376
377   return I->second;
378 }
379
380 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
381   unsigned Size = 0;
382   do {
383     Value >>= 7;
384     Size += sizeof(int8_t);
385   } while (Value);
386   return Size;
387 }
388
389 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
390   unsigned Size = 0;
391   int Sign = Value >> (8 * sizeof(Value) - 1);
392   bool IsMore;
393
394   do {
395     unsigned Byte = Value & 0x7f;
396     Value >>= 7;
397     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
398     Size += sizeof(int8_t);
399   } while (IsMore);
400   return Size;
401 }