LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TargetLoweringObjectFile.cpp
Go to the documentation of this file.
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 
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Target/Mangler.h"
31 using namespace llvm;
32 
33 //===----------------------------------------------------------------------===//
34 // Generic Code
35 //===----------------------------------------------------------------------===//
36 
37 /// Initialize - this method must be called before any actual lowering is
38 /// done. This specifies the current context for codegen, and gives the
39 /// lowering implementations a chance to set up their default sections.
41  const TargetMachine &TM) {
42  Ctx = &ctx;
44  TM.getRelocationModel(), TM.getCodeModel(), *Ctx);
45 }
46 
48 }
49 
50 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
51  const Constant *C = GV->getInitializer();
52 
53  // Must have zero initializer.
54  if (!C->isNullValue())
55  return false;
56 
57  // Leave constant zeros in readonly constant sections, so they can be shared.
58  if (GV->isConstant())
59  return false;
60 
61  // If the global has an explicit section specified, don't put it in BSS.
62  if (!GV->getSection().empty())
63  return false;
64 
65  // If -nozero-initialized-in-bss is specified, don't ever use BSS.
66  if (NoZerosInBSS)
67  return false;
68 
69  // Otherwise, put it in BSS!
70  return true;
71 }
72 
73 /// IsNullTerminatedString - Return true if the specified constant (which is
74 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
75 /// nul value and contains no other nuls in it. Note that this is more general
76 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
77 static bool IsNullTerminatedString(const Constant *C) {
78  // First check: is we have constant array terminated with zero
79  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
80  unsigned NumElts = CDS->getNumElements();
81  assert(NumElts != 0 && "Can't have an empty CDS");
82 
83  if (CDS->getElementAsInteger(NumElts-1) != 0)
84  return false; // Not null terminated.
85 
86  // Verify that the null doesn't occur anywhere else in the string.
87  for (unsigned i = 0; i != NumElts-1; ++i)
88  if (CDS->getElementAsInteger(i) == 0)
89  return false;
90  return true;
91  }
92 
93  // Another possibility: [1 x i8] zeroinitializer
94  if (isa<ConstantAggregateZero>(C))
95  return cast<ArrayType>(C->getType())->getNumElements() == 1;
96 
97  return false;
98 }
99 
100 /// Return the MCSymbol for the specified global value. This
101 /// symbol is the main label that is the address of the global.
103  const GlobalValue *GV) const {
104  SmallString<60> NameStr;
105  M.getNameWithPrefix(NameStr, GV, false);
106  return Ctx->GetOrCreateSymbol(NameStr.str());
107 }
108 
109 
112  MachineModuleInfo *MMI) const {
113  return getSymbol(*Mang, GV);
114 }
115 
117  const TargetMachine &TM,
118  const MCSymbol *Sym) const {
119 }
120 
121 
122 /// getKindForGlobal - This is a top-level target-independent classifier for
123 /// a global variable. Given an global variable and information from TM, it
124 /// classifies the global in a variety of ways that make various target
125 /// implementations simpler. The target implementation is free to ignore this
126 /// extra info of course.
128  const TargetMachine &TM){
129  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
130  "Can only be used for global definitions");
131 
132  Reloc::Model ReloModel = TM.getRelocationModel();
133 
134  // Early exit - functions should be always in text sections.
135  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
136  if (GVar == 0)
137  return SectionKind::getText();
138 
139  // Handle thread-local data first.
140  if (GVar->isThreadLocal()) {
141  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
142  return SectionKind::getThreadBSS();
144  }
145 
146  // Variables with common linkage always get classified as common.
147  if (GVar->hasCommonLinkage())
148  return SectionKind::getCommon();
149 
150  // Variable can be easily put to BSS section.
151  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
152  if (GVar->hasLocalLinkage())
153  return SectionKind::getBSSLocal();
154  else if (GVar->hasExternalLinkage())
155  return SectionKind::getBSSExtern();
156  return SectionKind::getBSS();
157  }
158 
159  const Constant *C = GVar->getInitializer();
160 
161  // If the global is marked constant, we can put it into a mergable section,
162  // a mergable string section, or general .data if it contains relocations.
163  if (GVar->isConstant()) {
164  // If the initializer for the global contains something that requires a
165  // relocation, then we may have to drop this into a writable data section
166  // even though it is marked const.
167  switch (C->getRelocationInfo()) {
169  // If the global is required to have a unique address, it can't be put
170  // into a mergable section: just drop it into the general read-only
171  // section instead.
172  if (!GVar->hasUnnamedAddr())
173  return SectionKind::getReadOnly();
174 
175  // If initializer is a null-terminated string, put it in a "cstring"
176  // section of the right width.
177  if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
178  if (IntegerType *ITy =
179  dyn_cast<IntegerType>(ATy->getElementType())) {
180  if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
181  ITy->getBitWidth() == 32) &&
183  if (ITy->getBitWidth() == 8)
185  if (ITy->getBitWidth() == 16)
187 
188  assert(ITy->getBitWidth() == 32 && "Unknown width");
190  }
191  }
192  }
193 
194  // Otherwise, just drop it into a mergable constant section. If we have
195  // a section for this size, use it, otherwise use the arbitrary sized
196  // mergable section.
197  switch (TM.getDataLayout()->getTypeAllocSize(C->getType())) {
198  case 4: return SectionKind::getMergeableConst4();
199  case 8: return SectionKind::getMergeableConst8();
200  case 16: return SectionKind::getMergeableConst16();
201  default: return SectionKind::getMergeableConst();
202  }
203 
205  // In static relocation model, the linker will resolve all addresses, so
206  // the relocation entries will actually be constants by the time the app
207  // starts up. However, we can't put this into a mergable section, because
208  // the linker doesn't take relocations into consideration when it tries to
209  // merge entries in the section.
210  if (ReloModel == Reloc::Static)
211  return SectionKind::getReadOnly();
212 
213  // Otherwise, the dynamic linker needs to fix it up, put it in the
214  // writable data.rel.local section.
216 
218  // In static relocation model, the linker will resolve all addresses, so
219  // the relocation entries will actually be constants by the time the app
220  // starts up. However, we can't put this into a mergable section, because
221  // the linker doesn't take relocations into consideration when it tries to
222  // merge entries in the section.
223  if (ReloModel == Reloc::Static)
224  return SectionKind::getReadOnly();
225 
226  // Otherwise, the dynamic linker needs to fix it up, put it in the
227  // writable data.rel section.
229  }
230  }
231 
232  // Okay, this isn't a constant. If the initializer for the global is going
233  // to require a runtime relocation by the dynamic linker, put it into a more
234  // specific section to improve startup time of the app. This coalesces these
235  // globals together onto fewer pages, improving the locality of the dynamic
236  // linker.
237  if (ReloModel == Reloc::Static)
238  return SectionKind::getDataNoRel();
239 
240  switch (C->getRelocationInfo()) {
242  return SectionKind::getDataNoRel();
246  return SectionKind::getDataRel();
247  }
248  llvm_unreachable("Invalid relocation");
249 }
250 
251 /// SectionForGlobal - This method computes the appropriate section to emit
252 /// the specified global variable or function definition. This should not
253 /// be passed external (or available externally) globals.
256  const TargetMachine &TM) const {
257  // Select section name.
258  if (GV->hasSection())
259  return getExplicitSectionGlobal(GV, Kind, Mang, TM);
260 
261 
262  // Use default section depending on the 'type' of global
263  return SelectSectionForGlobal(GV, Kind, Mang, TM);
264 }
265 
266 
267 // Lame default implementation. Calculate the section name for global.
268 const MCSection *
271  Mangler *Mang,
272  const TargetMachine &TM) const{
273  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
274 
275  if (Kind.isText())
276  return getTextSection();
277 
278  if (Kind.isBSS() && BSSSection != 0)
279  return BSSSection;
280 
281  if (Kind.isReadOnly() && ReadOnlySection != 0)
282  return ReadOnlySection;
283 
284  return getDataSection();
285 }
286 
287 /// getSectionForConstant - Given a mergable constant with the
288 /// specified size and relocation information, return a section that it
289 /// should be placed in.
290 const MCSection *
292  if (Kind.isReadOnly() && ReadOnlySection != 0)
293  return ReadOnlySection;
294 
295  return DataSection;
296 }
297 
298 /// getTTypeGlobalReference - Return an MCExpr to use for a
299 /// reference to the specified global variable from exception
300 /// handling information.
303  MachineModuleInfo *MMI, unsigned Encoding,
304  MCStreamer &Streamer) const {
305  const MCSymbolRefExpr *Ref =
307 
308  return getTTypeReference(Ref, Encoding, Streamer);
309 }
310 
312 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
313  MCStreamer &Streamer) const {
314  switch (Encoding & 0x70) {
315  default:
316  report_fatal_error("We do not support this DWARF encoding yet!");
318  // Do nothing special
319  return Sym;
320  case dwarf::DW_EH_PE_pcrel: {
321  // Emit a label to the streamer for the current position. This gives us
322  // .-foo addressing.
323  MCSymbol *PCSym = getContext().CreateTempSymbol();
324  Streamer.EmitLabel(PCSym);
325  const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
326  return MCBinaryExpr::CreateSub(Sym, PC, getContext());
327  }
328  }
329 }
330 
332  // FIXME: It's not clear what, if any, default this should have - perhaps a
333  // null return could mean 'no location' & we should just do that here.
334  return MCSymbolRefExpr::Create(Sym, *Ctx);
335 }
static SectionKind getReadOnlyWithRelLocal()
Definition: SectionKind.h:233
static SectionKind getKindForGlobal(const GlobalValue *GV, const TargetMachine &TM)
Reloc::Model getRelocationModel() const
virtual const MCSection * SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
static SectionKind getDataRel()
Definition: SectionKind.h:229
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, bool isImplicitlyPrivate, bool UseGlobalPrefix=true)
Definition: Mangler.cpp:90
bool isBSS() const
Definition: SectionKind.h:176
static SectionKind getDataRelLocal()
Definition: SectionKind.h:230
virtual const MCSection * getSectionForConstant(SectionKind Kind) const
static SectionKind getMergeableConst8()
Definition: SectionKind.h:221
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:195
static SectionKind getMergeableConst16()
Definition: SectionKind.h:222
static SectionKind getMergeable1ByteCString()
Definition: SectionKind.h:210
static SectionKind getCommon()
Definition: SectionKind.h:228
const MCSection * getDataSection() const
const Constant * getInitializer() const
static SectionKind getMergeableConst4()
Definition: SectionKind.h:220
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
MCSymbol * GetOrCreateSymbol(StringRef Name)
Definition: MCContext.cpp:118
bool hasCommonLinkage() const
Definition: GlobalValue.h:215
static SectionKind getBSS()
Definition: SectionKind.h:225
static SectionKind getMergeable4ByteCString()
Definition: SectionKind.h:216
MCSymbol * CreateTempSymbol()
Definition: MCContext.cpp:165
bool hasSection() const
Definition: GlobalValue.h:95
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
#define llvm_unreachable(msg)
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
static const MCBinaryExpr * CreateSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
virtual const MCExpr * getDebugThreadLocalSymbol(const MCSymbol *Sym) const
Create a symbol reference to describe the given TLS variable when emitting the address in debug info...
const MCSection * getTextSection() const
static SectionKind getThreadData()
Definition: SectionKind.h:224
static const MCSymbolRefExpr * Create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:270
void InitMCObjectFileInfo(StringRef TT, Reloc::Model RM, CodeModel::Model CM, MCContext &ctx)
static SectionKind getBSSLocal()
Definition: SectionKind.h:226
const MCSection * SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
const MCSection * BSSSection
BSSSection - Section that is default initialized to zero.
CodeModel::Model getCodeModel() const
bool isText() const
Definition: SectionKind.h:138
LLVM Constant Representation.
Definition: Constant.h:41
virtual const MCSection * getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const =0
static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS)
Integer representation type.
Definition: DerivedTypes.h:37
const std::string & getSection() const
Definition: GlobalValue.h:96
bool isThreadLocal() const
Definition: SectionKind.h:165
bool hasExternalLinkage() const
Definition: GlobalValue.h:194
PossibleRelocationsTy getRelocationInfo() const
Definition: Constants.cpp:337
static SectionKind getThreadBSS()
Definition: SectionKind.h:223
virtual void EmitLabel(MCSymbol *Symbol)
Definition: MCStreamer.cpp:212
uint64_t getTypeAllocSize(Type *Ty) const
Definition: DataLayout.h:326
static SectionKind getDataNoRel()
Definition: SectionKind.h:231
Type * getType() const
Definition: Value.h:111
static SectionKind getMergeableConst()
Definition: SectionKind.h:219
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:232
const MCSection * ReadOnlySection
bool isNullValue() const
Definition: Constants.cpp:75
virtual void emitPersonalityValue(MCStreamer &Streamer, const TargetMachine &TM, const MCSymbol *Sym) const
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:270
bool isConstant() const
const StringRef getTargetTriple() const
static bool IsNullTerminatedString(const Constant *C)
static SectionKind getMergeable2ByteCString()
Definition: SectionKind.h:213
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI, unsigned Encoding, MCStreamer &Streamer) const
bool isDeclaration() const
Definition: Globals.cpp:66
virtual const DataLayout * getDataLayout() const
static SectionKind getBSSExtern()
Definition: SectionKind.h:227
const MCSection * DataSection
bool hasLocalLinkage() const
Definition: GlobalValue.h:211
bool hasUnnamedAddr() const
Definition: GlobalValue.h:84
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI) const
static SectionKind getReadOnly()
Definition: SectionKind.h:209
bool isReadOnly() const
Definition: SectionKind.h:140
MCSymbol * getSymbol(Mangler &M, const GlobalValue *GV) const
static SectionKind getText()
Definition: SectionKind.h:208