Generalize support for analyzing loops to include SLE/SGE loop exit conditions
[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 void TargetAsmInfo::fillDefaultValues() {
29   BSSSection = "\t.bss";
30   BSSSection_ = 0;
31   ReadOnlySection = 0;
32   SmallDataSection = 0;
33   SmallBSSSection = 0;
34   SmallRODataSection = 0;
35   TLSDataSection = 0;
36   TLSBSSSection = 0;
37   ZeroFillDirective = 0;
38   NonexecutableStackDirective = 0;
39   NeedsSet = false;
40   MaxInstLength = 4;
41   PCSymbol = "$";
42   SeparatorChar = ';';
43   CommentString = "#";
44   GlobalPrefix = "";
45   PrivateGlobalPrefix = ".";
46   LessPrivateGlobalPrefix = "";
47   JumpTableSpecialLabelPrefix = 0;
48   GlobalVarAddrPrefix = "";
49   GlobalVarAddrSuffix = "";
50   FunctionAddrPrefix = "";
51   FunctionAddrSuffix = "";
52   PersonalityPrefix = "";
53   PersonalitySuffix = "";
54   NeedsIndirectEncoding = false;
55   InlineAsmStart = "#APP";
56   InlineAsmEnd = "#NO_APP";
57   AssemblerDialect = 0;
58   StringConstantPrefix = ".str";
59   ZeroDirective = "\t.zero\t";
60   ZeroDirectiveSuffix = 0;
61   AsciiDirective = "\t.ascii\t";
62   AscizDirective = "\t.asciz\t";
63   Data8bitsDirective = "\t.byte\t";
64   Data16bitsDirective = "\t.short\t";
65   Data32bitsDirective = "\t.long\t";
66   Data64bitsDirective = "\t.quad\t";
67   AlignDirective = "\t.align\t";
68   AlignmentIsInBytes = true;
69   TextAlignFillValue = 0;
70   SwitchToSectionDirective = "\t.section\t";
71   TextSectionStartSuffix = "";
72   DataSectionStartSuffix = "";
73   SectionEndDirectiveSuffix = 0;
74   ConstantPoolSection = "\t.section .rodata";
75   JumpTableDataSection = "\t.section .rodata";
76   JumpTableDirective = 0;
77   CStringSection = 0;
78   CStringSection_ = 0;
79   // FIXME: Flags are ELFish - replace with normal section stuff.
80   StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
81   StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
82   GlobalDirective = "\t.globl\t";
83   SetDirective = 0;
84   LCOMMDirective = 0;
85   COMMDirective = "\t.comm\t";
86   COMMDirectiveTakesAlignment = true;
87   HasDotTypeDotSizeDirective = true;
88   HasSingleParameterDotFile = true;
89   UsedDirective = 0;
90   WeakRefDirective = 0;
91   WeakDefDirective = 0;
92   // FIXME: These are ELFish - move to ELFTAI.
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(const TargetMachine &tm) 
124   : TM(tm) {
125   fillDefaultValues();
126 }
127
128 TargetAsmInfo::~TargetAsmInfo() {
129 }
130
131 /// Measure the specified inline asm to determine an approximation of its
132 /// length.
133 /// Comments (which run till the next SeparatorChar or newline) do not
134 /// count as an instruction.
135 /// Any other non-whitespace text is considered an instruction, with
136 /// multiple instructions separated by SeparatorChar or newlines.
137 /// Variable-length instructions are not handled here; this function
138 /// may be overloaded in the target code to do that.
139 unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
140   // Count the number of instructions in the asm.
141   bool atInsnStart = true;
142   unsigned Length = 0;
143   for (; *Str; ++Str) {
144     if (*Str == '\n' || *Str == SeparatorChar)
145       atInsnStart = true;
146     if (atInsnStart && !isspace(*Str)) {
147       Length += MaxInstLength;
148       atInsnStart = false;
149     }
150     if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
151       atInsnStart = false;
152   }
153
154   return Length;
155 }
156
157 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
158                                               bool Global) const {
159   return dwarf::DW_EH_PE_absptr;
160 }
161
162 static bool isSuitableForBSS(const GlobalVariable *GV) {
163   if (!GV->hasInitializer())
164     return true;
165
166   // Leave constant zeros in readonly constant sections, so they can be shared
167   Constant *C = GV->getInitializer();
168   return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
169 }
170
171 SectionKind::Kind
172 TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
173   // Early exit - functions should be always in text sections.
174   if (isa<Function>(GV))
175     return SectionKind::Text;
176
177   const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
178   bool isThreadLocal = GVar->isThreadLocal();
179   assert(GVar && "Invalid global value for section selection");
180
181   if (isSuitableForBSS(GVar)) {
182     // Variable can be easily put to BSS section.
183     return (isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS);
184   } else if (GVar->isConstant() && !isThreadLocal) {
185     // Now we know, that varible has initializer and it is constant. We need to
186     // check its initializer to decide, which section to output it into. Also
187     // note, there is no thread-local r/o section.
188     Constant *C = GVar->getInitializer();
189     if (C->ContainsRelocations())
190       return SectionKind::ROData;
191     else {
192       const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
193       // Check, if initializer is a null-terminated string
194       if (CVA && CVA->isCString())
195         return SectionKind::RODataMergeStr;
196       else
197         return SectionKind::RODataMergeConst;
198     }
199   }
200
201   // Variable is not constant or thread-local - emit to generic data section.
202   return (isThreadLocal ? SectionKind::ThreadData : SectionKind::Data);
203 }
204
205 unsigned
206 TargetAsmInfo::SectionFlagsForGlobal(const GlobalValue *GV,
207                                      const char* Name) const {
208   unsigned Flags = SectionFlags::None;
209
210   // Decode flags from global itself.
211   if (GV) {
212     SectionKind::Kind Kind = SectionKindForGlobal(GV);
213     switch (Kind) {
214      case SectionKind::Text:
215       Flags |= SectionFlags::Code;
216       break;
217      case SectionKind::ThreadData:
218      case SectionKind::ThreadBSS:
219       Flags |= SectionFlags::TLS;
220       // FALLS THROUGH
221      case SectionKind::Data:
222      case SectionKind::BSS:
223       Flags |= SectionFlags::Writeable;
224       break;
225      case SectionKind::ROData:
226      case SectionKind::RODataMergeStr:
227      case SectionKind::RODataMergeConst:
228       // No additional flags here
229       break;
230      case SectionKind::SmallData:
231      case SectionKind::SmallBSS:
232       Flags |= SectionFlags::Writeable;
233       // FALLS THROUGH
234      case SectionKind::SmallROData:
235       Flags |= SectionFlags::Small;
236       break;
237      default:
238       assert(0 && "Unexpected section kind!");
239     }
240
241     if (GV->mayBeOverridden())
242       Flags |= SectionFlags::Linkonce;
243   }
244
245   // Add flags from sections, if any.
246   if (Name && *Name) {
247     Flags |= SectionFlags::Named;
248
249     // Some lame default implementation based on some magic section names.
250     if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
251         strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
252         strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
253         strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
254       Flags |= SectionFlags::BSS;
255     else if (strcmp(Name, ".tdata") == 0 ||
256              strncmp(Name, ".tdata.", 7) == 0 ||
257              strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
258              strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
259       Flags |= SectionFlags::TLS;
260     else if (strcmp(Name, ".tbss") == 0 ||
261              strncmp(Name, ".tbss.", 6) == 0 ||
262              strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
263              strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
264       Flags |= SectionFlags::BSS | SectionFlags::TLS;
265   }
266
267   return Flags;
268 }
269
270 const Section*
271 TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
272   const Section* S;
273   // Select section name
274   if (GV->hasSection()) {
275     // Honour section already set, if any
276     unsigned Flags = SectionFlagsForGlobal(GV,
277                                            GV->getSection().c_str());
278     S = getNamedSection(GV->getSection().c_str(), Flags);
279   } else {
280     // Use default section depending on the 'type' of global
281     S = SelectSectionForGlobal(GV);
282   }
283
284   return S;
285 }
286
287 // Lame default implementation. Calculate the section name for global.
288 const Section*
289 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
290   SectionKind::Kind Kind = SectionKindForGlobal(GV);
291
292   if (GV->mayBeOverridden()) {
293     std::string Name = UniqueSectionForGlobal(GV, Kind);
294     unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());
295     return getNamedSection(Name.c_str(), Flags);
296   } else {
297     if (Kind == SectionKind::Text)
298       return getTextSection();
299     else if (isBSS(Kind) && getBSSSection_())
300       return getBSSSection_();
301     else if (getReadOnlySection() && SectionKind::isReadOnly(Kind))
302       return getReadOnlySection();
303   }
304
305   return getDataSection();
306 }
307
308 // Lame default implementation. Calculate the section name for machine const.
309 const Section*
310 TargetAsmInfo::SelectSectionForMachineConst(const Type *Ty) const {
311   // FIXME: Support data.rel stuff someday
312   return getDataSection();
313 }
314
315 std::string
316 TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
317                                       SectionKind::Kind Kind) const {
318   switch (Kind) {
319    case SectionKind::Text:
320     return ".gnu.linkonce.t." + GV->getName();
321    case SectionKind::Data:
322     return ".gnu.linkonce.d." + GV->getName();
323    case SectionKind::SmallData:
324     return ".gnu.linkonce.s." + GV->getName();
325    case SectionKind::BSS:
326     return ".gnu.linkonce.b." + GV->getName();
327    case SectionKind::SmallBSS:
328     return ".gnu.linkonce.sb." + GV->getName();
329    case SectionKind::ROData:
330    case SectionKind::RODataMergeConst:
331    case SectionKind::RODataMergeStr:
332     return ".gnu.linkonce.r." + GV->getName();
333    case SectionKind::SmallROData:
334     return ".gnu.linkonce.s2." + GV->getName();
335    case SectionKind::ThreadData:
336     return ".gnu.linkonce.td." + GV->getName();
337    case SectionKind::ThreadBSS:
338     return ".gnu.linkonce.tb." + GV->getName();
339    default:
340     assert(0 && "Unknown section kind");
341   }
342 }
343
344 const Section*
345 TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
346                                bool Override) const {
347   Section& S = Sections[Name];
348
349   // This is newly-created section, set it up properly.
350   if (S.Flags == SectionFlags::Invalid || Override) {
351     S.Flags = Flags | SectionFlags::Named;
352     S.Name = Name;
353   }
354
355   return &S;
356 }
357
358 const Section*
359 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
360                                  bool Override) const {
361   Section& S = Sections[Directive];
362
363   // This is newly-created section, set it up properly.
364   if (S.Flags == SectionFlags::Invalid || Override) {
365     S.Flags = Flags & ~SectionFlags::Named;
366     S.Name = Directive;
367   }
368
369   return &S;
370 }
371
372 const std::string&
373 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
374   SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
375
376   // We didn't print these flags yet, print and save them to map. This reduces
377   // amount of heap trashing due to std::string construction / concatenation.
378   if (I == FlagsStrings.end())
379     I = FlagsStrings.insert(std::make_pair(Flags,
380                                            printSectionFlags(Flags))).first;
381
382   return I->second;
383 }
384
385 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
386   unsigned Size = 0;
387   do {
388     Value >>= 7;
389     Size += sizeof(int8_t);
390   } while (Value);
391   return Size;
392 }
393
394 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
395   unsigned Size = 0;
396   int Sign = Value >> (8 * sizeof(Value) - 1);
397   bool IsMore;
398
399   do {
400     unsigned Byte = Value & 0x7f;
401     Value >>= 7;
402     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
403     Size += sizeof(int8_t);
404   } while (IsMore);
405   return Size;
406 }