minor change to rafael's recent patches: if something is
[oota-llvm.git] / lib / Target / TargetLoweringObjectFile.cpp
1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File 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 implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Target/Mangler.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallString.h"
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 //                              Generic Code
36 //===----------------------------------------------------------------------===//
37
38 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
39   TextSection = 0;
40   DataSection = 0;
41   BSSSection = 0;
42   ReadOnlySection = 0;
43   StaticCtorSection = 0;
44   StaticDtorSection = 0;
45   LSDASection = 0;
46   EHFrameSection = 0;
47
48   CommDirectiveSupportsAlignment = true;
49   DwarfAbbrevSection = 0;
50   DwarfInfoSection = 0;
51   DwarfLineSection = 0;
52   DwarfFrameSection = 0;
53   DwarfPubNamesSection = 0;
54   DwarfPubTypesSection = 0;
55   DwarfDebugInlineSection = 0;
56   DwarfStrSection = 0;
57   DwarfLocSection = 0;
58   DwarfARangesSection = 0;
59   DwarfRangesSection = 0;
60   DwarfMacroInfoSection = 0;
61   
62   IsFunctionEHSymbolGlobal = false;
63   IsFunctionEHFrameSymbolPrivate = true;
64   SupportsWeakOmittedEHFrame = true;
65 }
66
67 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
68 }
69
70 static bool isSuitableForBSS(const GlobalVariable *GV) {
71   Constant *C = GV->getInitializer();
72
73   // Must have zero initializer.
74   if (!C->isNullValue())
75     return false;
76
77   // Leave constant zeros in readonly constant sections, so they can be shared.
78   if (GV->isConstant())
79     return false;
80
81   // If the global has an explicit section specified, don't put it in BSS.
82   if (!GV->getSection().empty())
83     return false;
84
85   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
86   if (NoZerosInBSS)
87     return false;
88
89   // Otherwise, put it in BSS!
90   return true;
91 }
92
93 /// IsNullTerminatedString - Return true if the specified constant (which is
94 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
95 /// nul value and contains no other nuls in it.
96 static bool IsNullTerminatedString(const Constant *C) {
97   const ArrayType *ATy = cast<ArrayType>(C->getType());
98
99   // First check: is we have constant array of i8 terminated with zero
100   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
101     if (ATy->getNumElements() == 0) return false;
102
103     ConstantInt *Null =
104       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
105     if (Null == 0 || !Null->isZero())
106       return false; // Not null terminated.
107
108     // Verify that the null doesn't occur anywhere else in the string.
109     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
110       // Reject constantexpr elements etc.
111       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
112           CVA->getOperand(i) == Null)
113         return false;
114     return true;
115   }
116
117   // Another possibility: [1 x i8] zeroinitializer
118   if (isa<ConstantAggregateZero>(C))
119     return ATy->getNumElements() == 1;
120
121   return false;
122 }
123
124 /// getKindForGlobal - This is a top-level target-independent classifier for
125 /// a global variable.  Given an global variable and information from TM, it
126 /// classifies the global in a variety of ways that make various target
127 /// implementations simpler.  The target implementation is free to ignore this
128 /// extra info of course.
129 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
130                                                        const TargetMachine &TM){
131   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
132          "Can only be used for global definitions");
133
134   Reloc::Model ReloModel = TM.getRelocationModel();
135
136   // Early exit - functions should be always in text sections.
137   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
138   if (GVar == 0)
139     return SectionKind::getText();
140
141   // Handle thread-local data first.
142   if (GVar->isThreadLocal()) {
143     if (isSuitableForBSS(GVar))
144       return SectionKind::getThreadBSS();
145     return SectionKind::getThreadData();
146   }
147
148   // Variables with common linkage always get classified as common.
149   if (GVar->hasCommonLinkage())
150     return SectionKind::getCommon();
151
152   // Variable can be easily put to BSS section.
153   if (isSuitableForBSS(GVar)) {
154     if (GVar->hasLocalLinkage())
155       return SectionKind::getBSSLocal();
156     else if (GVar->hasExternalLinkage())
157       return SectionKind::getBSSExtern();
158     return SectionKind::getBSS();
159   }
160
161   Constant *C = GVar->getInitializer();
162
163   // If the global is marked constant, we can put it into a mergable section,
164   // a mergable string section, or general .data if it contains relocations.
165   if (GVar->isConstant()) {
166     // If the initializer for the global contains something that requires a
167     // relocation, then we may have to drop this into a wriable data section
168     // even though it is marked const.
169     switch (C->getRelocationInfo()) {
170     default: assert(0 && "unknown relocation info kind");
171     case Constant::NoRelocation:
172       // If the global is required to have a unique address, it can't be put
173       // into a mergable section: just drop it into the general read-only
174       // section instead.
175       if (!GVar->hasUnnamedAddr())
176         return SectionKind::getReadOnly();
177         
178       // If initializer is a null-terminated string, put it in a "cstring"
179       // section of the right width.
180       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
181         if (const IntegerType *ITy =
182               dyn_cast<IntegerType>(ATy->getElementType())) {
183           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
184                ITy->getBitWidth() == 32) &&
185               IsNullTerminatedString(C)) {
186             if (ITy->getBitWidth() == 8)
187               return SectionKind::getMergeable1ByteCString();
188             if (ITy->getBitWidth() == 16)
189               return SectionKind::getMergeable2ByteCString();
190
191             assert(ITy->getBitWidth() == 32 && "Unknown width");
192             return SectionKind::getMergeable4ByteCString();
193           }
194         }
195       }
196
197       // Otherwise, just drop it into a mergable constant section.  If we have
198       // a section for this size, use it, otherwise use the arbitrary sized
199       // mergable section.
200       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
201       case 4:  return SectionKind::getMergeableConst4();
202       case 8:  return SectionKind::getMergeableConst8();
203       case 16: return SectionKind::getMergeableConst16();
204       default: return SectionKind::getMergeableConst();
205       }
206
207     case Constant::LocalRelocation:
208       // In static relocation model, the linker will resolve all addresses, so
209       // the relocation entries will actually be constants by the time the app
210       // starts up.  However, we can't put this into a mergable section, because
211       // the linker doesn't take relocations into consideration when it tries to
212       // merge entries in the section.
213       if (ReloModel == Reloc::Static)
214         return SectionKind::getReadOnly();
215
216       // Otherwise, the dynamic linker needs to fix it up, put it in the
217       // writable data.rel.local section.
218       return SectionKind::getReadOnlyWithRelLocal();
219
220     case Constant::GlobalRelocations:
221       // In static relocation model, the linker will resolve all addresses, so
222       // the relocation entries will actually be constants by the time the app
223       // starts up.  However, we can't put this into a mergable section, because
224       // the linker doesn't take relocations into consideration when it tries to
225       // merge entries in the section.
226       if (ReloModel == Reloc::Static)
227         return SectionKind::getReadOnly();
228
229       // Otherwise, the dynamic linker needs to fix it up, put it in the
230       // writable data.rel section.
231       return SectionKind::getReadOnlyWithRel();
232     }
233   }
234
235   // Okay, this isn't a constant.  If the initializer for the global is going
236   // to require a runtime relocation by the dynamic linker, put it into a more
237   // specific section to improve startup time of the app.  This coalesces these
238   // globals together onto fewer pages, improving the locality of the dynamic
239   // linker.
240   if (ReloModel == Reloc::Static)
241     return SectionKind::getDataNoRel();
242
243   switch (C->getRelocationInfo()) {
244   default: assert(0 && "unknown relocation info kind");
245   case Constant::NoRelocation:
246     return SectionKind::getDataNoRel();
247   case Constant::LocalRelocation:
248     return SectionKind::getDataRelLocal();
249   case Constant::GlobalRelocations:
250     return SectionKind::getDataRel();
251   }
252 }
253
254 /// SectionForGlobal - This method computes the appropriate section to emit
255 /// the specified global variable or function definition.  This should not
256 /// be passed external (or available externally) globals.
257 const MCSection *TargetLoweringObjectFile::
258 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
259                  const TargetMachine &TM) const {
260   // Select section name.
261   if (GV->hasSection())
262     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
263
264
265   // Use default section depending on the 'type' of global
266   return SelectSectionForGlobal(GV, Kind, Mang, TM);
267 }
268
269
270 // Lame default implementation. Calculate the section name for global.
271 const MCSection *
272 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
273                                                  SectionKind Kind,
274                                                  Mangler *Mang,
275                                                  const TargetMachine &TM) const{
276   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
277
278   if (Kind.isText())
279     return getTextSection();
280
281   if (Kind.isBSS() && BSSSection != 0)
282     return BSSSection;
283
284   if (Kind.isReadOnly() && ReadOnlySection != 0)
285     return ReadOnlySection;
286
287   return getDataSection();
288 }
289
290 /// getSectionForConstant - Given a mergable constant with the
291 /// specified size and relocation information, return a section that it
292 /// should be placed in.
293 const MCSection *
294 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
295   if (Kind.isReadOnly() && ReadOnlySection != 0)
296     return ReadOnlySection;
297
298   return DataSection;
299 }
300
301 /// getExprForDwarfGlobalReference - Return an MCExpr to use for a
302 /// reference to the specified global variable from exception
303 /// handling information.
304 const MCExpr *TargetLoweringObjectFile::
305 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
306                                MachineModuleInfo *MMI, unsigned Encoding,
307                                MCStreamer &Streamer) const {
308   const MCSymbol *Sym = Mang->getSymbol(GV);
309   return getExprForDwarfReference(Sym, Mang, MMI, Encoding, Streamer);
310 }
311
312 const MCExpr *TargetLoweringObjectFile::
313 getExprForDwarfReference(const MCSymbol *Sym, Mangler *Mang,
314                          MachineModuleInfo *MMI, unsigned Encoding,
315                          MCStreamer &Streamer) const {
316   const MCExpr *Res = MCSymbolRefExpr::Create(Sym, getContext());
317
318   switch (Encoding & 0xF0) {
319   default:
320     report_fatal_error("We do not support this DWARF encoding yet!");
321   case dwarf::DW_EH_PE_absptr:
322     // Do nothing special
323     return Res;
324   case dwarf::DW_EH_PE_pcrel: {
325     // Emit a label to the streamer for the current position.  This gives us
326     // .-foo addressing.
327     MCSymbol *PCSym = getContext().CreateTempSymbol();
328     Streamer.EmitLabel(PCSym);
329     const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
330     return MCBinaryExpr::CreateSub(Res, PC, getContext());
331   }
332   }
333 }
334
335 unsigned TargetLoweringObjectFile::getPersonalityEncoding() const {
336   return dwarf::DW_EH_PE_absptr;
337 }
338
339 unsigned TargetLoweringObjectFile::getLSDAEncoding() const {
340   return dwarf::DW_EH_PE_absptr;
341 }
342
343 unsigned TargetLoweringObjectFile::getFDEEncoding() const {
344   return dwarf::DW_EH_PE_absptr;
345 }
346
347 unsigned TargetLoweringObjectFile::getTTypeEncoding() const {
348   return dwarf::DW_EH_PE_absptr;
349 }
350