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/BinaryFormat/Dwarf.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Mangler.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/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
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.
40 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
41 const TargetMachine &TM) {
43 // `Initialize` can be called more than once.
46 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx,
47 TM.getCodeModel() == CodeModel::Large);
50 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
54 static bool isNullOrUndef(const Constant *C) {
55 // Check that the constant isn't all zeros or undefs.
56 if (C->isNullValue() || isa<UndefValue>(C))
58 if (!isa<ConstantAggregate>(C))
60 for (auto Operand : C->operand_values()) {
61 if (!isNullOrUndef(cast<Constant>(Operand)))
67 static bool isSuitableForBSS(const GlobalVariable *GV) {
68 const Constant *C = GV->getInitializer();
70 // Must have zero initializer.
71 if (!isNullOrUndef(C))
74 // Leave constant zeros in readonly constant sections, so they can be shared.
78 // If the global has an explicit section specified, don't put it in BSS.
82 // Otherwise, put it in BSS!
86 /// IsNullTerminatedString - Return true if the specified constant (which is
87 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
88 /// nul value and contains no other nuls in it. Note that this is more general
89 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
90 static bool IsNullTerminatedString(const Constant *C) {
91 // First check: is we have constant array terminated with zero
92 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
93 unsigned NumElts = CDS->getNumElements();
94 assert(NumElts != 0 && "Can't have an empty CDS");
96 if (CDS->getElementAsInteger(NumElts-1) != 0)
97 return false; // Not null terminated.
99 // Verify that the null doesn't occur anywhere else in the string.
100 for (unsigned i = 0; i != NumElts-1; ++i)
101 if (CDS->getElementAsInteger(i) == 0)
106 // Another possibility: [1 x i8] zeroinitializer
107 if (isa<ConstantAggregateZero>(C))
108 return cast<ArrayType>(C->getType())->getNumElements() == 1;
113 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
114 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
115 assert(!Suffix.empty());
117 SmallString<60> NameStr;
118 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
119 TM.getNameWithPrefix(NameStr, GV, *Mang);
120 NameStr.append(Suffix.begin(), Suffix.end());
121 return Ctx->getOrCreateSymbol(NameStr);
124 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
125 const GlobalValue *GV, const TargetMachine &TM,
126 MachineModuleInfo *MMI) const {
127 return TM.getSymbol(GV);
130 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
132 const MCSymbol *Sym) const {
136 /// getKindForGlobal - This is a top-level target-independent classifier for
137 /// a global object. Given a global variable and information from the TM, this
138 /// function classifies the global in a target independent manner. This function
139 /// may be overridden by the target implementation.
140 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
141 const TargetMachine &TM){
142 assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
143 "Can only be used for global definitions");
145 // Functions are classified as text sections.
146 if (isa<Function>(GO))
147 return SectionKind::getText();
149 // Global variables require more detailed analysis.
150 const auto *GVar = cast<GlobalVariable>(GO);
152 // Handle thread-local data first.
153 if (GVar->isThreadLocal()) {
154 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
155 return SectionKind::getThreadBSS();
156 return SectionKind::getThreadData();
159 // Variables with common linkage always get classified as common.
160 if (GVar->hasCommonLinkage())
161 return SectionKind::getCommon();
163 // Most non-mergeable zero data can be put in the BSS section unless otherwise
165 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
166 if (GVar->hasLocalLinkage())
167 return SectionKind::getBSSLocal();
168 else if (GVar->hasExternalLinkage())
169 return SectionKind::getBSSExtern();
170 return SectionKind::getBSS();
173 // If the global is marked constant, we can put it into a mergable section,
174 // a mergable string section, or general .data if it contains relocations.
175 if (GVar->isConstant()) {
176 // If the initializer for the global contains something that requires a
177 // relocation, then we may have to drop this into a writable data section
178 // even though it is marked const.
179 const Constant *C = GVar->getInitializer();
180 if (!C->needsRelocation()) {
181 // If the global is required to have a unique address, it can't be put
182 // into a mergable section: just drop it into the general read-only
184 if (!GVar->hasGlobalUnnamedAddr())
185 return SectionKind::getReadOnly();
187 // If initializer is a null-terminated string, put it in a "cstring"
188 // section of the right width.
189 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
190 if (IntegerType *ITy =
191 dyn_cast<IntegerType>(ATy->getElementType())) {
192 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
193 ITy->getBitWidth() == 32) &&
194 IsNullTerminatedString(C)) {
195 if (ITy->getBitWidth() == 8)
196 return SectionKind::getMergeable1ByteCString();
197 if (ITy->getBitWidth() == 16)
198 return SectionKind::getMergeable2ByteCString();
200 assert(ITy->getBitWidth() == 32 && "Unknown width");
201 return SectionKind::getMergeable4ByteCString();
206 // Otherwise, just drop it into a mergable constant section. If we have
207 // a section for this size, use it, otherwise use the arbitrary sized
210 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
211 case 4: return SectionKind::getMergeableConst4();
212 case 8: return SectionKind::getMergeableConst8();
213 case 16: return SectionKind::getMergeableConst16();
214 case 32: return SectionKind::getMergeableConst32();
216 return SectionKind::getReadOnly();
220 // In static, ROPI and RWPI relocation models, the linker will resolve
221 // all addresses, so the relocation entries will actually be constants by
222 // the time the app starts up. However, we can't put this into a
223 // mergable section, because the linker doesn't take relocations into
224 // consideration when it tries to merge entries in the section.
225 Reloc::Model ReloModel = TM.getRelocationModel();
226 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
227 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
228 return SectionKind::getReadOnly();
230 // Otherwise, the dynamic linker needs to fix it up, put it in the
231 // writable data.rel section.
232 return SectionKind::getReadOnlyWithRel();
236 // Okay, this isn't a constant.
237 return SectionKind::getData();
240 /// This method computes the appropriate section to emit the specified global
241 /// variable or function definition. This should not be passed external (or
242 /// available externally) globals.
243 MCSection *TargetLoweringObjectFile::SectionForGlobal(
244 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
245 // Select section name.
246 if (GO->hasSection())
247 return getExplicitSectionGlobal(GO, Kind, TM);
249 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
250 auto Attrs = GVar->getAttributes();
251 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
252 (Attrs.hasAttribute("data-section") && Kind.isData()) ||
253 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) {
254 return getExplicitSectionGlobal(GO, Kind, TM);
258 if (auto *F = dyn_cast<Function>(GO)) {
259 if (F->hasFnAttribute("implicit-section-name"))
260 return getExplicitSectionGlobal(GO, Kind, TM);
263 // Use default section depending on the 'type' of global
264 return SelectSectionForGlobal(GO, Kind, TM);
267 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
268 const Function &F, const TargetMachine &TM) const {
270 return getSectionForConstant(F.getParent()->getDataLayout(),
271 SectionKind::getReadOnly(), /*C=*/nullptr,
275 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
276 bool UsesLabelDifference, const Function &F) const {
277 // In PIC mode, we need to emit the jump table to the same section as the
278 // function body itself, otherwise the label differences won't make sense.
279 // FIXME: Need a better predicate for this: what about custom entries?
280 if (UsesLabelDifference)
283 // We should also do if the section name is NULL or function is declared
284 // in discardable section
285 // FIXME: this isn't the right predicate, should be based on the MCSection
287 return F.isWeakForLinker();
290 /// Given a mergable constant with the specified size and relocation
291 /// information, return a section that it should be placed in.
292 MCSection *TargetLoweringObjectFile::getSectionForConstant(
293 const DataLayout &DL, SectionKind Kind, const Constant *C,
294 unsigned &Align) const {
295 if (Kind.isReadOnly() && ReadOnlySection != nullptr)
296 return ReadOnlySection;
301 /// getTTypeGlobalReference - Return an MCExpr to use for a
302 /// reference to the specified global variable from exception
303 /// handling information.
304 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
305 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
306 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
307 const MCSymbolRefExpr *Ref =
308 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
310 return getTTypeReference(Ref, Encoding, Streamer);
313 const MCExpr *TargetLoweringObjectFile::
314 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
315 MCStreamer &Streamer) const {
316 switch (Encoding & 0x70) {
318 report_fatal_error("We do not support this DWARF encoding yet!");
319 case dwarf::DW_EH_PE_absptr:
320 // Do nothing special
322 case dwarf::DW_EH_PE_pcrel: {
323 // Emit a label to the streamer for the current position. This gives us
325 MCSymbol *PCSym = getContext().createTempSymbol();
326 Streamer.EmitLabel(PCSym);
327 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
328 return MCBinaryExpr::createSub(Sym, PC, getContext());
333 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
334 // FIXME: It's not clear what, if any, default this should have - perhaps a
335 // null return could mean 'no location' & we should just do that here.
336 return MCSymbolRefExpr::create(Sym, *Ctx);
339 void TargetLoweringObjectFile::getNameWithPrefix(
340 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
341 const TargetMachine &TM) const {
342 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);