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