1 //===-- MipsTargetObjectFile.cpp - Mips Object Files ----------------------===//
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 #include "MipsTargetObjectFile.h"
10 #include "MipsSubtarget.h"
11 #include "MipsTargetMachine.h"
12 #include "MCTargetDesc/MipsMCExpr.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/DerivedTypes.h"
16 #include "llvm/IR/GlobalVariable.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCSectionELF.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Target/TargetMachine.h"
21 using namespace llvm;
22 
23 static cl::opt<unsigned>
24 SSThreshold("mips-ssection-threshold", cl::Hidden,
25             cl::desc("Small data and bss section threshold size (default=8)"),
26             cl::init(8));
27 
28 static cl::opt<bool>
29 LocalSData("mlocal-sdata", cl::Hidden,
30            cl::desc("MIPS: Use gp_rel for object-local data."),
31            cl::init(true));
32 
33 static cl::opt<bool>
34 ExternSData("mextern-sdata", cl::Hidden,
35             cl::desc("MIPS: Use gp_rel for data that is not defined by the "
36                      "current object."),
37             cl::init(true));
38 
39 static cl::opt<bool>
40 EmbeddedData("membedded-data", cl::Hidden,
41              cl::desc("MIPS: Try to allocate variables in the following"
42                       " sections if possible: .rodata, .sdata, .data ."),
43              cl::init(false));
44 
Initialize(MCContext & Ctx,const TargetMachine & TM)45 void MipsTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){
46   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
47 
48   SmallDataSection = getContext().getELFSection(
49       ".sdata", ELF::SHT_PROGBITS,
50       ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
51 
52   SmallBSSSection = getContext().getELFSection(".sbss", ELF::SHT_NOBITS,
53                                                ELF::SHF_WRITE | ELF::SHF_ALLOC |
54                                                    ELF::SHF_MIPS_GPREL);
55   this->TM = &static_cast<const MipsTargetMachine &>(TM);
56 }
57 
58 // A address must be loaded from a small section if its size is less than the
59 // small section size threshold. Data in this section must be addressed using
60 // gp_rel operator.
IsInSmallSection(uint64_t Size)61 static bool IsInSmallSection(uint64_t Size) {
62   // gcc has traditionally not treated zero-sized objects as small data, so this
63   // is effectively part of the ABI.
64   return Size > 0 && Size <= SSThreshold;
65 }
66 
67 /// Return true if this global address should be placed into small data/bss
68 /// section.
IsGlobalInSmallSection(const GlobalObject * GO,const TargetMachine & TM) const69 bool MipsTargetObjectFile::IsGlobalInSmallSection(
70     const GlobalObject *GO, const TargetMachine &TM) const {
71   // We first check the case where global is a declaration, because finding
72   // section kind using getKindForGlobal() is only allowed for global
73   // definitions.
74   if (GO->isDeclaration() || GO->hasAvailableExternallyLinkage())
75     return IsGlobalInSmallSectionImpl(GO, TM);
76 
77   return IsGlobalInSmallSection(GO, TM, getKindForGlobal(GO, TM));
78 }
79 
80 /// Return true if this global address should be placed into small data/bss
81 /// section.
82 bool MipsTargetObjectFile::
IsGlobalInSmallSection(const GlobalObject * GO,const TargetMachine & TM,SectionKind Kind) const83 IsGlobalInSmallSection(const GlobalObject *GO, const TargetMachine &TM,
84                        SectionKind Kind) const {
85   return IsGlobalInSmallSectionImpl(GO, TM) &&
86          (Kind.isData() || Kind.isBSS() || Kind.isCommon() ||
87           Kind.isReadOnly());
88 }
89 
90 /// Return true if this global address should be placed into small data/bss
91 /// section. This method does all the work, except for checking the section
92 /// kind.
93 bool MipsTargetObjectFile::
IsGlobalInSmallSectionImpl(const GlobalObject * GO,const TargetMachine & TM) const94 IsGlobalInSmallSectionImpl(const GlobalObject *GO,
95                            const TargetMachine &TM) const {
96   const MipsSubtarget &Subtarget =
97       *static_cast<const MipsTargetMachine &>(TM).getSubtargetImpl();
98 
99   // Return if small section is not available.
100   if (!Subtarget.useSmallSection())
101     return false;
102 
103   // Only global variables, not functions.
104   const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GO);
105   if (!GVA)
106     return false;
107 
108   // If the variable has an explicit section, it is placed in that section but
109   // it's addressing mode may change.
110   if (GVA->hasSection()) {
111     StringRef Section = GVA->getSection();
112 
113     // Explicitly placing any variable in the small data section overrides
114     // the global -G value.
115     if (Section == ".sdata" || Section == ".sbss")
116       return true;
117 
118     // Otherwise reject accessing it through the gp pointer. There are some
119     // historic cases which GCC doesn't appear to respect any more. These
120     // are .lit4, .lit8 and .srdata. For the moment reject these as well.
121     return false;
122   }
123 
124   // Enforce -mlocal-sdata.
125   if (!LocalSData && GVA->hasLocalLinkage())
126     return false;
127 
128   // Enforce -mextern-sdata.
129   if (!ExternSData && ((GVA->hasExternalLinkage() && GVA->isDeclaration()) ||
130                        GVA->hasCommonLinkage()))
131     return false;
132 
133   // Enforce -membedded-data.
134   if (EmbeddedData && GVA->isConstant())
135     return false;
136 
137   Type *Ty = GVA->getValueType();
138 
139   // It is possible that the type of the global is unsized, i.e. a declaration
140   // of a extern struct. In this case don't presume it is in the small data
141   // section. This happens e.g. when building the FreeBSD kernel.
142   if (!Ty->isSized())
143     return false;
144 
145   return IsInSmallSection(
146       GVA->getParent()->getDataLayout().getTypeAllocSize(Ty));
147 }
148 
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const149 MCSection *MipsTargetObjectFile::SelectSectionForGlobal(
150     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
151   // TODO: Could also support "weak" symbols as well with ".gnu.linkonce.s.*"
152   // sections?
153 
154   // Handle Small Section classification here.
155   if (Kind.isBSS() && IsGlobalInSmallSection(GO, TM, Kind))
156     return SmallBSSSection;
157   if (Kind.isData() && IsGlobalInSmallSection(GO, TM, Kind))
158     return SmallDataSection;
159   if (Kind.isReadOnly() && IsGlobalInSmallSection(GO, TM, Kind))
160     return SmallDataSection;
161 
162   // Otherwise, we work the same as ELF.
163   return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM);
164 }
165 
166 /// Return true if this constant should be placed into small data section.
IsConstantInSmallSection(const DataLayout & DL,const Constant * CN,const TargetMachine & TM) const167 bool MipsTargetObjectFile::IsConstantInSmallSection(
168     const DataLayout &DL, const Constant *CN, const TargetMachine &TM) const {
169   return (static_cast<const MipsTargetMachine &>(TM)
170               .getSubtargetImpl()
171               ->useSmallSection() &&
172           LocalSData && IsInSmallSection(DL.getTypeAllocSize(CN->getType())));
173 }
174 
175 /// Return true if this constant should be placed into small data section.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const176 MCSection *MipsTargetObjectFile::getSectionForConstant(const DataLayout &DL,
177                                                        SectionKind Kind,
178                                                        const Constant *C,
179                                                        Align &Alignment) const {
180   if (IsConstantInSmallSection(DL, C, *TM))
181     return SmallDataSection;
182 
183   // Otherwise, we work the same as ELF.
184   return TargetLoweringObjectFileELF::getSectionForConstant(DL, Kind, C,
185                                                             Alignment);
186 }
187 
188 const MCExpr *
getDebugThreadLocalSymbol(const MCSymbol * Sym) const189 MipsTargetObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
190   const MCExpr *Expr =
191       MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
192   Expr = MCBinaryExpr::createAdd(
193       Expr, MCConstantExpr::create(0x8000, getContext()), getContext());
194   return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL, Expr, getContext());
195 }
196