1//===-- PPCMCCodeEmitter.cpp - Convert PPC code to machine code -----------===//
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 the PPCMCCodeEmitter class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MCTargetDesc/PPCFixupKinds.h"
14#include "PPCInstrInfo.h"
15#include "PPCMCCodeEmitter.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/MC/MCFixup.h"
20#include "llvm/MC/MCInstrDesc.h"
21#include "llvm/MC/MCRegisterInfo.h"
22#include "llvm/Support/Endian.h"
23#include "llvm/Support/EndianStream.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/raw_ostream.h"
27#include <cassert>
28#include <cstdint>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "mccodeemitter"
33
34STATISTIC(MCNumEmitted, "Number of MC instructions emitted");
35
36MCCodeEmitter *llvm::createPPCMCCodeEmitter(const MCInstrInfo &MCII,
37                                            const MCRegisterInfo &MRI,
38                                            MCContext &Ctx) {
39  return new PPCMCCodeEmitter(MCII, Ctx);
40}
41
42unsigned PPCMCCodeEmitter::
43getDirectBrEncoding(const MCInst &MI, unsigned OpNo,
44                    SmallVectorImpl<MCFixup> &Fixups,
45                    const MCSubtargetInfo &STI) const {
46  const MCOperand &MO = MI.getOperand(OpNo);
47  if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
48
49  // Add a fixup for the branch target.
50  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
51                                   ((MI.getOpcode() == PPC::BL8_NOTOC)
52                                        ? (MCFixupKind)PPC::fixup_ppc_br24_notoc
53                                        : (MCFixupKind)PPC::fixup_ppc_br24)));
54  return 0;
55}
56
57unsigned PPCMCCodeEmitter::getCondBrEncoding(const MCInst &MI, unsigned OpNo,
58                                     SmallVectorImpl<MCFixup> &Fixups,
59                                     const MCSubtargetInfo &STI) const {
60  const MCOperand &MO = MI.getOperand(OpNo);
61  if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
62
63  // Add a fixup for the branch target.
64  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
65                                   (MCFixupKind)PPC::fixup_ppc_brcond14));
66  return 0;
67}
68
69unsigned PPCMCCodeEmitter::
70getAbsDirectBrEncoding(const MCInst &MI, unsigned OpNo,
71                       SmallVectorImpl<MCFixup> &Fixups,
72                       const MCSubtargetInfo &STI) const {
73  const MCOperand &MO = MI.getOperand(OpNo);
74  if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
75
76  // Add a fixup for the branch target.
77  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
78                                   (MCFixupKind)PPC::fixup_ppc_br24abs));
79  return 0;
80}
81
82unsigned PPCMCCodeEmitter::
83getAbsCondBrEncoding(const MCInst &MI, unsigned OpNo,
84                     SmallVectorImpl<MCFixup> &Fixups,
85                     const MCSubtargetInfo &STI) const {
86  const MCOperand &MO = MI.getOperand(OpNo);
87  if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
88
89  // Add a fixup for the branch target.
90  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
91                                   (MCFixupKind)PPC::fixup_ppc_brcond14abs));
92  return 0;
93}
94
95unsigned PPCMCCodeEmitter::getImm16Encoding(const MCInst &MI, unsigned OpNo,
96                                       SmallVectorImpl<MCFixup> &Fixups,
97                                       const MCSubtargetInfo &STI) const {
98  const MCOperand &MO = MI.getOperand(OpNo);
99  if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
100
101  // Add a fixup for the immediate field.
102  Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
103                                   (MCFixupKind)PPC::fixup_ppc_half16));
104  return 0;
105}
106
107uint64_t
108PPCMCCodeEmitter::getImm34Encoding(const MCInst &MI, unsigned OpNo,
109                                   SmallVectorImpl<MCFixup> &Fixups,
110                                   const MCSubtargetInfo &STI) const {
111  const MCOperand &MO = MI.getOperand(OpNo);
112  if (MO.isReg() || MO.isImm())
113    return getMachineOpValue(MI, MO, Fixups, STI);
114
115  // Add a fixup for the immediate field.
116  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
117                                   (MCFixupKind)PPC::fixup_ppc_pcrel34));
118  return 0;
119}
120
121unsigned PPCMCCodeEmitter::getMemRIEncoding(const MCInst &MI, unsigned OpNo,
122                                            SmallVectorImpl<MCFixup> &Fixups,
123                                            const MCSubtargetInfo &STI) const {
124  // Encode (imm, reg) as a memri, which has the low 16-bits as the
125  // displacement and the next 5 bits as the register #.
126  assert(MI.getOperand(OpNo+1).isReg());
127  unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 16;
128
129  const MCOperand &MO = MI.getOperand(OpNo);
130  if (MO.isImm())
131    return (getMachineOpValue(MI, MO, Fixups, STI) & 0xFFFF) | RegBits;
132
133  // Add a fixup for the displacement field.
134  Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
135                                   (MCFixupKind)PPC::fixup_ppc_half16));
136  return RegBits;
137}
138
139unsigned PPCMCCodeEmitter::getMemRIXEncoding(const MCInst &MI, unsigned OpNo,
140                                       SmallVectorImpl<MCFixup> &Fixups,
141                                       const MCSubtargetInfo &STI) const {
142  // Encode (imm, reg) as a memrix, which has the low 14-bits as the
143  // displacement and the next 5 bits as the register #.
144  assert(MI.getOperand(OpNo+1).isReg());
145  unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 14;
146
147  const MCOperand &MO = MI.getOperand(OpNo);
148  if (MO.isImm())
149    return ((getMachineOpValue(MI, MO, Fixups, STI) >> 2) & 0x3FFF) | RegBits;
150
151  // Add a fixup for the displacement field.
152  Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
153                                   (MCFixupKind)PPC::fixup_ppc_half16ds));
154  return RegBits;
155}
156
157unsigned PPCMCCodeEmitter::getMemRIX16Encoding(const MCInst &MI, unsigned OpNo,
158                                       SmallVectorImpl<MCFixup> &Fixups,
159                                       const MCSubtargetInfo &STI) const {
160  // Encode (imm, reg) as a memrix16, which has the low 12-bits as the
161  // displacement and the next 5 bits as the register #.
162  assert(MI.getOperand(OpNo+1).isReg());
163  unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 12;
164
165  const MCOperand &MO = MI.getOperand(OpNo);
166  if (MO.isImm()) {
167    assert(!(MO.getImm() % 16) &&
168           "Expecting an immediate that is a multiple of 16");
169    return ((getMachineOpValue(MI, MO, Fixups, STI) >> 4) & 0xFFF) | RegBits;
170  }
171
172  // Otherwise add a fixup for the displacement field.
173  Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
174                                   (MCFixupKind)PPC::fixup_ppc_half16ds));
175  return RegBits;
176}
177
178uint64_t
179PPCMCCodeEmitter::getMemRI34PCRelEncoding(const MCInst &MI, unsigned OpNo,
180                                          SmallVectorImpl<MCFixup> &Fixups,
181                                          const MCSubtargetInfo &STI) const {
182  // Encode the PCRelative version of memri34: imm34(r0).
183  // In the PC relative version the register for the address must be zero.
184  // The 34 bit immediate can fall into one of three cases:
185  // 1) It is a relocation to be filled in by the linker represented as:
186  //    (MCExpr::SymbolRef)
187  // 2) It is a relocation + SignedOffset represented as:
188  //    (MCExpr::Binary(MCExpr::SymbolRef + MCExpr::Constant))
189  // 3) It is a known value at compile time.
190
191  // Make sure that the register is a zero as expected.
192  assert(MI.getOperand(OpNo + 1).isImm() && "Expecting an immediate.");
193  uint64_t RegBits =
194    getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI) << 34;
195  assert(RegBits == 0 && "Operand must be 0.");
196
197  // If this is not a MCExpr then we are in case 3) and we are dealing with
198  // a value known at compile time, not a relocation.
199  const MCOperand &MO = MI.getOperand(OpNo);
200  if (!MO.isExpr())
201    return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
202
203  // At this point in the function it is known that MO is of type MCExpr.
204  // Therefore we are dealing with either case 1) a symbol ref or
205  // case 2) a symbol ref plus a constant.
206  const MCExpr *Expr = MO.getExpr();
207  switch (Expr->getKind()) {
208  default:
209    llvm_unreachable("Unsupported MCExpr for getMemRI34PCRelEncoding.");
210  case MCExpr::SymbolRef: {
211    // Relocation alone.
212    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
213    (void)SRE;
214    // Currently these are the only valid PCRelative Relocations.
215    assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
216            SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL) &&
217           "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL");
218    // Generate the fixup for the relocation.
219    Fixups.push_back(
220        MCFixup::create(0, Expr,
221                        static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
222    // Put zero in the location of the immediate. The linker will fill in the
223    // correct value based on the relocation.
224    return 0;
225  }
226  case MCExpr::Binary: {
227    // Relocation plus some offset.
228    const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
229    assert(BE->getOpcode() == MCBinaryExpr::Add &&
230           "Binary expression opcode must be an add.");
231
232    const MCExpr *LHS = BE->getLHS();
233    const MCExpr *RHS = BE->getRHS();
234
235    // Need to check in both directions. Reloc+Offset and Offset+Reloc.
236    if (LHS->getKind() != MCExpr::SymbolRef)
237      std::swap(LHS, RHS);
238
239    if (LHS->getKind() != MCExpr::SymbolRef ||
240        RHS->getKind() != MCExpr::Constant)
241      llvm_unreachable("Expecting to have one constant and one relocation.");
242
243    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(LHS);
244    (void)SRE;
245    assert(isInt<34>(cast<MCConstantExpr>(RHS)->getValue()) &&
246           "Value must fit in 34 bits.");
247
248    // Currently these are the only valid PCRelative Relocations.
249    assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
250            SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL) &&
251           "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL");
252    // Generate the fixup for the relocation.
253    Fixups.push_back(
254        MCFixup::create(0, Expr,
255                        static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
256    // Put zero in the location of the immediate. The linker will fill in the
257    // correct value based on the relocation.
258    return 0;
259    }
260  }
261}
262
263uint64_t
264PPCMCCodeEmitter::getMemRI34Encoding(const MCInst &MI, unsigned OpNo,
265                                     SmallVectorImpl<MCFixup> &Fixups,
266                                     const MCSubtargetInfo &STI) const {
267  // Encode (imm, reg) as a memri34, which has the low 34-bits as the
268  // displacement and the next 5 bits as the register #.
269  assert(MI.getOperand(OpNo + 1).isReg() && "Expecting a register.");
270  uint64_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI)
271                     << 34;
272  const MCOperand &MO = MI.getOperand(OpNo);
273  return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
274}
275
276unsigned PPCMCCodeEmitter::getSPE8DisEncoding(const MCInst &MI, unsigned OpNo,
277                                              SmallVectorImpl<MCFixup> &Fixups,
278                                              const MCSubtargetInfo &STI)
279                                              const {
280  // Encode (imm, reg) as a spe8dis, which has the low 5-bits of (imm / 8)
281  // as the displacement and the next 5 bits as the register #.
282  assert(MI.getOperand(OpNo+1).isReg());
283  uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
284
285  const MCOperand &MO = MI.getOperand(OpNo);
286  assert(MO.isImm());
287  uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 3;
288  return reverseBits(Imm | RegBits) >> 22;
289}
290
291unsigned PPCMCCodeEmitter::getSPE4DisEncoding(const MCInst &MI, unsigned OpNo,
292                                              SmallVectorImpl<MCFixup> &Fixups,
293                                              const MCSubtargetInfo &STI)
294                                              const {
295  // Encode (imm, reg) as a spe4dis, which has the low 5-bits of (imm / 4)
296  // as the displacement and the next 5 bits as the register #.
297  assert(MI.getOperand(OpNo+1).isReg());
298  uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
299
300  const MCOperand &MO = MI.getOperand(OpNo);
301  assert(MO.isImm());
302  uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 2;
303  return reverseBits(Imm | RegBits) >> 22;
304}
305
306unsigned PPCMCCodeEmitter::getSPE2DisEncoding(const MCInst &MI, unsigned OpNo,
307                                              SmallVectorImpl<MCFixup> &Fixups,
308                                              const MCSubtargetInfo &STI)
309                                              const {
310  // Encode (imm, reg) as a spe2dis, which has the low 5-bits of (imm / 2)
311  // as the displacement and the next 5 bits as the register #.
312  assert(MI.getOperand(OpNo+1).isReg());
313  uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
314
315  const MCOperand &MO = MI.getOperand(OpNo);
316  assert(MO.isImm());
317  uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 1;
318  return reverseBits(Imm | RegBits) >> 22;
319}
320
321unsigned PPCMCCodeEmitter::getTLSRegEncoding(const MCInst &MI, unsigned OpNo,
322                                       SmallVectorImpl<MCFixup> &Fixups,
323                                       const MCSubtargetInfo &STI) const {
324  const MCOperand &MO = MI.getOperand(OpNo);
325  if (MO.isReg()) return getMachineOpValue(MI, MO, Fixups, STI);
326
327  // Add a fixup for the TLS register, which simply provides a relocation
328  // hint to the linker that this statement is part of a relocation sequence.
329  // Return the thread-pointer register's encoding.
330  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
331                                   (MCFixupKind)PPC::fixup_ppc_nofixup));
332  const Triple &TT = STI.getTargetTriple();
333  bool isPPC64 = TT.isPPC64();
334  return CTX.getRegisterInfo()->getEncodingValue(isPPC64 ? PPC::X13 : PPC::R2);
335}
336
337unsigned PPCMCCodeEmitter::getTLSCallEncoding(const MCInst &MI, unsigned OpNo,
338                                       SmallVectorImpl<MCFixup> &Fixups,
339                                       const MCSubtargetInfo &STI) const {
340  // For special TLS calls, we need two fixups; one for the branch target
341  // (__tls_get_addr), which we create via getDirectBrEncoding as usual,
342  // and one for the TLSGD or TLSLD symbol, which is emitted here.
343  const MCOperand &MO = MI.getOperand(OpNo+1);
344  Fixups.push_back(MCFixup::create(0, MO.getExpr(),
345                                   (MCFixupKind)PPC::fixup_ppc_nofixup));
346  return getDirectBrEncoding(MI, OpNo, Fixups, STI);
347}
348
349unsigned PPCMCCodeEmitter::
350get_crbitm_encoding(const MCInst &MI, unsigned OpNo,
351                    SmallVectorImpl<MCFixup> &Fixups,
352                    const MCSubtargetInfo &STI) const {
353  const MCOperand &MO = MI.getOperand(OpNo);
354  assert((MI.getOpcode() == PPC::MTOCRF || MI.getOpcode() == PPC::MTOCRF8 ||
355          MI.getOpcode() == PPC::MFOCRF || MI.getOpcode() == PPC::MFOCRF8) &&
356         (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7));
357  return 0x80 >> CTX.getRegisterInfo()->getEncodingValue(MO.getReg());
358}
359
360// Get the index for this operand in this instruction. This is needed for
361// computing the register number in PPCInstrInfo::getRegNumForOperand() for
362// any instructions that use a different numbering scheme for registers in
363// different operands.
364static unsigned getOpIdxForMO(const MCInst &MI, const MCOperand &MO) {
365  for (unsigned i = 0; i < MI.getNumOperands(); i++) {
366    const MCOperand &Op = MI.getOperand(i);
367    if (&Op == &MO)
368      return i;
369  }
370  llvm_unreachable("This operand is not part of this instruction");
371  return ~0U; // Silence any warnings about no return.
372}
373
374uint64_t PPCMCCodeEmitter::
375getMachineOpValue(const MCInst &MI, const MCOperand &MO,
376                  SmallVectorImpl<MCFixup> &Fixups,
377                  const MCSubtargetInfo &STI) const {
378  if (MO.isReg()) {
379    // MTOCRF/MFOCRF should go through get_crbitm_encoding for the CR operand.
380    // The GPR operand should come through here though.
381    assert((MI.getOpcode() != PPC::MTOCRF && MI.getOpcode() != PPC::MTOCRF8 &&
382            MI.getOpcode() != PPC::MFOCRF && MI.getOpcode() != PPC::MFOCRF8) ||
383           MO.getReg() < PPC::CR0 || MO.getReg() > PPC::CR7);
384    unsigned OpNo = getOpIdxForMO(MI, MO);
385    unsigned Reg =
386      PPCInstrInfo::getRegNumForOperand(MCII.get(MI.getOpcode()),
387                                        MO.getReg(), OpNo);
388    return CTX.getRegisterInfo()->getEncodingValue(Reg);
389  }
390
391  assert(MO.isImm() &&
392         "Relocation required in an instruction that we cannot encode!");
393  return MO.getImm();
394}
395
396void PPCMCCodeEmitter::encodeInstruction(
397    const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
398    const MCSubtargetInfo &STI) const {
399  verifyInstructionPredicates(MI,
400                              computeAvailableFeatures(STI.getFeatureBits()));
401
402  uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
403
404  // Output the constant in big/little endian byte order.
405  unsigned Size = getInstSizeInBytes(MI);
406  support::endianness E = IsLittleEndian ? support::little : support::big;
407  switch (Size) {
408  case 0:
409    break;
410  case 4:
411    support::endian::write<uint32_t>(OS, Bits, E);
412    break;
413  case 8:
414    // If we emit a pair of instructions, the first one is
415    // always in the top 32 bits, even on little-endian.
416    support::endian::write<uint32_t>(OS, Bits >> 32, E);
417    support::endian::write<uint32_t>(OS, Bits, E);
418    break;
419  default:
420    llvm_unreachable("Invalid instruction size");
421  }
422
423  ++MCNumEmitted; // Keep track of the # of mi's emitted.
424}
425
426// Get the number of bytes used to encode the given MCInst.
427unsigned PPCMCCodeEmitter::getInstSizeInBytes(const MCInst &MI) const {
428  unsigned Opcode = MI.getOpcode();
429  const MCInstrDesc &Desc = MCII.get(Opcode);
430  return Desc.getSize();
431}
432
433bool PPCMCCodeEmitter::isPrefixedInstruction(const MCInst &MI) const {
434  unsigned Opcode = MI.getOpcode();
435  const PPCInstrInfo *InstrInfo = static_cast<const PPCInstrInfo*>(&MCII);
436  return InstrInfo->isPrefixed(Opcode);
437}
438
439#define ENABLE_INSTR_PREDICATE_VERIFIER
440#include "PPCGenMCCodeEmitter.inc"
441