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