1 //===-- SystemZFrameLowering.cpp - Frame lowering for SystemZ -------------===//
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 #include "SystemZFrameLowering.h"
10 #include "SystemZCallingConv.h"
11 #include "SystemZInstrBuilder.h"
12 #include "SystemZInstrInfo.h"
13 #include "SystemZMachineFunctionInfo.h"
14 #include "SystemZRegisterInfo.h"
15 #include "SystemZSubtarget.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/IR/Function.h"
20 
21 using namespace llvm;
22 
23 namespace {
24 // The ABI-defined register save slots, relative to the CFA (i.e.
25 // incoming stack pointer + SystemZMC::CallFrameSize).
26 static const TargetFrameLowering::SpillSlot SpillOffsetTable[] = {
27   { SystemZ::R2D,  0x10 },
28   { SystemZ::R3D,  0x18 },
29   { SystemZ::R4D,  0x20 },
30   { SystemZ::R5D,  0x28 },
31   { SystemZ::R6D,  0x30 },
32   { SystemZ::R7D,  0x38 },
33   { SystemZ::R8D,  0x40 },
34   { SystemZ::R9D,  0x48 },
35   { SystemZ::R10D, 0x50 },
36   { SystemZ::R11D, 0x58 },
37   { SystemZ::R12D, 0x60 },
38   { SystemZ::R13D, 0x68 },
39   { SystemZ::R14D, 0x70 },
40   { SystemZ::R15D, 0x78 },
41   { SystemZ::F0D,  0x80 },
42   { SystemZ::F2D,  0x88 },
43   { SystemZ::F4D,  0x90 },
44   { SystemZ::F6D,  0x98 }
45 };
46 } // end anonymous namespace
47 
48 SystemZFrameLowering::SystemZFrameLowering()
49     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(8),
50                           0, Align(8), false /* StackRealignable */),
51       RegSpillOffsets(0) {
52   // Due to the SystemZ ABI, the DWARF CFA (Canonical Frame Address) is not
53   // equal to the incoming stack pointer, but to incoming stack pointer plus
54   // 160.  Instead of using a Local Area Offset, the Register save area will
55   // be occupied by fixed frame objects, and all offsets are actually
56   // relative to CFA.
57 
58   // Create a mapping from register number to save slot offset.
59   // These offsets are relative to the start of the register save area.
60   RegSpillOffsets.grow(SystemZ::NUM_TARGET_REGS);
61   for (unsigned I = 0, E = array_lengthof(SpillOffsetTable); I != E; ++I)
62     RegSpillOffsets[SpillOffsetTable[I].Reg] = SpillOffsetTable[I].Offset;
63 }
64 
65 bool SystemZFrameLowering::
66 assignCalleeSavedSpillSlots(MachineFunction &MF,
67                             const TargetRegisterInfo *TRI,
68                             std::vector<CalleeSavedInfo> &CSI) const {
69   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
70   MachineFrameInfo &MFFrame = MF.getFrameInfo();
71   bool IsVarArg = MF.getFunction().isVarArg();
72   if (CSI.empty())
73     return true; // Early exit if no callee saved registers are modified!
74 
75   unsigned LowGPR = 0;
76   unsigned HighGPR = SystemZ::R15D;
77   int StartSPOffset = SystemZMC::CallFrameSize;
78   for (auto &CS : CSI) {
79     unsigned Reg = CS.getReg();
80     int Offset = getRegSpillOffset(MF, Reg);
81     if (Offset) {
82       if (SystemZ::GR64BitRegClass.contains(Reg) && StartSPOffset > Offset) {
83         LowGPR = Reg;
84         StartSPOffset = Offset;
85       }
86       Offset -= SystemZMC::CallFrameSize;
87       int FrameIdx = MFFrame.CreateFixedSpillStackObject(8, Offset);
88       CS.setFrameIdx(FrameIdx);
89     } else
90       CS.setFrameIdx(INT32_MAX);
91   }
92 
93   // Save the range of call-saved registers, for use by the
94   // prologue/epilogue inserters.
95   ZFI->setRestoreGPRRegs(LowGPR, HighGPR, StartSPOffset);
96   if (IsVarArg) {
97     // Also save the GPR varargs, if any.  R6D is call-saved, so would
98     // already be included, but we also need to handle the call-clobbered
99     // argument registers.
100     unsigned FirstGPR = ZFI->getVarArgsFirstGPR();
101     if (FirstGPR < SystemZ::NumArgGPRs) {
102       unsigned Reg = SystemZ::ArgGPRs[FirstGPR];
103       int Offset = getRegSpillOffset(MF, Reg);
104       if (StartSPOffset > Offset) {
105         LowGPR = Reg; StartSPOffset = Offset;
106       }
107     }
108   }
109   ZFI->setSpillGPRRegs(LowGPR, HighGPR, StartSPOffset);
110 
111   // Create fixed stack objects for the remaining registers.
112   int CurrOffset = -SystemZMC::CallFrameSize;
113   if (usePackedStack(MF))
114     CurrOffset += StartSPOffset;
115 
116   for (auto &CS : CSI) {
117     if (CS.getFrameIdx() != INT32_MAX)
118       continue;
119     unsigned Reg = CS.getReg();
120     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
121     unsigned Size = TRI->getSpillSize(*RC);
122     CurrOffset -= Size;
123     assert(CurrOffset % 8 == 0 &&
124            "8-byte alignment required for for all register save slots");
125     int FrameIdx = MFFrame.CreateFixedSpillStackObject(Size, CurrOffset);
126     CS.setFrameIdx(FrameIdx);
127   }
128 
129   return true;
130 }
131 
132 void SystemZFrameLowering::determineCalleeSaves(MachineFunction &MF,
133                                                 BitVector &SavedRegs,
134                                                 RegScavenger *RS) const {
135   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
136 
137   MachineFrameInfo &MFFrame = MF.getFrameInfo();
138   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
139   bool HasFP = hasFP(MF);
140   SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
141   bool IsVarArg = MF.getFunction().isVarArg();
142 
143   // va_start stores incoming FPR varargs in the normal way, but delegates
144   // the saving of incoming GPR varargs to spillCalleeSavedRegisters().
145   // Record these pending uses, which typically include the call-saved
146   // argument register R6D.
147   if (IsVarArg)
148     for (unsigned I = MFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
149       SavedRegs.set(SystemZ::ArgGPRs[I]);
150 
151   // If there are any landing pads, entering them will modify r6/r7.
152   if (!MF.getLandingPads().empty()) {
153     SavedRegs.set(SystemZ::R6D);
154     SavedRegs.set(SystemZ::R7D);
155   }
156 
157   // If the function requires a frame pointer, record that the hard
158   // frame pointer will be clobbered.
159   if (HasFP)
160     SavedRegs.set(SystemZ::R11D);
161 
162   // If the function calls other functions, record that the return
163   // address register will be clobbered.
164   if (MFFrame.hasCalls())
165     SavedRegs.set(SystemZ::R14D);
166 
167   // If we are saving GPRs other than the stack pointer, we might as well
168   // save and restore the stack pointer at the same time, via STMG and LMG.
169   // This allows the deallocation to be done by the LMG, rather than needing
170   // a separate %r15 addition.
171   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
172   for (unsigned I = 0; CSRegs[I]; ++I) {
173     unsigned Reg = CSRegs[I];
174     if (SystemZ::GR64BitRegClass.contains(Reg) && SavedRegs.test(Reg)) {
175       SavedRegs.set(SystemZ::R15D);
176       break;
177     }
178   }
179 }
180 
181 // Add GPR64 to the save instruction being built by MIB, which is in basic
182 // block MBB.  IsImplicit says whether this is an explicit operand to the
183 // instruction, or an implicit one that comes between the explicit start
184 // and end registers.
185 static void addSavedGPR(MachineBasicBlock &MBB, MachineInstrBuilder &MIB,
186                         unsigned GPR64, bool IsImplicit) {
187   const TargetRegisterInfo *RI =
188       MBB.getParent()->getSubtarget().getRegisterInfo();
189   Register GPR32 = RI->getSubReg(GPR64, SystemZ::subreg_l32);
190   bool IsLive = MBB.isLiveIn(GPR64) || MBB.isLiveIn(GPR32);
191   if (!IsLive || !IsImplicit) {
192     MIB.addReg(GPR64, getImplRegState(IsImplicit) | getKillRegState(!IsLive));
193     if (!IsLive)
194       MBB.addLiveIn(GPR64);
195   }
196 }
197 
198 bool SystemZFrameLowering::spillCalleeSavedRegisters(
199     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
200     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
201   if (CSI.empty())
202     return false;
203 
204   MachineFunction &MF = *MBB.getParent();
205   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
206   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
207   bool IsVarArg = MF.getFunction().isVarArg();
208   DebugLoc DL;
209 
210   // Save GPRs
211   SystemZ::GPRRegs SpillGPRs = ZFI->getSpillGPRRegs();
212   if (SpillGPRs.LowGPR) {
213     assert(SpillGPRs.LowGPR != SpillGPRs.HighGPR &&
214            "Should be saving %r15 and something else");
215 
216     // Build an STMG instruction.
217     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STMG));
218 
219     // Add the explicit register operands.
220     addSavedGPR(MBB, MIB, SpillGPRs.LowGPR, false);
221     addSavedGPR(MBB, MIB, SpillGPRs.HighGPR, false);
222 
223     // Add the address.
224     MIB.addReg(SystemZ::R15D).addImm(SpillGPRs.GPROffset);
225 
226     // Make sure all call-saved GPRs are included as operands and are
227     // marked as live on entry.
228     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
229       unsigned Reg = CSI[I].getReg();
230       if (SystemZ::GR64BitRegClass.contains(Reg))
231         addSavedGPR(MBB, MIB, Reg, true);
232     }
233 
234     // ...likewise GPR varargs.
235     if (IsVarArg)
236       for (unsigned I = ZFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
237         addSavedGPR(MBB, MIB, SystemZ::ArgGPRs[I], true);
238   }
239 
240   // Save FPRs/VRs in the normal TargetInstrInfo way.
241   for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
242     unsigned Reg = CSI[I].getReg();
243     if (SystemZ::FP64BitRegClass.contains(Reg)) {
244       MBB.addLiveIn(Reg);
245       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, CSI[I].getFrameIdx(),
246                                &SystemZ::FP64BitRegClass, TRI);
247     }
248     if (SystemZ::VR128BitRegClass.contains(Reg)) {
249       MBB.addLiveIn(Reg);
250       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, CSI[I].getFrameIdx(),
251                                &SystemZ::VR128BitRegClass, TRI);
252     }
253   }
254 
255   return true;
256 }
257 
258 bool SystemZFrameLowering::restoreCalleeSavedRegisters(
259     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
260     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
261   if (CSI.empty())
262     return false;
263 
264   MachineFunction &MF = *MBB.getParent();
265   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
266   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
267   bool HasFP = hasFP(MF);
268   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
269 
270   // Restore FPRs/VRs in the normal TargetInstrInfo way.
271   for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
272     unsigned Reg = CSI[I].getReg();
273     if (SystemZ::FP64BitRegClass.contains(Reg))
274       TII->loadRegFromStackSlot(MBB, MBBI, Reg, CSI[I].getFrameIdx(),
275                                 &SystemZ::FP64BitRegClass, TRI);
276     if (SystemZ::VR128BitRegClass.contains(Reg))
277       TII->loadRegFromStackSlot(MBB, MBBI, Reg, CSI[I].getFrameIdx(),
278                                 &SystemZ::VR128BitRegClass, TRI);
279   }
280 
281   // Restore call-saved GPRs (but not call-clobbered varargs, which at
282   // this point might hold return values).
283   SystemZ::GPRRegs RestoreGPRs = ZFI->getRestoreGPRRegs();
284   if (RestoreGPRs.LowGPR) {
285     // If we saved any of %r2-%r5 as varargs, we should also be saving
286     // and restoring %r6.  If we're saving %r6 or above, we should be
287     // restoring it too.
288     assert(RestoreGPRs.LowGPR != RestoreGPRs.HighGPR &&
289            "Should be loading %r15 and something else");
290 
291     // Build an LMG instruction.
292     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LMG));
293 
294     // Add the explicit register operands.
295     MIB.addReg(RestoreGPRs.LowGPR, RegState::Define);
296     MIB.addReg(RestoreGPRs.HighGPR, RegState::Define);
297 
298     // Add the address.
299     MIB.addReg(HasFP ? SystemZ::R11D : SystemZ::R15D);
300     MIB.addImm(RestoreGPRs.GPROffset);
301 
302     // Do a second scan adding regs as being defined by instruction
303     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
304       unsigned Reg = CSI[I].getReg();
305       if (Reg != RestoreGPRs.LowGPR && Reg != RestoreGPRs.HighGPR &&
306           SystemZ::GR64BitRegClass.contains(Reg))
307         MIB.addReg(Reg, RegState::ImplicitDefine);
308     }
309   }
310 
311   return true;
312 }
313 
314 void SystemZFrameLowering::
315 processFunctionBeforeFrameFinalized(MachineFunction &MF,
316                                     RegScavenger *RS) const {
317   MachineFrameInfo &MFFrame = MF.getFrameInfo();
318   bool BackChain = MF.getFunction().hasFnAttribute("backchain");
319 
320   if (!usePackedStack(MF) || BackChain)
321     // Create the incoming register save area.
322     getOrCreateFramePointerSaveIndex(MF);
323 
324   // Get the size of our stack frame to be allocated ...
325   uint64_t StackSize = (MFFrame.estimateStackSize(MF) +
326                         SystemZMC::CallFrameSize);
327   // ... and the maximum offset we may need to reach into the
328   // caller's frame to access the save area or stack arguments.
329   int64_t MaxArgOffset = 0;
330   for (int I = MFFrame.getObjectIndexBegin(); I != 0; ++I)
331     if (MFFrame.getObjectOffset(I) >= 0) {
332       int64_t ArgOffset = MFFrame.getObjectOffset(I) +
333                           MFFrame.getObjectSize(I);
334       MaxArgOffset = std::max(MaxArgOffset, ArgOffset);
335     }
336 
337   uint64_t MaxReach = StackSize + MaxArgOffset;
338   if (!isUInt<12>(MaxReach)) {
339     // We may need register scavenging slots if some parts of the frame
340     // are outside the reach of an unsigned 12-bit displacement.
341     // Create 2 for the case where both addresses in an MVC are
342     // out of range.
343     RS->addScavengingFrameIndex(MFFrame.CreateStackObject(8, 8, false));
344     RS->addScavengingFrameIndex(MFFrame.CreateStackObject(8, 8, false));
345   }
346 }
347 
348 // Emit instructions before MBBI (in MBB) to add NumBytes to Reg.
349 static void emitIncrement(MachineBasicBlock &MBB,
350                           MachineBasicBlock::iterator &MBBI,
351                           const DebugLoc &DL,
352                           unsigned Reg, int64_t NumBytes,
353                           const TargetInstrInfo *TII) {
354   while (NumBytes) {
355     unsigned Opcode;
356     int64_t ThisVal = NumBytes;
357     if (isInt<16>(NumBytes))
358       Opcode = SystemZ::AGHI;
359     else {
360       Opcode = SystemZ::AGFI;
361       // Make sure we maintain 8-byte stack alignment.
362       int64_t MinVal = -uint64_t(1) << 31;
363       int64_t MaxVal = (int64_t(1) << 31) - 8;
364       if (ThisVal < MinVal)
365         ThisVal = MinVal;
366       else if (ThisVal > MaxVal)
367         ThisVal = MaxVal;
368     }
369     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII->get(Opcode), Reg)
370       .addReg(Reg).addImm(ThisVal);
371     // The CC implicit def is dead.
372     MI->getOperand(3).setIsDead();
373     NumBytes -= ThisVal;
374   }
375 }
376 
377 void SystemZFrameLowering::emitPrologue(MachineFunction &MF,
378                                         MachineBasicBlock &MBB) const {
379   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
380   MachineFrameInfo &MFFrame = MF.getFrameInfo();
381   auto *ZII =
382       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
383   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
384   MachineBasicBlock::iterator MBBI = MBB.begin();
385   MachineModuleInfo &MMI = MF.getMMI();
386   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
387   const std::vector<CalleeSavedInfo> &CSI = MFFrame.getCalleeSavedInfo();
388   bool HasFP = hasFP(MF);
389 
390   // In GHC calling convention C stack space, including the ABI-defined
391   // 160-byte base area, is (de)allocated by GHC itself.  This stack space may
392   // be used by LLVM as spill slots for the tail recursive GHC functions.  Thus
393   // do not allocate stack space here, too.
394   if (MF.getFunction().getCallingConv() == CallingConv::GHC) {
395     if (MFFrame.getStackSize() > 2048 * sizeof(long)) {
396       report_fatal_error(
397           "Pre allocated stack space for GHC function is too small");
398     }
399     if (HasFP) {
400       report_fatal_error(
401           "In GHC calling convention a frame pointer is not supported");
402     }
403     MFFrame.setStackSize(MFFrame.getStackSize() + SystemZMC::CallFrameSize);
404     return;
405   }
406 
407   // Debug location must be unknown since the first debug location is used
408   // to determine the end of the prologue.
409   DebugLoc DL;
410 
411   // The current offset of the stack pointer from the CFA.
412   int64_t SPOffsetFromCFA = -SystemZMC::CFAOffsetFromInitialSP;
413 
414   if (ZFI->getSpillGPRRegs().LowGPR) {
415     // Skip over the GPR saves.
416     if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
417       ++MBBI;
418     else
419       llvm_unreachable("Couldn't skip over GPR saves");
420 
421     // Add CFI for the GPR saves.
422     for (auto &Save : CSI) {
423       unsigned Reg = Save.getReg();
424       if (SystemZ::GR64BitRegClass.contains(Reg)) {
425         int FI = Save.getFrameIdx();
426         int64_t Offset = MFFrame.getObjectOffset(FI);
427         unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
428             nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
429         BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
430             .addCFIIndex(CFIIndex);
431       }
432     }
433   }
434 
435   uint64_t StackSize = MFFrame.getStackSize();
436   // We need to allocate the ABI-defined 160-byte base area whenever
437   // we allocate stack space for our own use and whenever we call another
438   // function.
439   bool HasStackObject = false;
440   for (unsigned i = 0, e = MFFrame.getObjectIndexEnd(); i != e; ++i)
441     if (!MFFrame.isDeadObjectIndex(i)) {
442       HasStackObject = true;
443       break;
444     }
445   if (HasStackObject || MFFrame.hasCalls())
446     StackSize += SystemZMC::CallFrameSize;
447   // Don't allocate the incoming reg save area.
448   StackSize = StackSize > SystemZMC::CallFrameSize
449                   ? StackSize - SystemZMC::CallFrameSize
450                   : 0;
451   MFFrame.setStackSize(StackSize);
452 
453   if (StackSize) {
454     // Determine if we want to store a backchain.
455     bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
456 
457     // If we need backchain, save current stack pointer.  R1 is free at this
458     // point.
459     if (StoreBackchain)
460       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR))
461         .addReg(SystemZ::R1D, RegState::Define).addReg(SystemZ::R15D);
462 
463     // Allocate StackSize bytes.
464     int64_t Delta = -int64_t(StackSize);
465     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, Delta, ZII);
466 
467     // Add CFI for the allocation.
468     unsigned CFIIndex = MF.addFrameInst(
469         MCCFIInstruction::createDefCfaOffset(nullptr, SPOffsetFromCFA + Delta));
470     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
471         .addCFIIndex(CFIIndex);
472     SPOffsetFromCFA += Delta;
473 
474     if (StoreBackchain) {
475       // The back chain is stored topmost with packed-stack.
476       int Offset = usePackedStack(MF) ? SystemZMC::CallFrameSize - 8 : 0;
477       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::STG))
478         .addReg(SystemZ::R1D, RegState::Kill).addReg(SystemZ::R15D)
479         .addImm(Offset).addReg(0);
480     }
481   }
482 
483   if (HasFP) {
484     // Copy the base of the frame to R11.
485     BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R11D)
486       .addReg(SystemZ::R15D);
487 
488     // Add CFI for the new frame location.
489     unsigned HardFP = MRI->getDwarfRegNum(SystemZ::R11D, true);
490     unsigned CFIIndex = MF.addFrameInst(
491         MCCFIInstruction::createDefCfaRegister(nullptr, HardFP));
492     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
493         .addCFIIndex(CFIIndex);
494 
495     // Mark the FramePtr as live at the beginning of every block except
496     // the entry block.  (We'll have marked R11 as live on entry when
497     // saving the GPRs.)
498     for (auto I = std::next(MF.begin()), E = MF.end(); I != E; ++I)
499       I->addLiveIn(SystemZ::R11D);
500   }
501 
502   // Skip over the FPR/VR saves.
503   SmallVector<unsigned, 8> CFIIndexes;
504   for (auto &Save : CSI) {
505     unsigned Reg = Save.getReg();
506     if (SystemZ::FP64BitRegClass.contains(Reg)) {
507       if (MBBI != MBB.end() &&
508           (MBBI->getOpcode() == SystemZ::STD ||
509            MBBI->getOpcode() == SystemZ::STDY))
510         ++MBBI;
511       else
512         llvm_unreachable("Couldn't skip over FPR save");
513     } else if (SystemZ::VR128BitRegClass.contains(Reg)) {
514       if (MBBI != MBB.end() &&
515           MBBI->getOpcode() == SystemZ::VST)
516         ++MBBI;
517       else
518         llvm_unreachable("Couldn't skip over VR save");
519     } else
520       continue;
521 
522     // Add CFI for the this save.
523     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
524     unsigned IgnoredFrameReg;
525     int64_t Offset =
526         getFrameIndexReference(MF, Save.getFrameIdx(), IgnoredFrameReg);
527 
528     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
529           nullptr, DwarfReg, SPOffsetFromCFA + Offset));
530     CFIIndexes.push_back(CFIIndex);
531   }
532   // Complete the CFI for the FPR/VR saves, modelling them as taking effect
533   // after the last save.
534   for (auto CFIIndex : CFIIndexes) {
535     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
536         .addCFIIndex(CFIIndex);
537   }
538 }
539 
540 void SystemZFrameLowering::emitEpilogue(MachineFunction &MF,
541                                         MachineBasicBlock &MBB) const {
542   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
543   auto *ZII =
544       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
545   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
546   MachineFrameInfo &MFFrame = MF.getFrameInfo();
547 
548   // See SystemZFrameLowering::emitPrologue
549   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
550     return;
551 
552   // Skip the return instruction.
553   assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
554 
555   uint64_t StackSize = MFFrame.getStackSize();
556   if (ZFI->getRestoreGPRRegs().LowGPR) {
557     --MBBI;
558     unsigned Opcode = MBBI->getOpcode();
559     if (Opcode != SystemZ::LMG)
560       llvm_unreachable("Expected to see callee-save register restore code");
561 
562     unsigned AddrOpNo = 2;
563     DebugLoc DL = MBBI->getDebugLoc();
564     uint64_t Offset = StackSize + MBBI->getOperand(AddrOpNo + 1).getImm();
565     unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
566 
567     // If the offset is too large, use the largest stack-aligned offset
568     // and add the rest to the base register (the stack or frame pointer).
569     if (!NewOpcode) {
570       uint64_t NumBytes = Offset - 0x7fff8;
571       emitIncrement(MBB, MBBI, DL, MBBI->getOperand(AddrOpNo).getReg(),
572                     NumBytes, ZII);
573       Offset -= NumBytes;
574       NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
575       assert(NewOpcode && "No restore instruction available");
576     }
577 
578     MBBI->setDesc(ZII->get(NewOpcode));
579     MBBI->getOperand(AddrOpNo + 1).ChangeToImmediate(Offset);
580   } else if (StackSize) {
581     DebugLoc DL = MBBI->getDebugLoc();
582     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, StackSize, ZII);
583   }
584 }
585 
586 bool SystemZFrameLowering::hasFP(const MachineFunction &MF) const {
587   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
588           MF.getFrameInfo().hasVarSizedObjects() ||
589           MF.getInfo<SystemZMachineFunctionInfo>()->getManipulatesSP());
590 }
591 
592 bool
593 SystemZFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
594   // The ABI requires us to allocate 160 bytes of stack space for the callee,
595   // with any outgoing stack arguments being placed above that.  It seems
596   // better to make that area a permanent feature of the frame even if
597   // we're using a frame pointer.
598   return true;
599 }
600 
601 int SystemZFrameLowering::getFrameIndexReference(const MachineFunction &MF,
602                                                  int FI,
603                                                  unsigned &FrameReg) const {
604   // Our incoming SP is actually SystemZMC::CallFrameSize below the CFA, so
605   // add that difference here.
606   int64_t Offset =
607     TargetFrameLowering::getFrameIndexReference(MF, FI, FrameReg);
608   return Offset + SystemZMC::CallFrameSize;
609 }
610 
611 MachineBasicBlock::iterator SystemZFrameLowering::
612 eliminateCallFramePseudoInstr(MachineFunction &MF,
613                               MachineBasicBlock &MBB,
614                               MachineBasicBlock::iterator MI) const {
615   switch (MI->getOpcode()) {
616   case SystemZ::ADJCALLSTACKDOWN:
617   case SystemZ::ADJCALLSTACKUP:
618     assert(hasReservedCallFrame(MF) &&
619            "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
620     return MBB.erase(MI);
621     break;
622 
623   default:
624     llvm_unreachable("Unexpected call frame instruction");
625   }
626 }
627 
628 unsigned SystemZFrameLowering::getRegSpillOffset(MachineFunction &MF,
629                                                  unsigned Reg) const {
630   bool IsVarArg = MF.getFunction().isVarArg();
631   bool BackChain = MF.getFunction().hasFnAttribute("backchain");
632   bool SoftFloat = MF.getSubtarget<SystemZSubtarget>().hasSoftFloat();
633   unsigned Offset = RegSpillOffsets[Reg];
634   if (usePackedStack(MF) && !(IsVarArg && !SoftFloat)) {
635     if (SystemZ::GR64BitRegClass.contains(Reg))
636       // Put all GPRs at the top of the Register save area with packed
637       // stack. Make room for the backchain if needed.
638       Offset += BackChain ? 24 : 32;
639     else
640       Offset = 0;
641   }
642   return Offset;
643 }
644 
645 int SystemZFrameLowering::
646 getOrCreateFramePointerSaveIndex(MachineFunction &MF) const {
647   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
648   int FI = ZFI->getFramePointerSaveIndex();
649   if (!FI) {
650     MachineFrameInfo &MFFrame = MF.getFrameInfo();
651     // The back chain is stored topmost with packed-stack.
652     int Offset = usePackedStack(MF) ? -8 : -SystemZMC::CallFrameSize;
653     FI = MFFrame.CreateFixedObject(8, Offset, false);
654     ZFI->setFramePointerSaveIndex(FI);
655   }
656   return FI;
657 }
658 
659 bool SystemZFrameLowering::usePackedStack(MachineFunction &MF) const {
660   bool HasPackedStackAttr = MF.getFunction().hasFnAttribute("packed-stack");
661   bool BackChain = MF.getFunction().hasFnAttribute("backchain");
662   bool SoftFloat = MF.getSubtarget<SystemZSubtarget>().hasSoftFloat();
663   if (HasPackedStackAttr && BackChain && !SoftFloat)
664     report_fatal_error("packed-stack + backchain + hard-float is unsupported.");
665   bool CallConv = MF.getFunction().getCallingConv() != CallingConv::GHC;
666   return HasPackedStackAttr && CallConv;
667 }
668