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 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "mccodeemitter"
33 
34 STATISTIC(MCNumEmitted, "Number of MC instructions emitted");
35 
36 MCCodeEmitter *llvm::createPPCMCCodeEmitter(const MCInstrInfo &MCII,
37                                             const MCRegisterInfo &MRI,
38                                             MCContext &Ctx) {
39   return new PPCMCCodeEmitter(MCII, Ctx);
40 }
41 
42 unsigned PPCMCCodeEmitter::
43 getDirectBrEncoding(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 
57 unsigned 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 
69 unsigned PPCMCCodeEmitter::
70 getAbsDirectBrEncoding(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 
82 unsigned PPCMCCodeEmitter::
83 getAbsCondBrEncoding(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 
95 unsigned 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 
107 uint64_t
108 PPCMCCodeEmitter::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(IsLittleEndian? 0 : 1, MO.getExpr(),
117                                    (MCFixupKind)PPC::fixup_ppc_pcrel34));
118   return 0;
119 }
120 
121 unsigned 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 
139 unsigned 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 
157 unsigned 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 
178 uint64_t
179 PPCMCCodeEmitter::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(IsLittleEndian ? 0 : 1, Expr,
221                         static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
222     // There is no offset to return so just return 0.
223     return 0;
224   }
225   case MCExpr::Binary: {
226     // Relocation plus some offset.
227     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
228     assert(BE->getOpcode() == MCBinaryExpr::Add &&
229            "Binary expression opcode must be an add.");
230 
231     const MCExpr *LHS = BE->getLHS();
232     const MCExpr *RHS = BE->getRHS();
233 
234     // Need to check in both directions. Reloc+Offset and Offset+Reloc.
235     if (LHS->getKind() != MCExpr::SymbolRef)
236       std::swap(LHS, RHS);
237 
238     if (LHS->getKind() != MCExpr::SymbolRef ||
239         RHS->getKind() != MCExpr::Constant)
240       llvm_unreachable("Expecting to have one constant and one relocation.");
241 
242     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(LHS);
243     const MCConstantExpr *CE = cast<MCConstantExpr>(RHS);
244 
245     // Currently these are the only valid PCRelative Relocations.
246     assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
247             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL) &&
248            "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL");
249     // Generate the fixup for the relocation.
250     Fixups.push_back(
251         MCFixup::create(IsLittleEndian ? 0 : 1, Expr,
252                         static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
253     assert(isInt<34>(CE->getValue()) && "Value must fit in 34 bits.");
254     // Return the offset that should be added to the relocation by the linker.
255     return (CE->getValue() & 0x3FFFFFFFFUL) | RegBits;
256     }
257   }
258 }
259 
260 uint64_t
261 PPCMCCodeEmitter::getMemRI34Encoding(const MCInst &MI, unsigned OpNo,
262                                      SmallVectorImpl<MCFixup> &Fixups,
263                                      const MCSubtargetInfo &STI) const {
264   // Encode (imm, reg) as a memri34, which has the low 34-bits as the
265   // displacement and the next 5 bits as the register #.
266   assert(MI.getOperand(OpNo + 1).isReg() && "Expecting a register.");
267   uint64_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI)
268                      << 34;
269   const MCOperand &MO = MI.getOperand(OpNo);
270   return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
271 }
272 
273 unsigned PPCMCCodeEmitter::getSPE8DisEncoding(const MCInst &MI, unsigned OpNo,
274                                               SmallVectorImpl<MCFixup> &Fixups,
275                                               const MCSubtargetInfo &STI)
276                                               const {
277   // Encode (imm, reg) as a spe8dis, which has the low 5-bits of (imm / 8)
278   // as the displacement and the next 5 bits as the register #.
279   assert(MI.getOperand(OpNo+1).isReg());
280   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
281 
282   const MCOperand &MO = MI.getOperand(OpNo);
283   assert(MO.isImm());
284   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 3;
285   return reverseBits(Imm | RegBits) >> 22;
286 }
287 
288 unsigned PPCMCCodeEmitter::getSPE4DisEncoding(const MCInst &MI, unsigned OpNo,
289                                               SmallVectorImpl<MCFixup> &Fixups,
290                                               const MCSubtargetInfo &STI)
291                                               const {
292   // Encode (imm, reg) as a spe4dis, which has the low 5-bits of (imm / 4)
293   // as the displacement and the next 5 bits as the register #.
294   assert(MI.getOperand(OpNo+1).isReg());
295   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
296 
297   const MCOperand &MO = MI.getOperand(OpNo);
298   assert(MO.isImm());
299   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 2;
300   return reverseBits(Imm | RegBits) >> 22;
301 }
302 
303 unsigned PPCMCCodeEmitter::getSPE2DisEncoding(const MCInst &MI, unsigned OpNo,
304                                               SmallVectorImpl<MCFixup> &Fixups,
305                                               const MCSubtargetInfo &STI)
306                                               const {
307   // Encode (imm, reg) as a spe2dis, which has the low 5-bits of (imm / 2)
308   // as the displacement and the next 5 bits as the register #.
309   assert(MI.getOperand(OpNo+1).isReg());
310   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
311 
312   const MCOperand &MO = MI.getOperand(OpNo);
313   assert(MO.isImm());
314   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 1;
315   return reverseBits(Imm | RegBits) >> 22;
316 }
317 
318 unsigned PPCMCCodeEmitter::getTLSRegEncoding(const MCInst &MI, unsigned OpNo,
319                                        SmallVectorImpl<MCFixup> &Fixups,
320                                        const MCSubtargetInfo &STI) const {
321   const MCOperand &MO = MI.getOperand(OpNo);
322   if (MO.isReg()) return getMachineOpValue(MI, MO, Fixups, STI);
323 
324   // Add a fixup for the TLS register, which simply provides a relocation
325   // hint to the linker that this statement is part of a relocation sequence.
326   // Return the thread-pointer register's encoding.
327   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
328                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
329   const Triple &TT = STI.getTargetTriple();
330   bool isPPC64 = TT.isPPC64();
331   return CTX.getRegisterInfo()->getEncodingValue(isPPC64 ? PPC::X13 : PPC::R2);
332 }
333 
334 unsigned PPCMCCodeEmitter::getTLSCallEncoding(const MCInst &MI, unsigned OpNo,
335                                        SmallVectorImpl<MCFixup> &Fixups,
336                                        const MCSubtargetInfo &STI) const {
337   // For special TLS calls, we need two fixups; one for the branch target
338   // (__tls_get_addr), which we create via getDirectBrEncoding as usual,
339   // and one for the TLSGD or TLSLD symbol, which is emitted here.
340   const MCOperand &MO = MI.getOperand(OpNo+1);
341   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
342                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
343   return getDirectBrEncoding(MI, OpNo, Fixups, STI);
344 }
345 
346 unsigned PPCMCCodeEmitter::
347 get_crbitm_encoding(const MCInst &MI, unsigned OpNo,
348                     SmallVectorImpl<MCFixup> &Fixups,
349                     const MCSubtargetInfo &STI) const {
350   const MCOperand &MO = MI.getOperand(OpNo);
351   assert((MI.getOpcode() == PPC::MTOCRF || MI.getOpcode() == PPC::MTOCRF8 ||
352           MI.getOpcode() == PPC::MFOCRF || MI.getOpcode() == PPC::MFOCRF8) &&
353          (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7));
354   return 0x80 >> CTX.getRegisterInfo()->getEncodingValue(MO.getReg());
355 }
356 
357 // Get the index for this operand in this instruction. This is needed for
358 // computing the register number in PPCInstrInfo::getRegNumForOperand() for
359 // any instructions that use a different numbering scheme for registers in
360 // different operands.
361 static unsigned getOpIdxForMO(const MCInst &MI, const MCOperand &MO) {
362   for (unsigned i = 0; i < MI.getNumOperands(); i++) {
363     const MCOperand &Op = MI.getOperand(i);
364     if (&Op == &MO)
365       return i;
366   }
367   llvm_unreachable("This operand is not part of this instruction");
368   return ~0U; // Silence any warnings about no return.
369 }
370 
371 uint64_t PPCMCCodeEmitter::
372 getMachineOpValue(const MCInst &MI, const MCOperand &MO,
373                   SmallVectorImpl<MCFixup> &Fixups,
374                   const MCSubtargetInfo &STI) const {
375   if (MO.isReg()) {
376     // MTOCRF/MFOCRF should go through get_crbitm_encoding for the CR operand.
377     // The GPR operand should come through here though.
378     assert((MI.getOpcode() != PPC::MTOCRF && MI.getOpcode() != PPC::MTOCRF8 &&
379             MI.getOpcode() != PPC::MFOCRF && MI.getOpcode() != PPC::MFOCRF8) ||
380            MO.getReg() < PPC::CR0 || MO.getReg() > PPC::CR7);
381     unsigned OpNo = getOpIdxForMO(MI, MO);
382     unsigned Reg =
383       PPCInstrInfo::getRegNumForOperand(MCII.get(MI.getOpcode()),
384                                         MO.getReg(), OpNo);
385     return CTX.getRegisterInfo()->getEncodingValue(Reg);
386   }
387 
388   assert(MO.isImm() &&
389          "Relocation required in an instruction that we cannot encode!");
390   return MO.getImm();
391 }
392 
393 void PPCMCCodeEmitter::encodeInstruction(
394     const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
395     const MCSubtargetInfo &STI) const {
396   verifyInstructionPredicates(MI,
397                               computeAvailableFeatures(STI.getFeatureBits()));
398 
399   uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
400 
401   // Output the constant in big/little endian byte order.
402   unsigned Size = getInstSizeInBytes(MI);
403   support::endianness E = IsLittleEndian ? support::little : support::big;
404   switch (Size) {
405   case 0:
406     break;
407   case 4:
408     support::endian::write<uint32_t>(OS, Bits, E);
409     break;
410   case 8:
411     // If we emit a pair of instructions, the first one is
412     // always in the top 32 bits, even on little-endian.
413     support::endian::write<uint32_t>(OS, Bits >> 32, E);
414     support::endian::write<uint32_t>(OS, Bits, E);
415     break;
416   default:
417     llvm_unreachable("Invalid instruction size");
418   }
419 
420   ++MCNumEmitted; // Keep track of the # of mi's emitted.
421 }
422 
423 // Get the number of bytes used to encode the given MCInst.
424 unsigned PPCMCCodeEmitter::getInstSizeInBytes(const MCInst &MI) const {
425   unsigned Opcode = MI.getOpcode();
426   const MCInstrDesc &Desc = MCII.get(Opcode);
427   return Desc.getSize();
428 }
429 
430 bool PPCMCCodeEmitter::isPrefixedInstruction(const MCInst &MI) const {
431   unsigned Opcode = MI.getOpcode();
432   const PPCInstrInfo *InstrInfo = static_cast<const PPCInstrInfo*>(&MCII);
433   return InstrInfo->isPrefixed(Opcode);
434 }
435 
436 #define ENABLE_INSTR_PREDICATE_VERIFIER
437 #include "PPCGenMCCodeEmitter.inc"
438