1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File 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 implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
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"
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 /// Initialize - this method must be called before any actual lowering is
39 /// done. This specifies the current context for codegen, and gives the
40 /// lowering implementations a chance to set up their default sections.
41 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
42 const TargetMachine &TM) {
44 InitMCObjectFileInfo(TM.getTargetTriple(),
45 TM.getRelocationModel(), TM.getCodeModel(), *Ctx);
48 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
51 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
52 const Constant *C = GV->getInitializer();
54 // Must have zero initializer.
55 if (!C->isNullValue())
58 // Leave constant zeros in readonly constant sections, so they can be shared.
62 // If the global has an explicit section specified, don't put it in BSS.
63 if (!GV->getSection().empty())
66 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
70 // Otherwise, put it in BSS!
74 /// IsNullTerminatedString - Return true if the specified constant (which is
75 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
76 /// nul value and contains no other nuls in it. Note that this is more general
77 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
78 static bool IsNullTerminatedString(const Constant *C) {
79 // First check: is we have constant array terminated with zero
80 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
81 ArrayType *ATy = cast<ArrayType>(C->getType());
82 if (ATy->getNumElements() == 0) return false;
85 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
86 if (Null == 0 || !Null->isZero())
87 return false; // Not null terminated.
89 // Verify that the null doesn't occur anywhere else in the string.
90 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
91 // Reject constantexpr elements etc.
92 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
93 CVA->getOperand(i) == Null)
97 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
98 unsigned NumElts = CDS->getNumElements();
99 assert(NumElts != 0 && "Can't have an empty CDS");
101 if (CDS->getElementAsInteger(NumElts-1) != 0)
102 return false; // Not null terminated.
104 // Verify that the null doesn't occur anywhere else in the string.
105 for (unsigned i = 0; i != NumElts-1; ++i)
106 if (CDS->getElementAsInteger(i) == 0)
111 // Another possibility: [1 x i8] zeroinitializer
112 if (isa<ConstantAggregateZero>(C))
113 return cast<ArrayType>(C->getType())->getNumElements() == 1;
118 MCSymbol *TargetLoweringObjectFile::
119 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
120 MachineModuleInfo *MMI) const {
121 return Mang->getSymbol(GV);
124 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
125 const TargetMachine &TM,
126 const MCSymbol *Sym) const {
130 /// getKindForGlobal - This is a top-level target-independent classifier for
131 /// a global variable. Given an global variable and information from TM, it
132 /// classifies the global in a variety of ways that make various target
133 /// implementations simpler. The target implementation is free to ignore this
134 /// extra info of course.
135 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
136 const TargetMachine &TM){
137 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
138 "Can only be used for global definitions");
140 Reloc::Model ReloModel = TM.getRelocationModel();
142 // Early exit - functions should be always in text sections.
143 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
145 return SectionKind::getText();
147 // Handle thread-local data first.
148 if (GVar->isThreadLocal()) {
149 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
150 return SectionKind::getThreadBSS();
151 return SectionKind::getThreadData();
154 // Variables with common linkage always get classified as common.
155 if (GVar->hasCommonLinkage())
156 return SectionKind::getCommon();
158 // Variable can be easily put to BSS section.
159 if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
160 if (GVar->hasLocalLinkage())
161 return SectionKind::getBSSLocal();
162 else if (GVar->hasExternalLinkage())
163 return SectionKind::getBSSExtern();
164 return SectionKind::getBSS();
167 const Constant *C = GVar->getInitializer();
169 // If the global is marked constant, we can put it into a mergable section,
170 // a mergable string section, or general .data if it contains relocations.
171 if (GVar->isConstant()) {
172 // If the initializer for the global contains something that requires a
173 // relocation, then we may have to drop this into a wriable data section
174 // even though it is marked const.
175 switch (C->getRelocationInfo()) {
176 case Constant::NoRelocation:
177 // If the global is required to have a unique address, it can't be put
178 // into a mergable section: just drop it into the general read-only
180 if (!GVar->hasUnnamedAddr())
181 return SectionKind::getReadOnly();
183 // If initializer is a null-terminated string, put it in a "cstring"
184 // section of the right width.
185 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
186 if (IntegerType *ITy =
187 dyn_cast<IntegerType>(ATy->getElementType())) {
188 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
189 ITy->getBitWidth() == 32) &&
190 IsNullTerminatedString(C)) {
191 if (ITy->getBitWidth() == 8)
192 return SectionKind::getMergeable1ByteCString();
193 if (ITy->getBitWidth() == 16)
194 return SectionKind::getMergeable2ByteCString();
196 assert(ITy->getBitWidth() == 32 && "Unknown width");
197 return SectionKind::getMergeable4ByteCString();
202 // Otherwise, just drop it into a mergable constant section. If we have
203 // a section for this size, use it, otherwise use the arbitrary sized
205 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
206 case 4: return SectionKind::getMergeableConst4();
207 case 8: return SectionKind::getMergeableConst8();
208 case 16: return SectionKind::getMergeableConst16();
209 default: return SectionKind::getMergeableConst();
212 case Constant::LocalRelocation:
213 // In static relocation model, the linker will resolve all addresses, so
214 // the relocation entries will actually be constants by the time the app
215 // starts up. However, we can't put this into a mergable section, because
216 // the linker doesn't take relocations into consideration when it tries to
217 // merge entries in the section.
218 if (ReloModel == Reloc::Static)
219 return SectionKind::getReadOnly();
221 // Otherwise, the dynamic linker needs to fix it up, put it in the
222 // writable data.rel.local section.
223 return SectionKind::getReadOnlyWithRelLocal();
225 case Constant::GlobalRelocations:
226 // In static relocation model, the linker will resolve all addresses, so
227 // the relocation entries will actually be constants by the time the app
228 // starts up. However, we can't put this into a mergable section, because
229 // the linker doesn't take relocations into consideration when it tries to
230 // merge entries in the section.
231 if (ReloModel == Reloc::Static)
232 return SectionKind::getReadOnly();
234 // Otherwise, the dynamic linker needs to fix it up, put it in the
235 // writable data.rel section.
236 return SectionKind::getReadOnlyWithRel();
240 // Okay, this isn't a constant. If the initializer for the global is going
241 // to require a runtime relocation by the dynamic linker, put it into a more
242 // specific section to improve startup time of the app. This coalesces these
243 // globals together onto fewer pages, improving the locality of the dynamic
245 if (ReloModel == Reloc::Static)
246 return SectionKind::getDataNoRel();
248 switch (C->getRelocationInfo()) {
249 case Constant::NoRelocation:
250 return SectionKind::getDataNoRel();
251 case Constant::LocalRelocation:
252 return SectionKind::getDataRelLocal();
253 case Constant::GlobalRelocations:
254 return SectionKind::getDataRel();
256 llvm_unreachable("Invalid relocation");
259 /// SectionForGlobal - This method computes the appropriate section to emit
260 /// the specified global variable or function definition. This should not
261 /// be passed external (or available externally) globals.
262 const MCSection *TargetLoweringObjectFile::
263 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
264 const TargetMachine &TM) const {
265 // Select section name.
266 if (GV->hasSection())
267 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
270 // Use default section depending on the 'type' of global
271 return SelectSectionForGlobal(GV, Kind, Mang, TM);
275 // Lame default implementation. Calculate the section name for global.
277 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
280 const TargetMachine &TM) const{
281 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
284 return getTextSection();
286 if (Kind.isBSS() && BSSSection != 0)
289 if (Kind.isReadOnly() && ReadOnlySection != 0)
290 return ReadOnlySection;
292 return getDataSection();
295 /// getSectionForConstant - Given a mergable constant with the
296 /// specified size and relocation information, return a section that it
297 /// should be placed in.
299 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
300 if (Kind.isReadOnly() && ReadOnlySection != 0)
301 return ReadOnlySection;
306 /// getExprForDwarfGlobalReference - Return an MCExpr to use for a
307 /// reference to the specified global variable from exception
308 /// handling information.
309 const MCExpr *TargetLoweringObjectFile::
310 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
311 MachineModuleInfo *MMI, unsigned Encoding,
312 MCStreamer &Streamer) const {
313 const MCSymbol *Sym = Mang->getSymbol(GV);
314 return getExprForDwarfReference(Sym, Encoding, Streamer);
317 const MCExpr *TargetLoweringObjectFile::
318 getExprForDwarfReference(const MCSymbol *Sym, unsigned Encoding,
319 MCStreamer &Streamer) const {
320 const MCExpr *Res = MCSymbolRefExpr::Create(Sym, getContext());
322 switch (Encoding & 0x70) {
324 report_fatal_error("We do not support this DWARF encoding yet!");
325 case dwarf::DW_EH_PE_absptr:
326 // Do nothing special
328 case dwarf::DW_EH_PE_pcrel: {
329 // Emit a label to the streamer for the current position. This gives us
331 MCSymbol *PCSym = getContext().CreateTempSymbol();
332 Streamer.EmitLabel(PCSym);
333 const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
334 return MCBinaryExpr::CreateSub(Res, PC, getContext());