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