1 //===- AArch64RegisterInfo.cpp - AArch64 Register Information -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the AArch64 implementation of the TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AArch64RegisterInfo.h"
16 #include "AArch64FrameLowering.h"
17 #include "AArch64InstrInfo.h"
18 #include "AArch64MachineFunctionInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/RegisterScavenging.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/CodeGen/TargetFrameLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 
32 using namespace llvm;
33 
34 #define GET_REGINFO_TARGET_DESC
35 #include "AArch64GenRegisterInfo.inc"
36 
37 AArch64RegisterInfo::AArch64RegisterInfo(const Triple &TT)
38     : AArch64GenRegisterInfo(AArch64::LR), TT(TT) {
39   AArch64_MC::initLLVMToCVRegMapping(this);
40 }
41 
42 const MCPhysReg *
43 AArch64RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
44   assert(MF && "Invalid MachineFunction pointer.");
45   if (MF->getFunction().getCallingConv() == CallingConv::GHC)
46     // GHC set of callee saved regs is empty as all those regs are
47     // used for passing STG regs around
48     return CSR_AArch64_NoRegs_SaveList;
49   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg)
50     return CSR_AArch64_AllRegs_SaveList;
51   if (MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS)
52     return MF->getInfo<AArch64FunctionInfo>()->isSplitCSR() ?
53            CSR_AArch64_CXX_TLS_Darwin_PE_SaveList :
54            CSR_AArch64_CXX_TLS_Darwin_SaveList;
55   if (MF->getSubtarget<AArch64Subtarget>().getTargetLowering()
56           ->supportSwiftError() &&
57       MF->getFunction().getAttributes().hasAttrSomewhere(
58           Attribute::SwiftError))
59     return CSR_AArch64_AAPCS_SwiftError_SaveList;
60   if (MF->getFunction().getCallingConv() == CallingConv::PreserveMost)
61     return CSR_AArch64_RT_MostRegs_SaveList;
62   else
63     return CSR_AArch64_AAPCS_SaveList;
64 }
65 
66 const MCPhysReg *AArch64RegisterInfo::getCalleeSavedRegsViaCopy(
67     const MachineFunction *MF) const {
68   assert(MF && "Invalid MachineFunction pointer.");
69   if (MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS &&
70       MF->getInfo<AArch64FunctionInfo>()->isSplitCSR())
71     return CSR_AArch64_CXX_TLS_Darwin_ViaCopy_SaveList;
72   return nullptr;
73 }
74 
75 const uint32_t *
76 AArch64RegisterInfo::getCallPreservedMask(const MachineFunction &MF,
77                                           CallingConv::ID CC) const {
78   if (CC == CallingConv::GHC)
79     // This is academic because all GHC calls are (supposed to be) tail calls
80     return CSR_AArch64_NoRegs_RegMask;
81   if (CC == CallingConv::AnyReg)
82     return CSR_AArch64_AllRegs_RegMask;
83   if (CC == CallingConv::CXX_FAST_TLS)
84     return CSR_AArch64_CXX_TLS_Darwin_RegMask;
85   if (MF.getSubtarget<AArch64Subtarget>().getTargetLowering()
86           ->supportSwiftError() &&
87       MF.getFunction().getAttributes().hasAttrSomewhere(Attribute::SwiftError))
88     return CSR_AArch64_AAPCS_SwiftError_RegMask;
89   if (CC == CallingConv::PreserveMost)
90     return CSR_AArch64_RT_MostRegs_RegMask;
91   else
92     return CSR_AArch64_AAPCS_RegMask;
93 }
94 
95 const uint32_t *AArch64RegisterInfo::getTLSCallPreservedMask() const {
96   if (TT.isOSDarwin())
97     return CSR_AArch64_TLS_Darwin_RegMask;
98 
99   assert(TT.isOSBinFormatELF() && "Invalid target");
100   return CSR_AArch64_TLS_ELF_RegMask;
101 }
102 
103 const uint32_t *
104 AArch64RegisterInfo::getThisReturnPreservedMask(const MachineFunction &MF,
105                                                 CallingConv::ID CC) const {
106   // This should return a register mask that is the same as that returned by
107   // getCallPreservedMask but that additionally preserves the register used for
108   // the first i64 argument (which must also be the register used to return a
109   // single i64 return value)
110   //
111   // In case that the calling convention does not use the same register for
112   // both, the function should return NULL (does not currently apply)
113   assert(CC != CallingConv::GHC && "should not be GHC calling convention.");
114   return CSR_AArch64_AAPCS_ThisReturn_RegMask;
115 }
116 
117 BitVector
118 AArch64RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
119   const AArch64FrameLowering *TFI = getFrameLowering(MF);
120 
121   // FIXME: avoid re-calculating this every time.
122   BitVector Reserved(getNumRegs());
123   markSuperRegs(Reserved, AArch64::WSP);
124   markSuperRegs(Reserved, AArch64::WZR);
125 
126   if (TFI->hasFP(MF) || TT.isOSDarwin())
127     markSuperRegs(Reserved, AArch64::W29);
128 
129   if (MF.getSubtarget<AArch64Subtarget>().isX18Reserved())
130     markSuperRegs(Reserved, AArch64::W18); // Platform register
131 
132   if (hasBasePointer(MF))
133     markSuperRegs(Reserved, AArch64::W19);
134 
135   assert(checkAllSuperRegsMarked(Reserved));
136   return Reserved;
137 }
138 
139 bool AArch64RegisterInfo::isReservedReg(const MachineFunction &MF,
140                                       unsigned Reg) const {
141   const AArch64FrameLowering *TFI = getFrameLowering(MF);
142 
143   switch (Reg) {
144   default:
145     break;
146   case AArch64::SP:
147   case AArch64::XZR:
148   case AArch64::WSP:
149   case AArch64::WZR:
150     return true;
151   case AArch64::X18:
152   case AArch64::W18:
153     return MF.getSubtarget<AArch64Subtarget>().isX18Reserved();
154   case AArch64::FP:
155   case AArch64::W29:
156     return TFI->hasFP(MF) || TT.isOSDarwin();
157   case AArch64::W19:
158   case AArch64::X19:
159     return hasBasePointer(MF);
160   }
161 
162   return false;
163 }
164 
165 bool AArch64RegisterInfo::isConstantPhysReg(unsigned PhysReg) const {
166   return PhysReg == AArch64::WZR || PhysReg == AArch64::XZR;
167 }
168 
169 const TargetRegisterClass *
170 AArch64RegisterInfo::getPointerRegClass(const MachineFunction &MF,
171                                       unsigned Kind) const {
172   return &AArch64::GPR64spRegClass;
173 }
174 
175 const TargetRegisterClass *
176 AArch64RegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
177   if (RC == &AArch64::CCRRegClass)
178     return &AArch64::GPR64RegClass; // Only MSR & MRS copy NZCV.
179   return RC;
180 }
181 
182 unsigned AArch64RegisterInfo::getBaseRegister() const { return AArch64::X19; }
183 
184 bool AArch64RegisterInfo::hasBasePointer(const MachineFunction &MF) const {
185   const MachineFrameInfo &MFI = MF.getFrameInfo();
186 
187   // In the presence of variable sized objects, if the fixed stack size is
188   // large enough that referencing from the FP won't result in things being
189   // in range relatively often, we can use a base pointer to allow access
190   // from the other direction like the SP normally works.
191   // Furthermore, if both variable sized objects are present, and the
192   // stack needs to be dynamically re-aligned, the base pointer is the only
193   // reliable way to reference the locals.
194   if (MFI.hasVarSizedObjects()) {
195     if (needsStackRealignment(MF))
196       return true;
197     // Conservatively estimate whether the negative offset from the frame
198     // pointer will be sufficient to reach. If a function has a smallish
199     // frame, it's less likely to have lots of spills and callee saved
200     // space, so it's all more likely to be within range of the frame pointer.
201     // If it's wrong, we'll materialize the constant and still get to the
202     // object; it's just suboptimal. Negative offsets use the unscaled
203     // load/store instructions, which have a 9-bit signed immediate.
204     return MFI.getLocalFrameSize() >= 256;
205   }
206 
207   return false;
208 }
209 
210 unsigned
211 AArch64RegisterInfo::getFrameRegister(const MachineFunction &MF) const {
212   const AArch64FrameLowering *TFI = getFrameLowering(MF);
213   return TFI->hasFP(MF) ? AArch64::FP : AArch64::SP;
214 }
215 
216 bool AArch64RegisterInfo::requiresRegisterScavenging(
217     const MachineFunction &MF) const {
218   return true;
219 }
220 
221 bool AArch64RegisterInfo::requiresVirtualBaseRegisters(
222     const MachineFunction &MF) const {
223   return true;
224 }
225 
226 bool
227 AArch64RegisterInfo::useFPForScavengingIndex(const MachineFunction &MF) const {
228   // This function indicates whether the emergency spillslot should be placed
229   // close to the beginning of the stackframe (closer to FP) or the end
230   // (closer to SP).
231   //
232   // The beginning works most reliably if we have a frame pointer.
233   const AArch64FrameLowering &TFI = *getFrameLowering(MF);
234   return TFI.hasFP(MF);
235 }
236 
237 bool AArch64RegisterInfo::requiresFrameIndexScavenging(
238     const MachineFunction &MF) const {
239   return true;
240 }
241 
242 bool
243 AArch64RegisterInfo::cannotEliminateFrame(const MachineFunction &MF) const {
244   const MachineFrameInfo &MFI = MF.getFrameInfo();
245   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI.adjustsStack())
246     return true;
247   return MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken();
248 }
249 
250 /// needsFrameBaseReg - Returns true if the instruction's frame index
251 /// reference would be better served by a base register other than FP
252 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
253 /// references it should create new base registers for.
254 bool AArch64RegisterInfo::needsFrameBaseReg(MachineInstr *MI,
255                                             int64_t Offset) const {
256   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i)
257     assert(i < MI->getNumOperands() &&
258            "Instr doesn't have FrameIndex operand!");
259 
260   // It's the load/store FI references that cause issues, as it can be difficult
261   // to materialize the offset if it won't fit in the literal field. Estimate
262   // based on the size of the local frame and some conservative assumptions
263   // about the rest of the stack frame (note, this is pre-regalloc, so
264   // we don't know everything for certain yet) whether this offset is likely
265   // to be out of range of the immediate. Return true if so.
266 
267   // We only generate virtual base registers for loads and stores, so
268   // return false for everything else.
269   if (!MI->mayLoad() && !MI->mayStore())
270     return false;
271 
272   // Without a virtual base register, if the function has variable sized
273   // objects, all fixed-size local references will be via the frame pointer,
274   // Approximate the offset and see if it's legal for the instruction.
275   // Note that the incoming offset is based on the SP value at function entry,
276   // so it'll be negative.
277   MachineFunction &MF = *MI->getParent()->getParent();
278   const AArch64FrameLowering *TFI = getFrameLowering(MF);
279   MachineFrameInfo &MFI = MF.getFrameInfo();
280 
281   // Estimate an offset from the frame pointer.
282   // Conservatively assume all GPR callee-saved registers get pushed.
283   // FP, LR, X19-X28, D8-D15. 64-bits each.
284   int64_t FPOffset = Offset - 16 * 20;
285   // Estimate an offset from the stack pointer.
286   // The incoming offset is relating to the SP at the start of the function,
287   // but when we access the local it'll be relative to the SP after local
288   // allocation, so adjust our SP-relative offset by that allocation size.
289   Offset += MFI.getLocalFrameSize();
290   // Assume that we'll have at least some spill slots allocated.
291   // FIXME: This is a total SWAG number. We should run some statistics
292   //        and pick a real one.
293   Offset += 128; // 128 bytes of spill slots
294 
295   // If there is a frame pointer, try using it.
296   // The FP is only available if there is no dynamic realignment. We
297   // don't know for sure yet whether we'll need that, so we guess based
298   // on whether there are any local variables that would trigger it.
299   if (TFI->hasFP(MF) && isFrameOffsetLegal(MI, AArch64::FP, FPOffset))
300     return false;
301 
302   // If we can reference via the stack pointer or base pointer, try that.
303   // FIXME: This (and the code that resolves the references) can be improved
304   //        to only disallow SP relative references in the live range of
305   //        the VLA(s). In practice, it's unclear how much difference that
306   //        would make, but it may be worth doing.
307   if (isFrameOffsetLegal(MI, AArch64::SP, Offset))
308     return false;
309 
310   // The offset likely isn't legal; we want to allocate a virtual base register.
311   return true;
312 }
313 
314 bool AArch64RegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
315                                              unsigned BaseReg,
316                                              int64_t Offset) const {
317   assert(Offset <= INT_MAX && "Offset too big to fit in int.");
318   assert(MI && "Unable to get the legal offset for nil instruction.");
319   int SaveOffset = Offset;
320   return isAArch64FrameOffsetLegal(*MI, SaveOffset) & AArch64FrameOffsetIsLegal;
321 }
322 
323 /// Insert defining instruction(s) for BaseReg to be a pointer to FrameIdx
324 /// at the beginning of the basic block.
325 void AArch64RegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
326                                                        unsigned BaseReg,
327                                                        int FrameIdx,
328                                                        int64_t Offset) const {
329   MachineBasicBlock::iterator Ins = MBB->begin();
330   DebugLoc DL; // Defaults to "unknown"
331   if (Ins != MBB->end())
332     DL = Ins->getDebugLoc();
333   const MachineFunction &MF = *MBB->getParent();
334   const AArch64InstrInfo *TII =
335       MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
336   const MCInstrDesc &MCID = TII->get(AArch64::ADDXri);
337   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
338   MRI.constrainRegClass(BaseReg, TII->getRegClass(MCID, 0, this, MF));
339   unsigned Shifter = AArch64_AM::getShifterImm(AArch64_AM::LSL, 0);
340 
341   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
342       .addFrameIndex(FrameIdx)
343       .addImm(Offset)
344       .addImm(Shifter);
345 }
346 
347 void AArch64RegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
348                                             int64_t Offset) const {
349   int Off = Offset; // ARM doesn't need the general 64-bit offsets
350   unsigned i = 0;
351 
352   while (!MI.getOperand(i).isFI()) {
353     ++i;
354     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
355   }
356   const MachineFunction *MF = MI.getParent()->getParent();
357   const AArch64InstrInfo *TII =
358       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
359   bool Done = rewriteAArch64FrameIndex(MI, i, BaseReg, Off, TII);
360   assert(Done && "Unable to resolve frame index!");
361   (void)Done;
362 }
363 
364 void AArch64RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
365                                               int SPAdj, unsigned FIOperandNum,
366                                               RegScavenger *RS) const {
367   assert(SPAdj == 0 && "Unexpected");
368 
369   MachineInstr &MI = *II;
370   MachineBasicBlock &MBB = *MI.getParent();
371   MachineFunction &MF = *MBB.getParent();
372   const AArch64InstrInfo *TII =
373       MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
374   const AArch64FrameLowering *TFI = getFrameLowering(MF);
375 
376   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
377   unsigned FrameReg;
378   int Offset;
379 
380   // Special handling of dbg_value, stackmap and patchpoint instructions.
381   if (MI.isDebugValue() || MI.getOpcode() == TargetOpcode::STACKMAP ||
382       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
383     Offset = TFI->resolveFrameIndexReference(MF, FrameIndex, FrameReg,
384                                              /*PreferFP=*/true);
385     Offset += MI.getOperand(FIOperandNum + 1).getImm();
386     MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false /*isDef*/);
387     MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset);
388     return;
389   }
390 
391   // Modify MI as necessary to handle as much of 'Offset' as possible
392   Offset = TFI->resolveFrameIndexReference(MF, FrameIndex, FrameReg);
393   if (rewriteAArch64FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII))
394     return;
395 
396   assert((!RS || !RS->isScavengingFrameIndex(FrameIndex)) &&
397          "Emergency spill slot is out of reach");
398 
399   // If we get here, the immediate doesn't fit into the instruction.  We folded
400   // as much as possible above.  Handle the rest, providing a register that is
401   // SP+LargeImm.
402   unsigned ScratchReg =
403       MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass);
404   emitFrameOffset(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg, Offset, TII);
405   MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false, true);
406 }
407 
408 unsigned AArch64RegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
409                                                   MachineFunction &MF) const {
410   const AArch64FrameLowering *TFI = getFrameLowering(MF);
411 
412   switch (RC->getID()) {
413   default:
414     return 0;
415   case AArch64::GPR32RegClassID:
416   case AArch64::GPR32spRegClassID:
417   case AArch64::GPR32allRegClassID:
418   case AArch64::GPR64spRegClassID:
419   case AArch64::GPR64allRegClassID:
420   case AArch64::GPR64RegClassID:
421   case AArch64::GPR32commonRegClassID:
422   case AArch64::GPR64commonRegClassID:
423     return 32 - 1                                   // XZR/SP
424               - (TFI->hasFP(MF) || TT.isOSDarwin()) // FP
425               - MF.getSubtarget<AArch64Subtarget>()
426                     .isX18Reserved() // X18 reserved as platform register
427               - hasBasePointer(MF);  // X19
428   case AArch64::FPR8RegClassID:
429   case AArch64::FPR16RegClassID:
430   case AArch64::FPR32RegClassID:
431   case AArch64::FPR64RegClassID:
432   case AArch64::FPR128RegClassID:
433     return 32;
434 
435   case AArch64::DDRegClassID:
436   case AArch64::DDDRegClassID:
437   case AArch64::DDDDRegClassID:
438   case AArch64::QQRegClassID:
439   case AArch64::QQQRegClassID:
440   case AArch64::QQQQRegClassID:
441     return 32;
442 
443   case AArch64::FPR128_loRegClassID:
444     return 16;
445   }
446 }
447