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