LLVM 24.0.0git
PPCAsmBackend.cpp
Go to the documentation of this file.
1//===-- PPCAsmBackend.cpp - PPC Assembler Backend -------------------------===//
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
12#include "llvm/ADT/StringRef.h"
16#include "llvm/MC/MCAssembler.h"
17#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCSection.h"
23#include "llvm/MC/MCSymbolELF.h"
25#include "llvm/MC/MCValue.h"
28#include <cstdint>
29using namespace llvm;
30
31static uint64_t adjustFixupValue(MCContext &Ctx, const MCFixup &Fixup,
32 unsigned Kind, uint64_t Value,
33 const MCValue &Target, StringRef SecName,
34 uint64_t SrcOffset) {
35 // Name the target and the call position for the diagnostic. Build it only
36 // when an error is reported, since most fixups succeed.
37 auto describeBranch = [&]() -> std::string {
38 std::string Desc;
39 if (const MCSymbol *Sym = Target.getAddSym())
40 Desc += (Twine(" to '") + Sym->getName() + "'").str();
41 if (!SecName.empty())
42 Desc +=
43 (Twine(" at ") + SecName + "+0x" + Twine::utohexstr(SrcOffset)).str();
44 return Desc;
45 };
46
47 auto checkBrFixup = [&](unsigned Bits) {
48 int64_t SVal = int64_t(Value);
49 if ((Value & 3) != 0) {
50 Ctx.reportError(Fixup.getLoc(), "branch target not a multiple of four (" +
51 Twine(SVal) + ")" + describeBranch());
52 return;
53 }
54
55 // Low two bits are not encoded.
56 if (!isIntN(Bits + 2, Value)) {
57 Ctx.reportError(Fixup.getLoc(),
58 "branch target out of range (" + Twine(SVal) +
59 " not between " + Twine(minIntN(Bits) * 4) + " and " +
60 Twine(maxIntN(Bits) * 4) + ")" + describeBranch());
61 }
62 };
63
64 switch (Kind) {
65 default:
66 llvm_unreachable("Unknown fixup kind!");
67 case FK_Data_1:
68 case FK_Data_2:
69 case FK_Data_4:
70 case FK_Data_8:
72 return Value;
75 checkBrFixup(14);
76 return Value & 0xfffc;
80 checkBrFixup(24);
81 return Value & 0x3fffffc;
83 return Value & 0xffff;
86 return Value & 0xfffc;
89 return Value & 0xffffffff;
92 return Value & 0x3ffffffff;
93 }
94}
95
96static unsigned getFixupKindNumBytes(unsigned Kind) {
97 switch (Kind) {
98 default:
99 llvm_unreachable("Unknown fixup kind!");
100 case FK_Data_1:
101 return 1;
102 case FK_Data_2:
106 return 2;
107 case FK_Data_4:
113 return 4;
118 case FK_Data_8:
119 return 8;
121 return 0;
122 }
123}
124
125namespace {
126
127class PPCAsmBackend : public MCAsmBackend {
128protected:
129 Triple TT;
130public:
131 PPCAsmBackend(const Target &T, const Triple &TT)
132 : MCAsmBackend(TT.isLittleEndian() ? llvm::endianness::little
133 : llvm::endianness::big),
134 TT(TT) {}
135
136 MCFixupKindInfo getFixupKindInfo(MCFixupKind Kind) const override;
137
138 void applyFixup(const MCFragment &, const MCFixup &Fixup,
139 const MCValue &Target, uint8_t *Data, uint64_t Value,
140 bool IsResolved) override;
141
142 bool shouldForceRelocation(const MCFixup &Fixup, const MCValue &Target) {
143 // If there is a @ specifier, unless it is optimized out (e.g. constant @l),
144 // force a relocation.
145 if (Target.getSpecifier())
146 return true;
147 MCFixupKind Kind = Fixup.getKind();
148 switch ((unsigned)Kind) {
149 default:
150 return false;
154 // If the target symbol has a local entry point we must not attempt
155 // to resolve the fixup directly. Emit a relocation and leave
156 // resolution of the final target address to the linker.
157 if (const auto *A = Target.getAddSym()) {
158 if (getContext().isELF()) {
159 // The "other" values are stored in the last 6 bits of the second
160 // byte. The traditional defines for STO values assume the full byte
161 // and thus the shift to pack it.
162 unsigned Other = static_cast<const MCSymbolELF *>(A)->getOther() << 2;
163 if ((Other & ELF::STO_PPC64_LOCAL_MASK) != 0)
164 return true;
165 } else if (getContext().isXCOFF()) {
166 auto *S = static_cast<const MCSymbolXCOFF *>(A);
167 return !Target.isAbsolute() && S->isExternal() &&
168 S->getStorageClass() == XCOFF::C_WEAKEXT;
169 }
170 }
171 return false;
172 }
173 }
174
175 bool writeNopData(raw_ostream &OS, uint64_t Count,
176 const MCSubtargetInfo *STI) const override {
177 uint64_t NumNops = Count / 4;
178 for (uint64_t i = 0; i != NumNops; ++i)
179 support::endian::write<uint32_t>(OS, 0x60000000, Endian);
180
181 OS.write_zeros(Count % 4);
182
183 return true;
184 }
185};
186} // end anonymous namespace
187
188MCFixupKindInfo PPCAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
189 // clang-format off
190 const static MCFixupKindInfo InfosBE[PPC::NumTargetFixupKinds] = {
191 // name offset bits flags
192 {"fixup_ppc_br24", 6, 24, 0},
193 {"fixup_ppc_br24_notoc", 6, 24, 0},
194 {"fixup_ppc_brcond14", 16, 14, 0},
195 {"fixup_ppc_br24abs", 6, 24, 0},
196 {"fixup_ppc_brcond14abs", 16, 14, 0},
197 {"fixup_ppc_half16", 0, 16, 0},
198 {"fixup_ppc_half16ds", 0, 14, 0},
199 {"fixup_ppc_pcrel32", 0, 32, 0},
200 {"fixup_ppc_imm32", 0, 32, 0},
201 {"fixup_ppc_pcrel34", 0, 34, 0},
202 {"fixup_ppc_imm34", 0, 34, 0},
203 {"fixup_ppc_nofixup", 0, 0, 0}};
204 const static MCFixupKindInfo InfosLE[PPC::NumTargetFixupKinds] = {
205 // name offset bits flags
206 {"fixup_ppc_br24", 2, 24, 0},
207 {"fixup_ppc_br24_notoc", 2, 24, 0},
208 {"fixup_ppc_brcond14", 2, 14, 0},
209 {"fixup_ppc_br24abs", 2, 24, 0},
210 {"fixup_ppc_brcond14abs", 2, 14, 0},
211 {"fixup_ppc_half16", 0, 16, 0},
212 {"fixup_ppc_half16ds", 2, 14, 0},
213 {"fixup_ppc_pcrel32", 0, 32, 0},
214 {"fixup_ppc_imm32", 0, 32, 0},
215 {"fixup_ppc_pcrel34", 0, 34, 0},
216 {"fixup_ppc_imm34", 0, 34, 0},
217 {"fixup_ppc_nofixup", 0, 0, 0}};
218 // clang-format on
219
220 // Fixup kinds from .reloc directive are like R_PPC_NONE/R_PPC64_NONE. They
221 // do not require any extra processing.
222 if (mc::isRelocation(Kind))
223 return {};
224
225 if (Kind < FirstTargetFixupKind)
227
229 "Invalid kind!");
230 return (Endian == llvm::endianness::little
231 ? InfosLE
232 : InfosBE)[Kind - FirstTargetFixupKind];
233}
234
235void PPCAsmBackend::applyFixup(const MCFragment &F, const MCFixup &Fixup,
236 const MCValue &TargetVal, uint8_t *Data,
237 uint64_t Value, bool IsResolved) {
238 // In PPC64 ELFv1, .quad .TOC.@tocbase in the .opd section is expected to
239 // reference the null symbol.
240 auto Target = TargetVal;
241 if (Target.getSpecifier() == PPC::S_TOCBASE)
242 Target.setAddSym(nullptr);
243 if (IsResolved && shouldForceRelocation(Fixup, Target))
244 IsResolved = false;
245 if (!IsResolved)
246 Asm->getWriter().recordRelocation(F, Fixup, Target, Value);
247
248 MCFixupKind Kind = Fixup.getKind();
249 if (mc::isRelocation(Kind))
250 return;
251 const MCSection *Sec = F.getParent();
252 Value = adjustFixupValue(getContext(), Fixup, Kind, Value, Target,
253 Sec ? Sec->getName() : StringRef(),
254 Asm->getFragmentOffset(F) + Fixup.getOffset());
255 if (!Value)
256 return; // Doesn't change encoding.
257
258 unsigned NumBytes = getFixupKindNumBytes(Kind);
259
260 // For each byte of the fragment that the fixup touches, mask in the bits
261 // from the fixup value. The Value has been "split up" into the appropriate
262 // bitfields above.
263 for (unsigned i = 0; i != NumBytes; ++i) {
264 unsigned Idx = Endian == llvm::endianness::little ? i : (NumBytes - 1 - i);
265 Data[i] |= uint8_t((Value >> (Idx * 8)) & 0xff);
266 }
267}
268
269// FIXME: This should be in a separate file.
270namespace {
271
272class ELFPPCAsmBackend : public PPCAsmBackend {
273public:
274 ELFPPCAsmBackend(const Target &T, const Triple &TT) : PPCAsmBackend(T, TT) {}
275
276 std::unique_ptr<MCObjectTargetWriter>
277 createObjectTargetWriter() const override {
278 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
279 bool Is64 = TT.isPPC64();
280 return createPPCELFObjectWriter(Is64, OSABI);
281 }
282
283 std::optional<MCFixupKind> getFixupKind(StringRef Name) const override;
284};
285
286class XCOFFPPCAsmBackend : public PPCAsmBackend {
287public:
288 XCOFFPPCAsmBackend(const Target &T, const Triple &TT)
289 : PPCAsmBackend(T, TT) {}
290
291 std::unique_ptr<MCObjectTargetWriter>
292 createObjectTargetWriter() const override {
293 return createPPCXCOFFObjectWriter(TT.isArch64Bit());
294 }
295};
296
297} // end anonymous namespace
298
299std::optional<MCFixupKind>
300ELFPPCAsmBackend::getFixupKind(StringRef Name) const {
301 if (TT.isOSBinFormatELF()) {
302 unsigned Type;
303 if (TT.isPPC64()) {
304 Type = llvm::StringSwitch<unsigned>(Name)
305#define ELF_RELOC(X, Y) .Case(#X, Y)
306#include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
307#undef ELF_RELOC
308 .Case("BFD_RELOC_NONE", ELF::R_PPC64_NONE)
309 .Case("BFD_RELOC_16", ELF::R_PPC64_ADDR16)
310 .Case("BFD_RELOC_32", ELF::R_PPC64_ADDR32)
311 .Case("BFD_RELOC_64", ELF::R_PPC64_ADDR64)
312 .Default(-1u);
313 } else {
314 Type = llvm::StringSwitch<unsigned>(Name)
315#define ELF_RELOC(X, Y) .Case(#X, Y)
316#include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
317#undef ELF_RELOC
318 .Case("BFD_RELOC_NONE", ELF::R_PPC_NONE)
319 .Case("BFD_RELOC_16", ELF::R_PPC_ADDR16)
320 .Case("BFD_RELOC_32", ELF::R_PPC_ADDR32)
321 .Default(-1u);
322 }
323 if (Type != -1u)
324 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
325 }
326 return std::nullopt;
327}
328
330 const MCSubtargetInfo &STI,
331 const MCRegisterInfo &MRI,
332 const MCTargetOptions &Options) {
333 const Triple &TT = STI.getTargetTriple();
334 if (TT.isOSBinFormatXCOFF())
335 return new XCOFFPPCAsmBackend(T, TT);
336
337 return new ELFPPCAsmBackend(T, TT);
338}
static unsigned getFixupKindNumBytes(unsigned Kind)
The number of bytes the fixup may change.
static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target, uint64_t Value, MCContext &Ctx, const Triple &TheTriple, bool IsResolved)
static bool shouldForceRelocation(const MCFixup &Fixup)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define T
static unsigned getFixupKindNumBytes(unsigned Kind)
static uint64_t adjustFixupValue(MCContext &Ctx, const MCFixup &Fixup, unsigned Kind, uint64_t Value, const MCValue &Target, StringRef SecName, uint64_t SrcOffset)
MachineRegisterInfo & MRI
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
Generic interface to target specific assembler backends.
virtual MCFixupKindInfo getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
Context object for machine code objects.
Definition MCContext.h:84
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition MCFixup.h:65
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
StringRef getName() const
Definition MCSection.h:647
Generic base class for all target subtargets.
const Triple & getTargetTriple() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
LLVM Value Representation.
Definition Value.h:75
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ STO_PPC64_LOCAL_MASK
Definition ELF.h:232
@ fixup_ppc_brcond14abs
14-bit absolute relocation for conditional branches.
@ fixup_ppc_half16
A 16-bit fixup corresponding to lo16(_foo) or ha16(_foo) for instrs like 'li' or 'addis'.
@ NumTargetFixupKinds
@ fixup_ppc_br24_notoc
@ fixup_ppc_brcond14
14-bit PC relative relocation for conditional branches.
@ fixup_ppc_half16dq
A 16-bit fixup corresponding to lo16(_foo) with implied 3 zero bits for instrs like 'lxv'.
@ fixup_ppc_half16ds
A 14-bit fixup corresponding to lo16(_foo) with implied 2 zero bits for instrs like 'std'.
@ fixup_ppc_nofixup
Not a true fixup, but ties a symbol to a call to __tls_get_addr for the TLS general and local dynamic...
@ fixup_ppc_br24abs
24-bit absolute relocation for direct branches like 'ba' and 'bla'.
VE::Fixups getFixupKind(uint8_t S)
@ C_WEAKEXT
Definition XCOFF.h:200
bool isRelocation(MCFixupKind FixupKind)
Definition MCFixup.h:134
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:82
This is an optimization pass for GlobalISel generic memory operations.
constexpr int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition MathExtras.h:224
MCAsmBackend * createPPCAsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
constexpr MCFixupKind FirstTargetFixupKind
Definition MCFixup.h:49
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint16_t MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition MCFixup.h:22
std::unique_ptr< MCObjectTargetWriter > createPPCXCOFFObjectWriter(bool Is64Bit)
Construct a PPC XCOFF object writer.
@ Other
Any other memory.
Definition ModRef.h:68
@ FK_Data_8
A eight-byte fixup.
Definition MCFixup.h:41
@ FK_Data_1
A one-byte fixup.
Definition MCFixup.h:38
@ FK_Data_4
A four-byte fixup.
Definition MCFixup.h:40
@ FK_Data_2
A two-byte fixup.
Definition MCFixup.h:39
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
std::unique_ptr< MCObjectTargetWriter > createPPCELFObjectWriter(bool Is64Bit, uint8_t OSABI)
Construct an PPC ELF object writer.
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
endianness
Definition bit.h:71
constexpr MCFixupKind FirstLiteralRelocationKind
Definition MCFixup.h:32
Target independent information on a fixup kind.