[ARM] MVE integer min and max
[llvm-complete.git] / lib / Target / TargetLoweringObjectFile.cpp
blobee32d01572461edcf32587845e90a43dae9cfd58
1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 using namespace llvm;
32 //===----------------------------------------------------------------------===//
33 // Generic Code
34 //===----------------------------------------------------------------------===//
36 /// Initialize - this method must be called before any actual lowering is
37 /// done. This specifies the current context for codegen, and gives the
38 /// lowering implementations a chance to set up their default sections.
39 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
40 const TargetMachine &TM) {
41 Ctx = &ctx;
42 // `Initialize` can be called more than once.
43 delete Mang;
44 Mang = new Mangler();
45 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx,
46 TM.getCodeModel() == CodeModel::Large);
48 // Reset various EH DWARF encodings.
49 PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
52 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
53 delete Mang;
56 static bool isNullOrUndef(const Constant *C) {
57 // Check that the constant isn't all zeros or undefs.
58 if (C->isNullValue() || isa<UndefValue>(C))
59 return true;
60 if (!isa<ConstantAggregate>(C))
61 return false;
62 for (auto Operand : C->operand_values()) {
63 if (!isNullOrUndef(cast<Constant>(Operand)))
64 return false;
66 return true;
69 static bool isSuitableForBSS(const GlobalVariable *GV) {
70 const Constant *C = GV->getInitializer();
72 // Must have zero initializer.
73 if (!isNullOrUndef(C))
74 return false;
76 // Leave constant zeros in readonly constant sections, so they can be shared.
77 if (GV->isConstant())
78 return false;
80 // If the global has an explicit section specified, don't put it in BSS.
81 if (GV->hasSection())
82 return false;
84 // Otherwise, put it in BSS!
85 return true;
88 /// IsNullTerminatedString - Return true if the specified constant (which is
89 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
90 /// nul value and contains no other nuls in it. Note that this is more general
91 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
92 static bool IsNullTerminatedString(const Constant *C) {
93 // First check: is we have constant array terminated with zero
94 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
95 unsigned NumElts = CDS->getNumElements();
96 assert(NumElts != 0 && "Can't have an empty CDS");
98 if (CDS->getElementAsInteger(NumElts-1) != 0)
99 return false; // Not null terminated.
101 // Verify that the null doesn't occur anywhere else in the string.
102 for (unsigned i = 0; i != NumElts-1; ++i)
103 if (CDS->getElementAsInteger(i) == 0)
104 return false;
105 return true;
108 // Another possibility: [1 x i8] zeroinitializer
109 if (isa<ConstantAggregateZero>(C))
110 return cast<ArrayType>(C->getType())->getNumElements() == 1;
112 return false;
115 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
116 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
117 assert(!Suffix.empty());
119 SmallString<60> NameStr;
120 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
121 TM.getNameWithPrefix(NameStr, GV, *Mang);
122 NameStr.append(Suffix.begin(), Suffix.end());
123 return Ctx->getOrCreateSymbol(NameStr);
126 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
127 const GlobalValue *GV, const TargetMachine &TM,
128 MachineModuleInfo *MMI) const {
129 return TM.getSymbol(GV);
132 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
133 const DataLayout &,
134 const MCSymbol *Sym) const {
138 /// getKindForGlobal - This is a top-level target-independent classifier for
139 /// a global object. Given a global variable and information from the TM, this
140 /// function classifies the global in a target independent manner. This function
141 /// may be overridden by the target implementation.
142 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
143 const TargetMachine &TM){
144 assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
145 "Can only be used for global definitions");
147 // Functions are classified as text sections.
148 if (isa<Function>(GO))
149 return SectionKind::getText();
151 // Global variables require more detailed analysis.
152 const auto *GVar = cast<GlobalVariable>(GO);
154 // Handle thread-local data first.
155 if (GVar->isThreadLocal()) {
156 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
157 return SectionKind::getThreadBSS();
158 return SectionKind::getThreadData();
161 // Variables with common linkage always get classified as common.
162 if (GVar->hasCommonLinkage())
163 return SectionKind::getCommon();
165 // Most non-mergeable zero data can be put in the BSS section unless otherwise
166 // specified.
167 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
168 if (GVar->hasLocalLinkage())
169 return SectionKind::getBSSLocal();
170 else if (GVar->hasExternalLinkage())
171 return SectionKind::getBSSExtern();
172 return SectionKind::getBSS();
175 // If the global is marked constant, we can put it into a mergable section,
176 // a mergable string section, or general .data if it contains relocations.
177 if (GVar->isConstant()) {
178 // If the initializer for the global contains something that requires a
179 // relocation, then we may have to drop this into a writable data section
180 // even though it is marked const.
181 const Constant *C = GVar->getInitializer();
182 if (!C->needsRelocation()) {
183 // If the global is required to have a unique address, it can't be put
184 // into a mergable section: just drop it into the general read-only
185 // section instead.
186 if (!GVar->hasGlobalUnnamedAddr())
187 return SectionKind::getReadOnly();
189 // If initializer is a null-terminated string, put it in a "cstring"
190 // section of the right width.
191 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
192 if (IntegerType *ITy =
193 dyn_cast<IntegerType>(ATy->getElementType())) {
194 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
195 ITy->getBitWidth() == 32) &&
196 IsNullTerminatedString(C)) {
197 if (ITy->getBitWidth() == 8)
198 return SectionKind::getMergeable1ByteCString();
199 if (ITy->getBitWidth() == 16)
200 return SectionKind::getMergeable2ByteCString();
202 assert(ITy->getBitWidth() == 32 && "Unknown width");
203 return SectionKind::getMergeable4ByteCString();
208 // Otherwise, just drop it into a mergable constant section. If we have
209 // a section for this size, use it, otherwise use the arbitrary sized
210 // mergable section.
211 switch (
212 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
213 case 4: return SectionKind::getMergeableConst4();
214 case 8: return SectionKind::getMergeableConst8();
215 case 16: return SectionKind::getMergeableConst16();
216 case 32: return SectionKind::getMergeableConst32();
217 default:
218 return SectionKind::getReadOnly();
221 } else {
222 // In static, ROPI and RWPI relocation models, the linker will resolve
223 // all addresses, so the relocation entries will actually be constants by
224 // the time the app starts up. However, we can't put this into a
225 // mergable section, because the linker doesn't take relocations into
226 // consideration when it tries to merge entries in the section.
227 Reloc::Model ReloModel = TM.getRelocationModel();
228 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
229 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
230 return SectionKind::getReadOnly();
232 // Otherwise, the dynamic linker needs to fix it up, put it in the
233 // writable data.rel section.
234 return SectionKind::getReadOnlyWithRel();
238 // Okay, this isn't a constant.
239 return SectionKind::getData();
242 /// This method computes the appropriate section to emit the specified global
243 /// variable or function definition. This should not be passed external (or
244 /// available externally) globals.
245 MCSection *TargetLoweringObjectFile::SectionForGlobal(
246 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
247 // Select section name.
248 if (GO->hasSection())
249 return getExplicitSectionGlobal(GO, Kind, TM);
251 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
252 auto Attrs = GVar->getAttributes();
253 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
254 (Attrs.hasAttribute("data-section") && Kind.isData()) ||
255 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) {
256 return getExplicitSectionGlobal(GO, Kind, TM);
260 if (auto *F = dyn_cast<Function>(GO)) {
261 if (F->hasFnAttribute("implicit-section-name"))
262 return getExplicitSectionGlobal(GO, Kind, TM);
265 // Use default section depending on the 'type' of global
266 return SelectSectionForGlobal(GO, Kind, TM);
269 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
270 const Function &F, const TargetMachine &TM) const {
271 unsigned Align = 0;
272 return getSectionForConstant(F.getParent()->getDataLayout(),
273 SectionKind::getReadOnly(), /*C=*/nullptr,
274 Align);
277 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
278 bool UsesLabelDifference, const Function &F) const {
279 // In PIC mode, we need to emit the jump table to the same section as the
280 // function body itself, otherwise the label differences won't make sense.
281 // FIXME: Need a better predicate for this: what about custom entries?
282 if (UsesLabelDifference)
283 return true;
285 // We should also do if the section name is NULL or function is declared
286 // in discardable section
287 // FIXME: this isn't the right predicate, should be based on the MCSection
288 // for the function.
289 return F.isWeakForLinker();
292 /// Given a mergable constant with the specified size and relocation
293 /// information, return a section that it should be placed in.
294 MCSection *TargetLoweringObjectFile::getSectionForConstant(
295 const DataLayout &DL, SectionKind Kind, const Constant *C,
296 unsigned &Align) const {
297 if (Kind.isReadOnly() && ReadOnlySection != nullptr)
298 return ReadOnlySection;
300 return DataSection;
303 /// getTTypeGlobalReference - Return an MCExpr to use for a
304 /// reference to the specified global variable from exception
305 /// handling information.
306 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
307 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
308 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
309 const MCSymbolRefExpr *Ref =
310 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
312 return getTTypeReference(Ref, Encoding, Streamer);
315 const MCExpr *TargetLoweringObjectFile::
316 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
317 MCStreamer &Streamer) const {
318 switch (Encoding & 0x70) {
319 default:
320 report_fatal_error("We do not support this DWARF encoding yet!");
321 case dwarf::DW_EH_PE_absptr:
322 // Do nothing special
323 return Sym;
324 case dwarf::DW_EH_PE_pcrel: {
325 // Emit a label to the streamer for the current position. This gives us
326 // .-foo addressing.
327 MCSymbol *PCSym = getContext().createTempSymbol();
328 Streamer.EmitLabel(PCSym);
329 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
330 return MCBinaryExpr::createSub(Sym, PC, getContext());
335 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
336 // FIXME: It's not clear what, if any, default this should have - perhaps a
337 // null return could mean 'no location' & we should just do that here.
338 return MCSymbolRefExpr::create(Sym, *Ctx);
341 void TargetLoweringObjectFile::getNameWithPrefix(
342 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
343 const TargetMachine &TM) const {
344 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);