1 //===-- RISCVRegisterInfo.cpp - RISCV Register Information ------*- C++ -*-===//
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 contains the RISCV implementation of the TargetRegisterInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVRegisterInfo.h"
14 #include "RISCV.h"
15 #include "RISCVMachineFunctionInfo.h"
16 #include "RISCVSubtarget.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/RegisterScavenging.h"
21 #include "llvm/CodeGen/TargetFrameLowering.h"
22 #include "llvm/CodeGen/TargetInstrInfo.h"
23 #include "llvm/IR/DebugInfoMetadata.h"
24 #include "llvm/Support/ErrorHandling.h"
25 
26 #define GET_REGINFO_TARGET_DESC
27 #include "RISCVGenRegisterInfo.inc"
28 
29 using namespace llvm;
30 
31 static_assert(RISCV::X1 == RISCV::X0 + 1, "Register list not consecutive");
32 static_assert(RISCV::X31 == RISCV::X0 + 31, "Register list not consecutive");
33 static_assert(RISCV::F1_H == RISCV::F0_H + 1, "Register list not consecutive");
34 static_assert(RISCV::F31_H == RISCV::F0_H + 31,
35               "Register list not consecutive");
36 static_assert(RISCV::F1_F == RISCV::F0_F + 1, "Register list not consecutive");
37 static_assert(RISCV::F31_F == RISCV::F0_F + 31,
38               "Register list not consecutive");
39 static_assert(RISCV::F1_D == RISCV::F0_D + 1, "Register list not consecutive");
40 static_assert(RISCV::F31_D == RISCV::F0_D + 31,
41               "Register list not consecutive");
42 static_assert(RISCV::V1 == RISCV::V0 + 1, "Register list not consecutive");
43 static_assert(RISCV::V31 == RISCV::V0 + 31, "Register list not consecutive");
44 
45 RISCVRegisterInfo::RISCVRegisterInfo(unsigned HwMode)
46     : RISCVGenRegisterInfo(RISCV::X1, /*DwarfFlavour*/0, /*EHFlavor*/0,
47                            /*PC*/0, HwMode) {}
48 
49 const MCPhysReg *
50 RISCVRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
51   auto &Subtarget = MF->getSubtarget<RISCVSubtarget>();
52   if (MF->getFunction().getCallingConv() == CallingConv::GHC)
53     return CSR_NoRegs_SaveList;
54   if (MF->getFunction().hasFnAttribute("interrupt")) {
55     if (Subtarget.hasStdExtD())
56       return CSR_XLEN_F64_Interrupt_SaveList;
57     if (Subtarget.hasStdExtF())
58       return CSR_XLEN_F32_Interrupt_SaveList;
59     return CSR_Interrupt_SaveList;
60   }
61 
62   switch (Subtarget.getTargetABI()) {
63   default:
64     llvm_unreachable("Unrecognized ABI");
65   case RISCVABI::ABI_ILP32:
66   case RISCVABI::ABI_LP64:
67     return CSR_ILP32_LP64_SaveList;
68   case RISCVABI::ABI_ILP32F:
69   case RISCVABI::ABI_LP64F:
70     return CSR_ILP32F_LP64F_SaveList;
71   case RISCVABI::ABI_ILP32D:
72   case RISCVABI::ABI_LP64D:
73     return CSR_ILP32D_LP64D_SaveList;
74   }
75 }
76 
77 BitVector RISCVRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
78   const RISCVFrameLowering *TFI = getFrameLowering(MF);
79   BitVector Reserved(getNumRegs());
80 
81   // Mark any registers requested to be reserved as such
82   for (size_t Reg = 0; Reg < getNumRegs(); Reg++) {
83     if (MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(Reg))
84       markSuperRegs(Reserved, Reg);
85   }
86 
87   // Use markSuperRegs to ensure any register aliases are also reserved
88   markSuperRegs(Reserved, RISCV::X0); // zero
89   markSuperRegs(Reserved, RISCV::X2); // sp
90   markSuperRegs(Reserved, RISCV::X3); // gp
91   markSuperRegs(Reserved, RISCV::X4); // tp
92   if (TFI->hasFP(MF))
93     markSuperRegs(Reserved, RISCV::X8); // fp
94   // Reserve the base register if we need to realign the stack and allocate
95   // variable-sized objects at runtime.
96   if (TFI->hasBP(MF))
97     markSuperRegs(Reserved, RISCVABI::getBPReg()); // bp
98 
99   // V registers for code generation. We handle them manually.
100   markSuperRegs(Reserved, RISCV::VL);
101   markSuperRegs(Reserved, RISCV::VTYPE);
102   markSuperRegs(Reserved, RISCV::VXSAT);
103   markSuperRegs(Reserved, RISCV::VXRM);
104 
105   // Floating point environment registers.
106   markSuperRegs(Reserved, RISCV::FRM);
107   markSuperRegs(Reserved, RISCV::FFLAGS);
108   markSuperRegs(Reserved, RISCV::FCSR);
109 
110   assert(checkAllSuperRegsMarked(Reserved));
111   return Reserved;
112 }
113 
114 bool RISCVRegisterInfo::isAsmClobberable(const MachineFunction &MF,
115                                          MCRegister PhysReg) const {
116   return !MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(PhysReg);
117 }
118 
119 bool RISCVRegisterInfo::isConstantPhysReg(MCRegister PhysReg) const {
120   return PhysReg == RISCV::X0;
121 }
122 
123 const uint32_t *RISCVRegisterInfo::getNoPreservedMask() const {
124   return CSR_NoRegs_RegMask;
125 }
126 
127 // Frame indexes representing locations of CSRs which are given a fixed location
128 // by save/restore libcalls.
129 static const std::map<unsigned, int> FixedCSRFIMap = {
130   {/*ra*/  RISCV::X1,   -1},
131   {/*s0*/  RISCV::X8,   -2},
132   {/*s1*/  RISCV::X9,   -3},
133   {/*s2*/  RISCV::X18,  -4},
134   {/*s3*/  RISCV::X19,  -5},
135   {/*s4*/  RISCV::X20,  -6},
136   {/*s5*/  RISCV::X21,  -7},
137   {/*s6*/  RISCV::X22,  -8},
138   {/*s7*/  RISCV::X23,  -9},
139   {/*s8*/  RISCV::X24,  -10},
140   {/*s9*/  RISCV::X25,  -11},
141   {/*s10*/ RISCV::X26,  -12},
142   {/*s11*/ RISCV::X27,  -13}
143 };
144 
145 bool RISCVRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
146                                              Register Reg,
147                                              int &FrameIdx) const {
148   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
149   if (!RVFI->useSaveRestoreLibCalls(MF))
150     return false;
151 
152   auto FII = FixedCSRFIMap.find(Reg);
153   if (FII == FixedCSRFIMap.end())
154     return false;
155 
156   FrameIdx = FII->second;
157   return true;
158 }
159 
160 void RISCVRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
161                                             int SPAdj, unsigned FIOperandNum,
162                                             RegScavenger *RS) const {
163   assert(SPAdj == 0 && "Unexpected non-zero SPAdj value");
164 
165   MachineInstr &MI = *II;
166   MachineFunction &MF = *MI.getParent()->getParent();
167   MachineRegisterInfo &MRI = MF.getRegInfo();
168   const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
169   DebugLoc DL = MI.getDebugLoc();
170 
171   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
172   Register FrameReg;
173   StackOffset Offset =
174       getFrameLowering(MF)->getFrameIndexReference(MF, FrameIndex, FrameReg);
175   bool IsRVVSpill = TII->isRVVSpill(MI, /*CheckFIs*/ false);
176   if (!IsRVVSpill)
177     Offset += StackOffset::getFixed(MI.getOperand(FIOperandNum + 1).getImm());
178 
179   if (!isInt<32>(Offset.getFixed())) {
180     report_fatal_error(
181         "Frame offsets outside of the signed 32-bit range not supported");
182   }
183 
184   MachineBasicBlock &MBB = *MI.getParent();
185   bool FrameRegIsKill = false;
186 
187   // If required, pre-compute the scalable factor amount which will be used in
188   // later offset computation. Since this sequence requires up to two scratch
189   // registers -- after which one is made free -- this grants us better
190   // scavenging of scratch registers as only up to two are live at one time,
191   // rather than three.
192   Register ScalableFactorRegister;
193   unsigned ScalableAdjOpc = RISCV::ADD;
194   if (Offset.getScalable()) {
195     int64_t ScalableValue = Offset.getScalable();
196     if (ScalableValue < 0) {
197       ScalableValue = -ScalableValue;
198       ScalableAdjOpc = RISCV::SUB;
199     }
200     // 1. Get vlenb && multiply vlen with the number of vector registers.
201     ScalableFactorRegister =
202         TII->getVLENFactoredAmount(MF, MBB, II, DL, ScalableValue);
203   }
204 
205   if (!isInt<12>(Offset.getFixed())) {
206     // The offset won't fit in an immediate, so use a scratch register instead
207     // Modify Offset and FrameReg appropriately
208     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
209     TII->movImm(MBB, II, DL, ScratchReg, Offset.getFixed());
210     if (MI.getOpcode() == RISCV::ADDI && !Offset.getScalable()) {
211       BuildMI(MBB, II, DL, TII->get(RISCV::ADD), MI.getOperand(0).getReg())
212         .addReg(FrameReg)
213         .addReg(ScratchReg, RegState::Kill);
214       MI.eraseFromParent();
215       return;
216     }
217     BuildMI(MBB, II, DL, TII->get(RISCV::ADD), ScratchReg)
218         .addReg(FrameReg)
219         .addReg(ScratchReg, RegState::Kill);
220     Offset = StackOffset::get(0, Offset.getScalable());
221     FrameReg = ScratchReg;
222     FrameRegIsKill = true;
223   }
224 
225   if (!Offset.getScalable()) {
226     // Offset = (fixed offset, 0)
227     MI.getOperand(FIOperandNum)
228         .ChangeToRegister(FrameReg, false, false, FrameRegIsKill);
229     if (!IsRVVSpill)
230       MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
231     else {
232       if (Offset.getFixed()) {
233         Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
234         BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), ScratchReg)
235           .addReg(FrameReg, getKillRegState(FrameRegIsKill))
236           .addImm(Offset.getFixed());
237         MI.getOperand(FIOperandNum)
238           .ChangeToRegister(ScratchReg, false, false, true);
239       }
240     }
241   } else {
242     // Offset = (fixed offset, scalable offset)
243     // Step 1, the scalable offset, has already been computed.
244     assert(ScalableFactorRegister &&
245            "Expected pre-computation of scalable factor in earlier step");
246 
247     // 2. Calculate address: FrameReg + result of multiply
248     if (MI.getOpcode() == RISCV::ADDI && !Offset.getFixed()) {
249       BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), MI.getOperand(0).getReg())
250           .addReg(FrameReg, getKillRegState(FrameRegIsKill))
251           .addReg(ScalableFactorRegister, RegState::Kill);
252       MI.eraseFromParent();
253       return;
254     }
255     Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
256     BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), VL)
257         .addReg(FrameReg, getKillRegState(FrameRegIsKill))
258         .addReg(ScalableFactorRegister, RegState::Kill);
259 
260     if (IsRVVSpill && Offset.getFixed()) {
261       // Scalable load/store has no immediate argument. We need to add the
262       // fixed part into the load/store base address.
263       BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), VL)
264           .addReg(VL)
265           .addImm(Offset.getFixed());
266     }
267 
268     // 3. Replace address register with calculated address register
269     MI.getOperand(FIOperandNum).ChangeToRegister(VL, false, false, true);
270     if (!IsRVVSpill)
271       MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
272   }
273 
274   auto ZvlssegInfo = TII->isRVVSpillForZvlsseg(MI.getOpcode());
275   if (ZvlssegInfo) {
276     Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
277     BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), VL);
278     uint32_t ShiftAmount = Log2_32(ZvlssegInfo->second);
279     if (ShiftAmount != 0)
280       BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), VL)
281           .addReg(VL)
282           .addImm(ShiftAmount);
283     // The last argument of pseudo spilling opcode for zvlsseg is the length of
284     // one element of zvlsseg types. For example, for vint32m2x2_t, it will be
285     // the length of vint32m2_t.
286     MI.getOperand(FIOperandNum + 1).ChangeToRegister(VL, /*isDef=*/false);
287   }
288 }
289 
290 Register RISCVRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
291   const TargetFrameLowering *TFI = getFrameLowering(MF);
292   return TFI->hasFP(MF) ? RISCV::X8 : RISCV::X2;
293 }
294 
295 const uint32_t *
296 RISCVRegisterInfo::getCallPreservedMask(const MachineFunction & MF,
297                                         CallingConv::ID CC) const {
298   auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
299 
300   if (CC == CallingConv::GHC)
301     return CSR_NoRegs_RegMask;
302   switch (Subtarget.getTargetABI()) {
303   default:
304     llvm_unreachable("Unrecognized ABI");
305   case RISCVABI::ABI_ILP32:
306   case RISCVABI::ABI_LP64:
307     return CSR_ILP32_LP64_RegMask;
308   case RISCVABI::ABI_ILP32F:
309   case RISCVABI::ABI_LP64F:
310     return CSR_ILP32F_LP64F_RegMask;
311   case RISCVABI::ABI_ILP32D:
312   case RISCVABI::ABI_LP64D:
313     return CSR_ILP32D_LP64D_RegMask;
314   }
315 }
316 
317 const TargetRegisterClass *
318 RISCVRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
319                                              const MachineFunction &) const {
320   if (RC == &RISCV::VMV0RegClass)
321     return &RISCV::VRRegClass;
322   return RC;
323 }
324 
325 void RISCVRegisterInfo::getOffsetOpcodes(const StackOffset &Offset,
326                                          SmallVectorImpl<uint64_t> &Ops) const {
327   // VLENB is the length of a vector register in bytes. We use <vscale x 8 x i8>
328   // to represent one vector register. The dwarf offset is
329   // VLENB * scalable_offset / 8.
330   assert(Offset.getScalable() % 8 == 0 && "Invalid frame offset");
331 
332   // Add fixed-sized offset using existing DIExpression interface.
333   DIExpression::appendOffset(Ops, Offset.getFixed());
334 
335   unsigned VLENB = getDwarfRegNum(RISCV::VLENB, true);
336   int64_t VLENBSized = Offset.getScalable() / 8;
337   if (VLENBSized > 0) {
338     Ops.push_back(dwarf::DW_OP_constu);
339     Ops.push_back(VLENBSized);
340     Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
341     Ops.push_back(dwarf::DW_OP_mul);
342     Ops.push_back(dwarf::DW_OP_plus);
343   } else if (VLENBSized < 0) {
344     Ops.push_back(dwarf::DW_OP_constu);
345     Ops.push_back(-VLENBSized);
346     Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
347     Ops.push_back(dwarf::DW_OP_mul);
348     Ops.push_back(dwarf::DW_OP_minus);
349   }
350 }
351