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.
11 //
12 //===----------------------------------------------------------------------===//
13 
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;
31 
32 //===----------------------------------------------------------------------===//
33 //                              Generic Code
34 //===----------------------------------------------------------------------===//
35 
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);
47 
48   // Reset various EH DWARF encodings.
49   PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
50   CallSiteEncoding = dwarf::DW_EH_PE_uleb128;
51 }
52 
53 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
54   delete Mang;
55 }
56 
57 static bool isNullOrUndef(const Constant *C) {
58   // Check that the constant isn't all zeros or undefs.
59   if (C->isNullValue() || isa<UndefValue>(C))
60     return true;
61   if (!isa<ConstantAggregate>(C))
62     return false;
63   for (auto Operand : C->operand_values()) {
64     if (!isNullOrUndef(cast<Constant>(Operand)))
65       return false;
66   }
67   return true;
68 }
69 
70 static bool isSuitableForBSS(const GlobalVariable *GV) {
71   const Constant *C = GV->getInitializer();
72 
73   // Must have zero initializer.
74   if (!isNullOrUndef(C))
75     return false;
76 
77   // Leave constant zeros in readonly constant sections, so they can be shared.
78   if (GV->isConstant())
79     return false;
80 
81   // If the global has an explicit section specified, don't put it in BSS.
82   if (GV->hasSection())
83     return false;
84 
85   // Otherwise, put it in BSS!
86   return true;
87 }
88 
89 /// IsNullTerminatedString - Return true if the specified constant (which is
90 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
91 /// nul value and contains no other nuls in it.  Note that this is more general
92 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
93 static bool IsNullTerminatedString(const Constant *C) {
94   // First check: is we have constant array terminated with zero
95   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
96     unsigned NumElts = CDS->getNumElements();
97     assert(NumElts != 0 && "Can't have an empty CDS");
98 
99     if (CDS->getElementAsInteger(NumElts-1) != 0)
100       return false; // Not null terminated.
101 
102     // Verify that the null doesn't occur anywhere else in the string.
103     for (unsigned i = 0; i != NumElts-1; ++i)
104       if (CDS->getElementAsInteger(i) == 0)
105         return false;
106     return true;
107   }
108 
109   // Another possibility: [1 x i8] zeroinitializer
110   if (isa<ConstantAggregateZero>(C))
111     return cast<ArrayType>(C->getType())->getNumElements() == 1;
112 
113   return false;
114 }
115 
116 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
117     const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
118   assert(!Suffix.empty());
119 
120   SmallString<60> NameStr;
121   NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
122   TM.getNameWithPrefix(NameStr, GV, *Mang);
123   NameStr.append(Suffix.begin(), Suffix.end());
124   return Ctx->getOrCreateSymbol(NameStr);
125 }
126 
127 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
128     const GlobalValue *GV, const TargetMachine &TM,
129     MachineModuleInfo *MMI) const {
130   return TM.getSymbol(GV);
131 }
132 
133 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
134                                                     const DataLayout &,
135                                                     const MCSymbol *Sym) const {
136 }
137 
138 
139 /// getKindForGlobal - This is a top-level target-independent classifier for
140 /// a global object.  Given a global variable and information from the TM, this
141 /// function classifies the global in a target independent manner. This function
142 /// may be overridden by the target implementation.
143 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
144                                                        const TargetMachine &TM){
145   assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
146          "Can only be used for global definitions");
147 
148   // Functions are classified as text sections.
149   if (isa<Function>(GO))
150     return SectionKind::getText();
151 
152   // Basic blocks are classified as text sections.
153   if (isa<BasicBlock>(GO))
154     return SectionKind::getText();
155 
156   // Global variables require more detailed analysis.
157   const auto *GVar = cast<GlobalVariable>(GO);
158 
159   // Handle thread-local data first.
160   if (GVar->isThreadLocal()) {
161     if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS)
162       return SectionKind::getThreadBSS();
163     return SectionKind::getThreadData();
164   }
165 
166   // Variables with common linkage always get classified as common.
167   if (GVar->hasCommonLinkage())
168     return SectionKind::getCommon();
169 
170   // Most non-mergeable zero data can be put in the BSS section unless otherwise
171   // specified.
172   if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
173     if (GVar->hasLocalLinkage())
174       return SectionKind::getBSSLocal();
175     else if (GVar->hasExternalLinkage())
176       return SectionKind::getBSSExtern();
177     return SectionKind::getBSS();
178   }
179 
180   // If the global is marked constant, we can put it into a mergable section,
181   // a mergable string section, or general .data if it contains relocations.
182   if (GVar->isConstant()) {
183     // If the initializer for the global contains something that requires a
184     // relocation, then we may have to drop this into a writable data section
185     // even though it is marked const.
186     const Constant *C = GVar->getInitializer();
187     if (!C->needsRelocation()) {
188       // If the global is required to have a unique address, it can't be put
189       // into a mergable section: just drop it into the general read-only
190       // section instead.
191       if (!GVar->hasGlobalUnnamedAddr())
192         return SectionKind::getReadOnly();
193 
194       // If initializer is a null-terminated string, put it in a "cstring"
195       // section of the right width.
196       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
197         if (IntegerType *ITy =
198               dyn_cast<IntegerType>(ATy->getElementType())) {
199           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
200                ITy->getBitWidth() == 32) &&
201               IsNullTerminatedString(C)) {
202             if (ITy->getBitWidth() == 8)
203               return SectionKind::getMergeable1ByteCString();
204             if (ITy->getBitWidth() == 16)
205               return SectionKind::getMergeable2ByteCString();
206 
207             assert(ITy->getBitWidth() == 32 && "Unknown width");
208             return SectionKind::getMergeable4ByteCString();
209           }
210         }
211       }
212 
213       // Otherwise, just drop it into a mergable constant section.  If we have
214       // a section for this size, use it, otherwise use the arbitrary sized
215       // mergable section.
216       switch (
217           GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
218       case 4:  return SectionKind::getMergeableConst4();
219       case 8:  return SectionKind::getMergeableConst8();
220       case 16: return SectionKind::getMergeableConst16();
221       case 32: return SectionKind::getMergeableConst32();
222       default:
223         return SectionKind::getReadOnly();
224       }
225 
226     } else {
227       // In static, ROPI and RWPI relocation models, the linker will resolve
228       // all addresses, so the relocation entries will actually be constants by
229       // the time the app starts up.  However, we can't put this into a
230       // mergable section, because the linker doesn't take relocations into
231       // consideration when it tries to merge entries in the section.
232       Reloc::Model ReloModel = TM.getRelocationModel();
233       if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
234           ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI)
235         return SectionKind::getReadOnly();
236 
237       // Otherwise, the dynamic linker needs to fix it up, put it in the
238       // writable data.rel section.
239       return SectionKind::getReadOnlyWithRel();
240     }
241   }
242 
243   // Okay, this isn't a constant.
244   return SectionKind::getData();
245 }
246 
247 /// This method computes the appropriate section to emit the specified global
248 /// variable or function definition.  This should not be passed external (or
249 /// available externally) globals.
250 MCSection *TargetLoweringObjectFile::SectionForGlobal(
251     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
252   // Select section name.
253   if (GO->hasSection())
254     return getExplicitSectionGlobal(GO, Kind, TM);
255 
256   if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
257     auto Attrs = GVar->getAttributes();
258     if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
259         (Attrs.hasAttribute("data-section") && Kind.isData()) ||
260         (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) ||
261         (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()))  {
262        return getExplicitSectionGlobal(GO, Kind, TM);
263     }
264   }
265 
266   if (auto *F = dyn_cast<Function>(GO)) {
267     if (F->hasFnAttribute("implicit-section-name"))
268       return getExplicitSectionGlobal(GO, Kind, TM);
269   }
270 
271   // Use default section depending on the 'type' of global
272   return SelectSectionForGlobal(GO, Kind, TM);
273 }
274 
275 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
276     const Function &F, const TargetMachine &TM) const {
277   unsigned Align = 0;
278   return getSectionForConstant(F.getParent()->getDataLayout(),
279                                SectionKind::getReadOnly(), /*C=*/nullptr,
280                                Align);
281 }
282 
283 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
284     bool UsesLabelDifference, const Function &F) const {
285   // In PIC mode, we need to emit the jump table to the same section as the
286   // function body itself, otherwise the label differences won't make sense.
287   // FIXME: Need a better predicate for this: what about custom entries?
288   if (UsesLabelDifference)
289     return true;
290 
291   // We should also do if the section name is NULL or function is declared
292   // in discardable section
293   // FIXME: this isn't the right predicate, should be based on the MCSection
294   // for the function.
295   return F.isWeakForLinker();
296 }
297 
298 /// Given a mergable constant with the specified size and relocation
299 /// information, return a section that it should be placed in.
300 MCSection *TargetLoweringObjectFile::getSectionForConstant(
301     const DataLayout &DL, SectionKind Kind, const Constant *C,
302     unsigned &Align) const {
303   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
304     return ReadOnlySection;
305 
306   return DataSection;
307 }
308 
309 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock(
310     const Function &F, const MachineBasicBlock &MBB,
311     const TargetMachine &TM) const {
312   return nullptr;
313 }
314 
315 MCSection *TargetLoweringObjectFile::getNamedSectionForMachineBasicBlock(
316     const Function &F, const MachineBasicBlock &MBB, const TargetMachine &TM,
317     const char *Suffix) const {
318   return nullptr;
319 }
320 
321 /// getTTypeGlobalReference - Return an MCExpr to use for a
322 /// reference to the specified global variable from exception
323 /// handling information.
324 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
325     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
326     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
327   const MCSymbolRefExpr *Ref =
328       MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
329 
330   return getTTypeReference(Ref, Encoding, Streamer);
331 }
332 
333 const MCExpr *TargetLoweringObjectFile::
334 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
335                   MCStreamer &Streamer) const {
336   switch (Encoding & 0x70) {
337   default:
338     report_fatal_error("We do not support this DWARF encoding yet!");
339   case dwarf::DW_EH_PE_absptr:
340     // Do nothing special
341     return Sym;
342   case dwarf::DW_EH_PE_pcrel: {
343     // Emit a label to the streamer for the current position.  This gives us
344     // .-foo addressing.
345     MCSymbol *PCSym = getContext().createTempSymbol();
346     Streamer.emitLabel(PCSym);
347     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
348     return MCBinaryExpr::createSub(Sym, PC, getContext());
349   }
350   }
351 }
352 
353 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
354   // FIXME: It's not clear what, if any, default this should have - perhaps a
355   // null return could mean 'no location' & we should just do that here.
356   return MCSymbolRefExpr::create(Sym, *Ctx);
357 }
358 
359 void TargetLoweringObjectFile::getNameWithPrefix(
360     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
361     const TargetMachine &TM) const {
362   Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
363 }
364