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