LLVM  3.7.0
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/IR/Mangler.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Dwarf.h"
34 using namespace llvm;
35 
36 //===----------------------------------------------------------------------===//
37 // Generic Code
38 //===----------------------------------------------------------------------===//
39 
40 /// Initialize - this method must be called before any actual lowering is
41 /// done. This specifies the current context for codegen, and gives the
42 /// lowering implementations a chance to set up their default sections.
44  const TargetMachine &TM) {
45  Ctx = &ctx;
46  DL = TM.getDataLayout();
48  TM.getCodeModel(), *Ctx);
49 }
50 
52 }
53 
54 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
55  const Constant *C = GV->getInitializer();
56 
57  // Must have zero initializer.
58  if (!C->isNullValue())
59  return false;
60 
61  // Leave constant zeros in readonly constant sections, so they can be shared.
62  if (GV->isConstant())
63  return false;
64 
65  // If the global has an explicit section specified, don't put it in BSS.
66  if (GV->hasSection())
67  return false;
68 
69  // If -nozero-initialized-in-bss is specified, don't ever use BSS.
70  if (NoZerosInBSS)
71  return false;
72 
73  // Otherwise, put it in BSS!
74  return true;
75 }
76 
77 /// IsNullTerminatedString - Return true if the specified constant (which is
78 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
79 /// nul value and contains no other nuls in it. Note that this is more general
80 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
81 static bool IsNullTerminatedString(const Constant *C) {
82  // First check: is we have constant array terminated with zero
83  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
84  unsigned NumElts = CDS->getNumElements();
85  assert(NumElts != 0 && "Can't have an empty CDS");
86 
87  if (CDS->getElementAsInteger(NumElts-1) != 0)
88  return false; // Not null terminated.
89 
90  // Verify that the null doesn't occur anywhere else in the string.
91  for (unsigned i = 0; i != NumElts-1; ++i)
92  if (CDS->getElementAsInteger(i) == 0)
93  return false;
94  return true;
95  }
96 
97  // Another possibility: [1 x i8] zeroinitializer
98  if (isa<ConstantAggregateZero>(C))
99  return cast<ArrayType>(C->getType())->getNumElements() == 1;
100 
101  return false;
102 }
103 
105  const GlobalValue *GV, StringRef Suffix, Mangler &Mang,
106  const TargetMachine &TM) const {
107  assert(!Suffix.empty());
108 
109  SmallString<60> NameStr;
110  NameStr += DL->getPrivateGlobalPrefix();
111  TM.getNameWithPrefix(NameStr, GV, Mang);
112  NameStr.append(Suffix.begin(), Suffix.end());
113  return Ctx->getOrCreateSymbol(NameStr);
114 }
115 
117  const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
118  MachineModuleInfo *MMI) const {
119  return TM.getSymbol(GV, Mang);
120 }
121 
123  const TargetMachine &TM,
124  const MCSymbol *Sym) const {
125 }
126 
127 
128 /// getKindForGlobal - This is a top-level target-independent classifier for
129 /// a global variable. Given an global variable and information from TM, it
130 /// classifies the global in a variety of ways that make various target
131 /// implementations simpler. The target implementation is free to ignore this
132 /// extra info of course.
134  const TargetMachine &TM){
135  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
136  "Can only be used for global definitions");
137 
138  Reloc::Model ReloModel = TM.getRelocationModel();
139 
140  // Early exit - functions should be always in text sections.
141  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
142  if (!GVar)
143  return SectionKind::getText();
144 
145  // Handle thread-local data first.
146  if (GVar->isThreadLocal()) {
147  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
148  return SectionKind::getThreadBSS();
150  }
151 
152  // Variables with common linkage always get classified as common.
153  if (GVar->hasCommonLinkage())
154  return SectionKind::getCommon();
155 
156  // Variable can be easily put to BSS section.
157  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
158  if (GVar->hasLocalLinkage())
159  return SectionKind::getBSSLocal();
160  else if (GVar->hasExternalLinkage())
161  return SectionKind::getBSSExtern();
162  return SectionKind::getBSS();
163  }
164 
165  const Constant *C = GVar->getInitializer();
166 
167  // If the global is marked constant, we can put it into a mergable section,
168  // a mergable string section, or general .data if it contains relocations.
169  if (GVar->isConstant()) {
170  // If the initializer for the global contains something that requires a
171  // relocation, then we may have to drop this into a writable data section
172  // even though it is marked const.
173  switch (C->getRelocationInfo()) {
175  // If the global is required to have a unique address, it can't be put
176  // into a mergable section: just drop it into the general read-only
177  // section instead.
178  if (!GVar->hasUnnamedAddr())
179  return SectionKind::getReadOnly();
180 
181  // If initializer is a null-terminated string, put it in a "cstring"
182  // section of the right width.
183  if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
184  if (IntegerType *ITy =
185  dyn_cast<IntegerType>(ATy->getElementType())) {
186  if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
187  ITy->getBitWidth() == 32) &&
189  if (ITy->getBitWidth() == 8)
191  if (ITy->getBitWidth() == 16)
193 
194  assert(ITy->getBitWidth() == 32 && "Unknown width");
196  }
197  }
198  }
199 
200  // Otherwise, just drop it into a mergable constant section. If we have
201  // a section for this size, use it, otherwise use the arbitrary sized
202  // mergable section.
203  switch (TM.getDataLayout()->getTypeAllocSize(C->getType())) {
204  case 4: return SectionKind::getMergeableConst4();
205  case 8: return SectionKind::getMergeableConst8();
206  case 16: return SectionKind::getMergeableConst16();
207  default:
208  return SectionKind::getReadOnly();
209  }
210 
212  // In static relocation model, the linker will resolve all addresses, so
213  // the relocation entries will actually be constants by the time the app
214  // starts up. However, we can't put this into a mergable section, because
215  // the linker doesn't take relocations into consideration when it tries to
216  // merge entries in the section.
217  if (ReloModel == Reloc::Static)
218  return SectionKind::getReadOnly();
219 
220  // Otherwise, the dynamic linker needs to fix it up, put it in the
221  // writable data.rel.local section.
223 
225  // In static relocation model, the linker will resolve all addresses, so
226  // the relocation entries will actually be constants by the time the app
227  // starts up. However, we can't put this into a mergable section, because
228  // the linker doesn't take relocations into consideration when it tries to
229  // merge entries in the section.
230  if (ReloModel == Reloc::Static)
231  return SectionKind::getReadOnly();
232 
233  // Otherwise, the dynamic linker needs to fix it up, put it in the
234  // writable data.rel section.
236  }
237  }
238 
239  // Okay, this isn't a constant. If the initializer for the global is going
240  // to require a runtime relocation by the dynamic linker, put it into a more
241  // specific section to improve startup time of the app. This coalesces these
242  // globals together onto fewer pages, improving the locality of the dynamic
243  // linker.
244  if (ReloModel == Reloc::Static)
245  return SectionKind::getDataNoRel();
246 
247  switch (C->getRelocationInfo()) {
249  return SectionKind::getDataNoRel();
253  return SectionKind::getDataRel();
254  }
255  llvm_unreachable("Invalid relocation");
256 }
257 
258 /// This method computes the appropriate section to emit the specified global
259 /// variable or function definition. This should not be passed external (or
260 /// available externally) globals.
261 MCSection *
263  SectionKind Kind, Mangler &Mang,
264  const TargetMachine &TM) const {
265  // Select section name.
266  if (GV->hasSection())
267  return getExplicitSectionGlobal(GV, Kind, Mang, TM);
268 
269 
270  // Use default section depending on the 'type' of global
271  return SelectSectionForGlobal(GV, Kind, Mang, TM);
272 }
273 
275  const Function &F, Mangler &Mang, const TargetMachine &TM) const {
276  return getSectionForConstant(SectionKind::getReadOnly(), /*C=*/nullptr);
277 }
278 
280  bool UsesLabelDifference, const Function &F) const {
281  // In PIC mode, we need to emit the jump table to the same section as the
282  // function body itself, otherwise the label differences won't make sense.
283  // FIXME: Need a better predicate for this: what about custom entries?
284  if (UsesLabelDifference)
285  return true;
286 
287  // We should also do if the section name is NULL or function is declared
288  // in discardable section
289  // FIXME: this isn't the right predicate, should be based on the MCSection
290  // for the function.
291  if (F.isWeakForLinker())
292  return true;
293 
294  return false;
295 }
296 
297 /// Given a mergable constant with the specified size and relocation
298 /// information, return a section that it should be placed in.
299 MCSection *
301  const Constant *C) const {
302  if (Kind.isReadOnly() && ReadOnlySection != nullptr)
303  return ReadOnlySection;
304 
305  return DataSection;
306 }
307 
308 /// getTTypeGlobalReference - Return an MCExpr to use for a
309 /// reference to the specified global variable from exception
310 /// handling information.
312  const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
313  const TargetMachine &TM, MachineModuleInfo *MMI,
314  MCStreamer &Streamer) const {
315  const MCSymbolRefExpr *Ref =
317 
318  return getTTypeReference(Ref, Encoding, Streamer);
319 }
320 
322 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
323  MCStreamer &Streamer) const {
324  switch (Encoding & 0x70) {
325  default:
326  report_fatal_error("We do not support this DWARF encoding yet!");
328  // Do nothing special
329  return Sym;
330  case dwarf::DW_EH_PE_pcrel: {
331  // Emit a label to the streamer for the current position. This gives us
332  // .-foo addressing.
333  MCSymbol *PCSym = getContext().createTempSymbol();
334  Streamer.EmitLabel(PCSym);
335  const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
336  return MCBinaryExpr::createSub(Sym, PC, getContext());
337  }
338  }
339 }
340 
342  // FIXME: It's not clear what, if any, default this should have - perhaps a
343  // null return could mean 'no location' & we should just do that here.
344  return MCSymbolRefExpr::create(Sym, *Ctx);
345 }
346 
348  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
349  bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
350  Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
351 }
static SectionKind getReadOnlyWithRelLocal()
Definition: SectionKind.h:231
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:48
static SectionKind getKindForGlobal(const GlobalValue *GV, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSection * getSectionForJumpTable(const Function &F, Mangler &Mang, const TargetMachine &TM) const
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:315
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
static SectionKind getDataRel()
Definition: SectionKind.h:227
static SectionKind getDataRelLocal()
Definition: SectionKind.h:228
const char * getPrivateGlobalPrefix() const
Definition: DataLayout.h:281
static SectionKind getMergeableConst8()
Definition: SectionKind.h:219
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:261
static SectionKind getMergeableConst16()
Definition: SectionKind.h:220
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const
static SectionKind getMergeable1ByteCString()
Definition: SectionKind.h:209
static SectionKind getCommon()
Definition: SectionKind.h:226
F(f)
virtual MCSection * SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler &Mang, const TargetMachine &TM) const =0
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static SectionKind getMergeableConst4()
Definition: SectionKind.h:218
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
const Triple & getTargetTriple() const
bool hasCommonLinkage() const
Definition: GlobalValue.h:282
static SectionKind getBSS()
Definition: SectionKind.h:223
static SectionKind getMergeable4ByteCString()
Definition: SectionKind.h:215
bool hasSection() const
Definition: GlobalValue.h:175
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:33
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:159
Context object for machine code objects.
Definition: MCContext.h:48
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:514
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:557
ArrayType - Class to represent array types.
Definition: DerivedTypes.h:336
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...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
static SectionKind getThreadData()
Definition: SectionKind.h:222
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, Mangler &Mang, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
MCSection * DataSection
Section directive for standard data.
iterator begin() const
Definition: StringRef.h:90
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:254
bool hasSection() const
Definition: GlobalObject.h:56
static SectionKind getBSSLocal()
Definition: SectionKind.h:224
Streaming machine code generation interface.
Definition: MCStreamer.h:157
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:222
CodeModel::Model getCodeModel() const
Returns the code model.
MCSection * SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler &Mang, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS)
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:28
Class to represent integer types.
Definition: DerivedTypes.h:37
virtual MCSection * getSectionForConstant(SectionKind Kind, const Constant *C) const
Given a constant with the SectionKind, return a section that it should be placed in.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:152
unsigned NoZerosInBSS
NoZerosInBSS - By default some codegens place zero-initialized data to .bss section.
MCSymbol * getSymbol(const GlobalValue *GV, Mangler &Mang) const
bool hasExternalLinkage() const
Definition: GlobalValue.h:260
PossibleRelocationsTy getRelocationInfo() const
getRelocationInfo - This method classifies the entry according to whether or not it may generate a re...
Definition: Constants.cpp:429
static SectionKind getThreadBSS()
Definition: SectionKind.h:221
virtual void EmitLabel(MCSymbol *Symbol)
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:203
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:388
const DataLayout * getDataLayout() const
Deprecated in 3.7, will be removed in 3.8.
static SectionKind getDataNoRel()
Definition: SectionKind.h:229
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:230
bool isNullValue() const
isNullValue - Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:75
virtual void emitPersonalityValue(MCStreamer &Streamer, const TargetMachine &TM, const MCSymbol *Sym) const
void InitMCObjectFileInfo(const Triple &TT, Reloc::Model RM, CodeModel::Model CM, MCContext &ctx)
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, Mangler &Mang, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
static bool IsNullTerminatedString(const Constant *C)
IsNullTerminatedString - Return true if the specified constant (which is known to have a type that is...
static SectionKind getMergeable2ByteCString()
Definition: SectionKind.h:212
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:111
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:108
static SectionKind getBSSExtern()
Definition: SectionKind.h:225
bool hasLocalLinkage() const
Definition: GlobalValue.h:280
const ARM::ArchExtKind Kind
bool hasUnnamedAddr() const
Definition: GlobalValue.h:130
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM, MachineModuleInfo *MMI) const
iterator end() const
Definition: StringRef.h:92
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
virtual MCSection * getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, Mangler &Mang, const TargetMachine &TM) const =0
Targets should implement this method to assign a section to globals with an explicit section specfied...
static SectionKind getReadOnly()
Definition: SectionKind.h:208
bool isReadOnly() const
Definition: SectionKind.h:139
MachineModuleInfo - This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110
static SectionKind getText()
Definition: SectionKind.h:207