LLVM  4.0.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  // `Initialize` can be called more than once.
47  if (Mang != nullptr) delete Mang;
48  Mang = new Mangler();
50  TM.getCodeModel(), *Ctx);
51 }
52 
54  delete Mang;
55 }
56 
57 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
58  const Constant *C = GV->getInitializer();
59 
60  // Must have zero initializer.
61  if (!C->isNullValue())
62  return false;
63 
64  // Leave constant zeros in readonly constant sections, so they can be shared.
65  if (GV->isConstant())
66  return false;
67 
68  // If the global has an explicit section specified, don't put it in BSS.
69  if (GV->hasSection())
70  return false;
71 
72  // If -nozero-initialized-in-bss is specified, don't ever use BSS.
73  if (NoZerosInBSS)
74  return false;
75 
76  // Otherwise, put it in BSS!
77  return true;
78 }
79 
80 /// IsNullTerminatedString - Return true if the specified constant (which is
81 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
82 /// nul value and contains no other nuls in it. Note that this is more general
83 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
84 static bool IsNullTerminatedString(const Constant *C) {
85  // First check: is we have constant array terminated with zero
86  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
87  unsigned NumElts = CDS->getNumElements();
88  assert(NumElts != 0 && "Can't have an empty CDS");
89 
90  if (CDS->getElementAsInteger(NumElts-1) != 0)
91  return false; // Not null terminated.
92 
93  // Verify that the null doesn't occur anywhere else in the string.
94  for (unsigned i = 0; i != NumElts-1; ++i)
95  if (CDS->getElementAsInteger(i) == 0)
96  return false;
97  return true;
98  }
99 
100  // Another possibility: [1 x i8] zeroinitializer
101  if (isa<ConstantAggregateZero>(C))
102  return cast<ArrayType>(C->getType())->getNumElements() == 1;
103 
104  return false;
105 }
106 
108  const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
109  assert(!Suffix.empty());
110 
111  SmallString<60> NameStr;
112  NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
113  TM.getNameWithPrefix(NameStr, GV, *Mang);
114  NameStr.append(Suffix.begin(), Suffix.end());
115  return Ctx->getOrCreateSymbol(NameStr);
116 }
117 
119  const GlobalValue *GV, const TargetMachine &TM,
120  MachineModuleInfo *MMI) const {
121  return TM.getSymbol(GV);
122 }
123 
125  const DataLayout &,
126  const MCSymbol *Sym) const {
127 }
128 
129 
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.
136  const TargetMachine &TM){
138  "Can only be used for global definitions");
139 
140  Reloc::Model ReloModel = TM.getRelocationModel();
141 
142  // Early exit - functions should be always in text sections.
143  const auto *GVar = dyn_cast<GlobalVariable>(GO);
144  if (!GVar)
145  return SectionKind::getText();
146 
147  // Handle thread-local data first.
148  if (GVar->isThreadLocal()) {
149  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
150  return SectionKind::getThreadBSS();
152  }
153 
154  // Variables with common linkage always get classified as common.
155  if (GVar->hasCommonLinkage())
156  return SectionKind::getCommon();
157 
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();
165  }
166 
167  const Constant *C = GVar->getInitializer();
168 
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 writable data section
174  // even though it is marked const.
175  if (!C->needsRelocation()) {
176  // If the global is required to have a unique address, it can't be put
177  // into a mergable section: just drop it into the general read-only
178  // section instead.
179  if (!GVar->hasGlobalUnnamedAddr())
180  return SectionKind::getReadOnly();
181 
182  // If initializer is a null-terminated string, put it in a "cstring"
183  // section of the right width.
184  if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
185  if (IntegerType *ITy =
186  dyn_cast<IntegerType>(ATy->getElementType())) {
187  if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
188  ITy->getBitWidth() == 32) &&
190  if (ITy->getBitWidth() == 8)
192  if (ITy->getBitWidth() == 16)
194 
195  assert(ITy->getBitWidth() == 32 && "Unknown width");
197  }
198  }
199  }
200 
201  // Otherwise, just drop it into a mergable constant section. If we have
202  // a section for this size, use it, otherwise use the arbitrary sized
203  // mergable section.
204  switch (
205  GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
206  case 4: return SectionKind::getMergeableConst4();
207  case 8: return SectionKind::getMergeableConst8();
208  case 16: return SectionKind::getMergeableConst16();
209  case 32: return SectionKind::getMergeableConst32();
210  default:
211  return SectionKind::getReadOnly();
212  }
213 
214  } else {
215  // In static, ROPI and RWPI relocation models, the linker will resolve
216  // all addresses, so the relocation entries will actually be constants by
217  // the time the app starts up. However, we can't put this into a
218  // mergable section, because the linker doesn't take relocations into
219  // consideration when it tries to merge entries in the section.
220  if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
221  ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
222  return SectionKind::getReadOnly();
223 
224  // Otherwise, the dynamic linker needs to fix it up, put it in the
225  // writable data.rel section.
227  }
228  }
229 
230  // Okay, this isn't a constant.
231  return SectionKind::getData();
232 }
233 
234 /// This method computes the appropriate section to emit the specified global
235 /// variable or function definition. This should not be passed external (or
236 /// available externally) globals.
238  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
239  // Select section name.
240  if (GO->hasSection())
241  return getExplicitSectionGlobal(GO, Kind, TM);
242 
243  // Use default section depending on the 'type' of global
244  return SelectSectionForGlobal(GO, Kind, TM);
245 }
246 
248  const Function &F, const TargetMachine &TM) const {
249  unsigned Align = 0;
251  SectionKind::getReadOnly(), /*C=*/nullptr,
252  Align);
253 }
254 
256  bool UsesLabelDifference, const Function &F) const {
257  // In PIC mode, we need to emit the jump table to the same section as the
258  // function body itself, otherwise the label differences won't make sense.
259  // FIXME: Need a better predicate for this: what about custom entries?
260  if (UsesLabelDifference)
261  return true;
262 
263  // We should also do if the section name is NULL or function is declared
264  // in discardable section
265  // FIXME: this isn't the right predicate, should be based on the MCSection
266  // for the function.
267  if (F.isWeakForLinker())
268  return true;
269 
270  return false;
271 }
272 
273 /// Given a mergable constant with the specified size and relocation
274 /// information, return a section that it should be placed in.
276  const DataLayout &DL, SectionKind Kind, const Constant *C,
277  unsigned &Align) const {
278  if (Kind.isReadOnly() && ReadOnlySection != nullptr)
279  return ReadOnlySection;
280 
281  return DataSection;
282 }
283 
284 /// getTTypeGlobalReference - Return an MCExpr to use for a
285 /// reference to the specified global variable from exception
286 /// handling information.
288  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
289  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
290  const MCSymbolRefExpr *Ref =
292 
293  return getTTypeReference(Ref, Encoding, Streamer);
294 }
295 
297 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
298  MCStreamer &Streamer) const {
299  switch (Encoding & 0x70) {
300  default:
301  report_fatal_error("We do not support this DWARF encoding yet!");
303  // Do nothing special
304  return Sym;
305  case dwarf::DW_EH_PE_pcrel: {
306  // Emit a label to the streamer for the current position. This gives us
307  // .-foo addressing.
308  MCSymbol *PCSym = getContext().createTempSymbol();
309  Streamer.EmitLabel(PCSym);
310  const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
311  return MCBinaryExpr::createSub(Sym, PC, getContext());
312  }
313  }
314 }
315 
317  // FIXME: It's not clear what, if any, default this should have - perhaps a
318  // null return could mean 'no location' & we should just do that here.
319  return MCSymbolRefExpr::create(Sym, *Ctx);
320 }
321 
323  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
324  const TargetMachine &TM) const {
325  Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
326 }
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:40
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
static SectionKind getData()
Definition: SectionKind.h:202
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:284
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:298
static SectionKind getMergeableConst32()
Definition: SectionKind.h:195
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
size_t i
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
MCSymbol * getSymbol(const GlobalValue *GV) const
static SectionKind getMergeableConst8()
Definition: SectionKind.h:193
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:402
static SectionKind getMergeableConst16()
Definition: SectionKind.h:194
static SectionKind getMergeable1ByteCString()
Definition: SectionKind.h:183
virtual void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym) const
static SectionKind getCommon()
Definition: SectionKind.h:201
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static SectionKind getMergeableConst4()
Definition: SectionKind.h:192
void InitMCObjectFileInfo(const Triple &TT, bool PIC, CodeModel::Model CM, MCContext &ctx)
const Triple & getTargetTriple() const
static SectionKind getBSS()
Definition: SectionKind.h:198
static SectionKind getMergeable4ByteCString()
Definition: SectionKind.h:189
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
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:34
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:161
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
Context object for machine code objects.
Definition: MCContext.h:51
#define F(x, y, z)
Definition: MD5.cpp:51
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:497
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:564
Class to represent array types.
Definition: DerivedTypes.h:345
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:26
static SectionKind getThreadData()
Definition: SectionKind.h:197
MCSection * DataSection
Section directive for standard data.
iterator begin() const
Definition: StringRef.h:103
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:349
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:73
static SectionKind getBSSLocal()
Definition: SectionKind.h:199
Streaming machine code generation interface.
Definition: MCStreamer.h:161
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:218
CodeModel::Model getCodeModel() const
Returns the code model.
This is an important base class in LLVM.
Definition: Constant.h:42
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const
Given a constant with the SectionKind, return a section that it should be placed in.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS)
bool isPositionIndependent() const
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
Class to represent integer types.
Definition: DerivedTypes.h:39
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry...
Definition: Constants.cpp:415
unsigned NoZerosInBSS
NoZerosInBSS - By default some codegens place zero-initialized data to .bss section.
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, 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 SectionKind getThreadBSS()
Definition: SectionKind.h:196
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
virtual void EmitLabel(MCSymbol *Symbol)
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:293
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:203
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:130
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:186
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:114
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:188
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
LLVM_NODISCARD 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:287
static SectionKind getBSSExtern()
Definition: SectionKind.h:200
virtual MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
Targets should implement this method to assign a section to globals with an explicit section specfied...
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const
const unsigned Kind
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
virtual MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
iterator end() const
Definition: StringRef.h:105
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
static SectionKind getReadOnly()
Definition: SectionKind.h:182
bool isReadOnly() const
Definition: SectionKind.h:123
This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
static SectionKind getText()
Definition: SectionKind.h:180
char * PC