1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetLoweringObjectFile.h"
15 #include "llvm/BinaryFormat/Dwarf.h"
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/IR/Module.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/MC/SectionKind.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.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) {
43 // `Initialize` can be called more than once.
46 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), ctx,
47 TM.getCodeModel() == CodeModel::Large);
49 // Reset various EH DWARF encodings.
50 PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
51 CallSiteEncoding = dwarf::DW_EH_PE_uleb128;
54 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
58 static bool isNullOrUndef(const Constant *C) {
59 // Check that the constant isn't all zeros or undefs.
60 if (C->isNullValue() || isa<UndefValue>(C))
62 if (!isa<ConstantAggregate>(C))
64 for (auto Operand : C->operand_values()) {
65 if (!isNullOrUndef(cast<Constant>(Operand)))
71 static bool isSuitableForBSS(const GlobalVariable *GV) {
72 const Constant *C = GV->getInitializer();
74 // Must have zero initializer.
75 if (!isNullOrUndef(C))
78 // Leave constant zeros in readonly constant sections, so they can be shared.
82 // If the global has an explicit section specified, don't put it in BSS.
86 // Otherwise, put it in BSS!
90 /// IsNullTerminatedString - Return true if the specified constant (which is
91 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
92 /// nul value and contains no other nuls in it. Note that this is more general
93 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
94 static bool IsNullTerminatedString(const Constant *C) {
95 // First check: is we have constant array terminated with zero
96 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
97 unsigned NumElts = CDS->getNumElements();
98 assert(NumElts != 0 && "Can't have an empty CDS");
100 if (CDS->getElementAsInteger(NumElts-1) != 0)
101 return false; // Not null terminated.
103 // Verify that the null doesn't occur anywhere else in the string.
104 for (unsigned i = 0; i != NumElts-1; ++i)
105 if (CDS->getElementAsInteger(i) == 0)
110 // Another possibility: [1 x i8] zeroinitializer
111 if (isa<ConstantAggregateZero>(C))
112 return cast<ArrayType>(C->getType())->getNumElements() == 1;
117 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
118 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
119 assert(!Suffix.empty());
121 SmallString<60> NameStr;
122 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
123 TM.getNameWithPrefix(NameStr, GV, *Mang);
124 NameStr.append(Suffix.begin(), Suffix.end());
125 return getContext().getOrCreateSymbol(NameStr);
128 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
129 const GlobalValue *GV, const TargetMachine &TM,
130 MachineModuleInfo *MMI) const {
131 return TM.getSymbol(GV);
134 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
136 const MCSymbol *Sym) const {
140 /// getKindForGlobal - This is a top-level target-independent classifier for
141 /// a global object. Given a global variable and information from the TM, this
142 /// function classifies the global in a target independent manner. This function
143 /// may be overridden by the target implementation.
144 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
145 const TargetMachine &TM){
146 assert(!GO->isDeclarationForLinker() &&
147 "Can only be used for global definitions");
149 // Functions are classified as text sections.
150 if (isa<Function>(GO))
151 return SectionKind::getText();
153 // Basic blocks are classified as text sections.
154 if (isa<BasicBlock>(GO))
155 return SectionKind::getText();
157 // Global variables require more detailed analysis.
158 const auto *GVar = cast<GlobalVariable>(GO);
160 // Handle thread-local data first.
161 if (GVar->isThreadLocal()) {
162 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
163 return SectionKind::getThreadBSS();
164 return SectionKind::getThreadData();
167 // Variables with common linkage always get classified as common.
168 if (GVar->hasCommonLinkage())
169 return SectionKind::getCommon();
171 // Most non-mergeable zero data can be put in the BSS section unless otherwise
173 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
174 if (GVar->hasLocalLinkage())
175 return SectionKind::getBSSLocal();
176 else if (GVar->hasExternalLinkage())
177 return SectionKind::getBSSExtern();
178 return SectionKind::getBSS();
181 // If the global is marked constant, we can put it into a mergable section,
182 // a mergable string section, or general .data if it contains relocations.
183 if (GVar->isConstant()) {
184 // If the initializer for the global contains something that requires a
185 // relocation, then we may have to drop this into a writable data section
186 // even though it is marked const.
187 const Constant *C = GVar->getInitializer();
188 if (!C->needsRelocation()) {
189 // If the global is required to have a unique address, it can't be put
190 // into a mergable section: just drop it into the general read-only
192 if (!GVar->hasGlobalUnnamedAddr())
193 return SectionKind::getReadOnly();
195 // If initializer is a null-terminated string, put it in a "cstring"
196 // section of the right width.
197 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
198 if (IntegerType *ITy =
199 dyn_cast<IntegerType>(ATy->getElementType())) {
200 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
201 ITy->getBitWidth() == 32) &&
202 IsNullTerminatedString(C)) {
203 if (ITy->getBitWidth() == 8)
204 return SectionKind::getMergeable1ByteCString();
205 if (ITy->getBitWidth() == 16)
206 return SectionKind::getMergeable2ByteCString();
208 assert(ITy->getBitWidth() == 32 && "Unknown width");
209 return SectionKind::getMergeable4ByteCString();
214 // Otherwise, just drop it into a mergable constant section. If we have
215 // a section for this size, use it, otherwise use the arbitrary sized
218 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
219 case 4: return SectionKind::getMergeableConst4();
220 case 8: return SectionKind::getMergeableConst8();
221 case 16: return SectionKind::getMergeableConst16();
222 case 32: return SectionKind::getMergeableConst32();
224 return SectionKind::getReadOnly();
228 // In static, ROPI and RWPI relocation models, the linker will resolve
229 // all addresses, so the relocation entries will actually be constants by
230 // the time the app starts up. However, we can't put this into a
231 // mergable section, because the linker doesn't take relocations into
232 // consideration when it tries to merge entries in the section.
233 Reloc::Model ReloModel = TM.getRelocationModel();
234 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
235 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
236 return SectionKind::getReadOnly();
238 // Otherwise, the dynamic linker needs to fix it up, put it in the
239 // writable data.rel section.
240 return SectionKind::getReadOnlyWithRel();
244 // Okay, this isn't a constant.
245 return SectionKind::getData();
248 /// This method computes the appropriate section to emit the specified global
249 /// variable or function definition. This should not be passed external (or
250 /// available externally) globals.
251 MCSection *TargetLoweringObjectFile::SectionForGlobal(
252 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
253 // Select section name.
254 if (GO->hasSection())
255 return getExplicitSectionGlobal(GO, Kind, TM);
257 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
258 auto Attrs = GVar->getAttributes();
259 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
260 (Attrs.hasAttribute("data-section") && Kind.isData()) ||
261 (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) ||
262 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) {
263 return getExplicitSectionGlobal(GO, Kind, TM);
267 if (auto *F = dyn_cast<Function>(GO)) {
268 if (F->hasFnAttribute("implicit-section-name"))
269 return getExplicitSectionGlobal(GO, Kind, TM);
272 // Use default section depending on the 'type' of global
273 return SelectSectionForGlobal(GO, Kind, TM);
276 /// This method computes the appropriate section to emit the specified global
277 /// variable or function definition. This should not be passed external (or
278 /// available externally) globals.
280 TargetLoweringObjectFile::SectionForGlobal(const GlobalObject *GO,
281 const TargetMachine &TM) const {
282 return SectionForGlobal(GO, getKindForGlobal(GO, TM), TM);
285 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
286 const Function &F, const TargetMachine &TM) const {
288 return getSectionForConstant(F.getParent()->getDataLayout(),
289 SectionKind::getReadOnly(), /*C=*/nullptr,
293 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
294 bool UsesLabelDifference, const Function &F) const {
295 // In PIC mode, we need to emit the jump table to the same section as the
296 // function body itself, otherwise the label differences won't make sense.
297 // FIXME: Need a better predicate for this: what about custom entries?
298 if (UsesLabelDifference)
301 // We should also do if the section name is NULL or function is declared
302 // in discardable section
303 // FIXME: this isn't the right predicate, should be based on the MCSection
305 return F.isWeakForLinker();
308 /// Given a mergable constant with the specified size and relocation
309 /// information, return a section that it should be placed in.
310 MCSection *TargetLoweringObjectFile::getSectionForConstant(
311 const DataLayout &DL, SectionKind Kind, const Constant *C,
312 Align &Alignment) const {
313 if (Kind.isReadOnly() && ReadOnlySection != nullptr)
314 return ReadOnlySection;
319 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock(
320 const Function &F, const MachineBasicBlock &MBB,
321 const TargetMachine &TM) const {
325 /// getTTypeGlobalReference - Return an MCExpr to use for a
326 /// reference to the specified global variable from exception
327 /// handling information.
328 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
329 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
330 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
331 const MCSymbolRefExpr *Ref =
332 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
334 return getTTypeReference(Ref, Encoding, Streamer);
337 const MCExpr *TargetLoweringObjectFile::
338 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
339 MCStreamer &Streamer) const {
340 switch (Encoding & 0x70) {
342 report_fatal_error("We do not support this DWARF encoding yet!");
343 case dwarf::DW_EH_PE_absptr:
344 // Do nothing special
346 case dwarf::DW_EH_PE_pcrel: {
347 // Emit a label to the streamer for the current position. This gives us
349 MCSymbol *PCSym = getContext().createTempSymbol();
350 Streamer.emitLabel(PCSym);
351 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
352 return MCBinaryExpr::createSub(Sym, PC, getContext());
357 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
358 // FIXME: It's not clear what, if any, default this should have - perhaps a
359 // null return could mean 'no location' & we should just do that here.
360 return MCSymbolRefExpr::create(Sym, getContext());
363 void TargetLoweringObjectFile::getNameWithPrefix(
364 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
365 const TargetMachine &TM) const {
366 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);