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