1 //===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines target asm properties related what form asm statements
13 //===----------------------------------------------------------------------===//
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"
30 TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) {
31 BSSSection = "\t.bss";
36 ZeroFillDirective = 0;
37 NonexecutableStackDirective = 0;
44 FirstOperandColumn = 0;
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";
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;
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";
87 COMMDirective = "\t.comm\t";
88 COMMDirectiveTakesAlignment = true;
89 HasDotTypeDotSizeDirective = true;
90 HasSingleParameterDotFile = true;
94 // FIXME: These are ELFish - move to ELFTAI.
95 HiddenDirective = "\t.hidden\t";
96 ProtectedDirective = "\t.protected\t";
97 AbsoluteDebugSectionOffsets = false;
98 AbsoluteEHSectionOffsets = 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";
124 TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
125 DataSection = getUnnamedSection("\t.data", SectionFlags::Writable);
128 TargetAsmInfo::~TargetAsmInfo() {
131 /// Measure the specified inline asm to determine an approximation of its
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;
143 for (; *Str; ++Str) {
144 if (*Str == '\n' || *Str == SeparatorChar)
146 if (atInsnStart && !isspace(*Str)) {
147 Length += MaxInstLength;
150 if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
157 unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
159 return dwarf::DW_EH_PE_absptr;
162 static bool isSuitableForBSS(const GlobalVariable *GV) {
163 Constant *C = GV->getInitializer();
165 // Must have zero initializer.
166 if (!C->isNullValue())
169 // Leave constant zeros in readonly constant sections, so they can be shared.
170 if (GV->isConstant())
173 // If the global has an explicit section specified, don't put it in BSS.
174 if (!GV->getSection().empty())
177 // Otherwise, put it in BSS unless the target really doesn't want us to.
178 return !NoZerosInBSS;
181 static bool isConstantString(const Constant *C) {
182 // First check: is we have constant array of i8 terminated with zero
183 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
184 // Check, if initializer is a null-terminated string
185 if (CVA && CVA->isCString())
188 // Another possibility: [1 x i8] zeroinitializer
189 if (isa<ConstantAggregateZero>(C))
190 if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
191 return (Ty->getElementType() == Type::Int8Ty &&
192 Ty->getNumElements() == 1);
197 static unsigned SectionFlagsForGlobal(const GlobalValue *GV,
198 SectionKind::Kind Kind) {
199 // Decode flags from global and section kind.
200 unsigned Flags = SectionFlags::None;
201 if (GV->isWeakForLinker())
202 Flags |= SectionFlags::Linkonce;
203 if (SectionKind::isBSS(Kind))
204 Flags |= SectionFlags::BSS;
205 if (SectionKind::isTLS(Kind))
206 Flags |= SectionFlags::TLS;
207 if (SectionKind::isCode(Kind))
208 Flags |= SectionFlags::Code;
209 if (SectionKind::isWritable(Kind))
210 Flags |= SectionFlags::Writable;
215 static SectionKind::Kind SectionKindForGlobal(const GlobalValue *GV,
216 Reloc::Model ReloModel) {
217 // Early exit - functions should be always in text sections.
218 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
220 return SectionKind::Text;
222 bool isThreadLocal = GVar->isThreadLocal();
224 // Variable can be easily put to BSS section.
225 if (isSuitableForBSS(GVar))
226 return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
228 // If this is thread-local, put it in the general "thread_data" section.
230 return SectionKind::ThreadData;
232 Constant *C = GVar->getInitializer();
234 // If the global is marked constant, we can put it into a mergable section,
235 // a mergable string section, or general .data if it contains relocations.
236 if (GVar->isConstant()) {
237 // If the initializer for the global contains something that requires a
238 // relocation, then we may have to drop this into a wriable data section
239 // even though it is marked const.
240 switch (C->getRelocationInfo()) {
241 default: llvm_unreachable("unknown relocation info kind");
242 case Constant::NoRelocation:
243 // If initializer is a null-terminated string, put it in a "cstring"
244 // section if the target has it.
245 if (isConstantString(C))
246 return SectionKind::RODataMergeStr;
248 // Otherwise, just drop it into a mergable constant section.
249 return SectionKind::RODataMergeConst;
251 case Constant::LocalRelocation:
252 // In static relocation model, the linker will resolve all addresses, so
253 // the relocation entries will actually be constants by the time the app
255 if (ReloModel == Reloc::Static)
256 return SectionKind::ROData;
258 // Otherwise, the dynamic linker needs to fix it up, put it in the
259 // writable data.rel.local section.
260 return SectionKind::DataRelROLocal;
262 case Constant::GlobalRelocations:
263 // In static relocation model, the linker will resolve all addresses, so
264 // the relocation entries will actually be constants by the time the app
266 if (ReloModel == Reloc::Static)
267 return SectionKind::ROData;
269 // Otherwise, the dynamic linker needs to fix it up, put it in the
270 // writable data.rel section.
271 return SectionKind::DataRelRO;
275 // Okay, this isn't a constant. If the initializer for the global is going
276 // to require a runtime relocation by the dynamic linker, put it into a more
277 // specific section to improve startup time of the app. This coalesces these
278 // globals together onto fewer pages, improving the locality of the dynamic
280 if (ReloModel == Reloc::Static)
281 return SectionKind::Data;
283 switch (C->getRelocationInfo()) {
284 default: llvm_unreachable("unknown relocation info kind");
285 case Constant::NoRelocation: return SectionKind::Data;
286 case Constant::LocalRelocation: return SectionKind::DataRelLocal;
287 case Constant::GlobalRelocations: return SectionKind::DataRel;
291 /// SectionForGlobal - This method computes the appropriate section to emit
292 /// the specified global variable or function definition. This should not
293 /// be passed external (or available externally) globals.
294 const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
295 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
296 "Can only be used for global definitions");
298 SectionKind::Kind Kind = SectionKindForGlobal(GV, TM.getRelocationModel());
300 // Select section name.
301 if (GV->hasSection()) {
302 // If the target has special section hacks for specifically named globals,
304 if (const Section *TS = getSpecialCasedSectionGlobals(GV, Kind))
307 // Honour section already set, if any.
308 unsigned Flags = SectionFlagsForGlobal(GV, Kind);
310 // This is an explicitly named section.
311 Flags |= SectionFlags::Named;
313 // If the target has magic semantics for certain section names, make sure to
314 // pick up the flags. This allows the user to write things with attribute
315 // section and still get the appropriate section flags printed.
316 Flags |= getFlagsForNamedSection(GV->getSection().c_str());
318 return getNamedSection(GV->getSection().c_str(), Flags);
321 // If this global is linkonce/weak and the target handles this by emitting it
322 // into a 'uniqued' section name, create and return the section now.
323 if (GV->isWeakForLinker()) {
324 if (const char *Prefix = getSectionPrefixForUniqueGlobal(Kind)) {
325 unsigned Flags = SectionFlagsForGlobal(GV, Kind);
327 // FIXME: Use mangler interface (PR4584).
328 std::string Name = Prefix+GV->getNameStr();
329 return getNamedSection(Name.c_str(), Flags);
333 // Use default section depending on the 'type' of global
334 return SelectSectionForGlobal(GV, Kind);
337 // Lame default implementation. Calculate the section name for global.
339 TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV,
340 SectionKind::Kind Kind) const {
341 if (SectionKind::isCode(Kind))
342 return getTextSection();
344 if (SectionKind::isBSS(SectionKind::BSS))
345 if (const Section *S = getBSSSection_())
348 if (SectionKind::isReadOnly(Kind))
349 if (const Section *S = getReadOnlySection())
352 return getDataSection();
355 /// getSectionForMergableConstant - Given a mergable constant with the
356 /// specified size and relocation information, return a section that it
357 /// should be placed in.
359 TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
360 unsigned ReloInfo) const {
361 // FIXME: Support data.rel stuff someday
362 // Lame default implementation. Calculate the section name for machine const.
363 return getDataSection();
367 const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
368 bool Override) const {
369 Section &S = Sections[Name];
371 // This is newly-created section, set it up properly.
372 if (S.Flags == SectionFlags::Invalid || Override) {
373 S.Flags = Flags | SectionFlags::Named;
381 TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
382 bool Override) const {
383 Section& S = Sections[Directive];
385 // This is newly-created section, set it up properly.
386 if (S.Flags == SectionFlags::Invalid || Override) {
387 S.Flags = Flags & ~SectionFlags::Named;
395 TargetAsmInfo::getSectionFlags(unsigned Flags) const {
396 SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);
398 // We didn't print these flags yet, print and save them to map. This reduces
399 // amount of heap trashing due to std::string construction / concatenation.
400 if (I == FlagsStrings.end())
401 I = FlagsStrings.insert(std::make_pair(Flags,
402 printSectionFlags(Flags))).first;
407 unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
411 Size += sizeof(int8_t);
416 unsigned TargetAsmInfo::getSLEB128Size(int Value) {
418 int Sign = Value >> (8 * sizeof(Value) - 1);
422 unsigned Byte = Value & 0x7f;
424 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
425 Size += sizeof(int8_t);