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, const DebugLoc &DL,
351                           Register Reg, int64_t NumBytes,
352                           const TargetInstrInfo *TII) {
353   while (NumBytes) {
354     unsigned Opcode;
355     int64_t ThisVal = NumBytes;
356     if (isInt<16>(NumBytes))
357       Opcode = SystemZ::AGHI;
358     else {
359       Opcode = SystemZ::AGFI;
360       // Make sure we maintain 8-byte stack alignment.
361       int64_t MinVal = -uint64_t(1) << 31;
362       int64_t MaxVal = (int64_t(1) << 31) - 8;
363       if (ThisVal < MinVal)
364         ThisVal = MinVal;
365       else if (ThisVal > MaxVal)
366         ThisVal = MaxVal;
367     }
368     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII->get(Opcode), Reg)
369       .addReg(Reg).addImm(ThisVal);
370     // The CC implicit def is dead.
371     MI->getOperand(3).setIsDead();
372     NumBytes -= ThisVal;
373   }
374 }
375 
376 void SystemZFrameLowering::emitPrologue(MachineFunction &MF,
377                                         MachineBasicBlock &MBB) const {
378   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
379   MachineFrameInfo &MFFrame = MF.getFrameInfo();
380   auto *ZII =
381       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
382   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
383   MachineBasicBlock::iterator MBBI = MBB.begin();
384   MachineModuleInfo &MMI = MF.getMMI();
385   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
386   const std::vector<CalleeSavedInfo> &CSI = MFFrame.getCalleeSavedInfo();
387   bool HasFP = hasFP(MF);
388 
389   // In GHC calling convention C stack space, including the ABI-defined
390   // 160-byte base area, is (de)allocated by GHC itself.  This stack space may
391   // be used by LLVM as spill slots for the tail recursive GHC functions.  Thus
392   // do not allocate stack space here, too.
393   if (MF.getFunction().getCallingConv() == CallingConv::GHC) {
394     if (MFFrame.getStackSize() > 2048 * sizeof(long)) {
395       report_fatal_error(
396           "Pre allocated stack space for GHC function is too small");
397     }
398     if (HasFP) {
399       report_fatal_error(
400           "In GHC calling convention a frame pointer is not supported");
401     }
402     MFFrame.setStackSize(MFFrame.getStackSize() + SystemZMC::CallFrameSize);
403     return;
404   }
405 
406   // Debug location must be unknown since the first debug location is used
407   // to determine the end of the prologue.
408   DebugLoc DL;
409 
410   // The current offset of the stack pointer from the CFA.
411   int64_t SPOffsetFromCFA = -SystemZMC::CFAOffsetFromInitialSP;
412 
413   if (ZFI->getSpillGPRRegs().LowGPR) {
414     // Skip over the GPR saves.
415     if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
416       ++MBBI;
417     else
418       llvm_unreachable("Couldn't skip over GPR saves");
419 
420     // Add CFI for the GPR saves.
421     for (auto &Save : CSI) {
422       unsigned Reg = Save.getReg();
423       if (SystemZ::GR64BitRegClass.contains(Reg)) {
424         int FI = Save.getFrameIdx();
425         int64_t Offset = MFFrame.getObjectOffset(FI);
426         unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
427             nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
428         BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
429             .addCFIIndex(CFIIndex);
430       }
431     }
432   }
433 
434   uint64_t StackSize = MFFrame.getStackSize();
435   // We need to allocate the ABI-defined 160-byte base area whenever
436   // we allocate stack space for our own use and whenever we call another
437   // function.
438   bool HasStackObject = false;
439   for (unsigned i = 0, e = MFFrame.getObjectIndexEnd(); i != e; ++i)
440     if (!MFFrame.isDeadObjectIndex(i)) {
441       HasStackObject = true;
442       break;
443     }
444   if (HasStackObject || MFFrame.hasCalls())
445     StackSize += SystemZMC::CallFrameSize;
446   // Don't allocate the incoming reg save area.
447   StackSize = StackSize > SystemZMC::CallFrameSize
448                   ? StackSize - SystemZMC::CallFrameSize
449                   : 0;
450   MFFrame.setStackSize(StackSize);
451 
452   if (StackSize) {
453     // Determine if we want to store a backchain.
454     bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
455 
456     // If we need backchain, save current stack pointer.  R1 is free at this
457     // point.
458     if (StoreBackchain)
459       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR))
460         .addReg(SystemZ::R1D, RegState::Define).addReg(SystemZ::R15D);
461 
462     // Allocate StackSize bytes.
463     int64_t Delta = -int64_t(StackSize);
464     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, Delta, ZII);
465 
466     // Add CFI for the allocation.
467     unsigned CFIIndex = MF.addFrameInst(
468         MCCFIInstruction::createDefCfaOffset(nullptr, SPOffsetFromCFA + Delta));
469     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
470         .addCFIIndex(CFIIndex);
471     SPOffsetFromCFA += Delta;
472 
473     if (StoreBackchain) {
474       // The back chain is stored topmost with packed-stack.
475       int Offset = usePackedStack(MF) ? SystemZMC::CallFrameSize - 8 : 0;
476       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::STG))
477         .addReg(SystemZ::R1D, RegState::Kill).addReg(SystemZ::R15D)
478         .addImm(Offset).addReg(0);
479     }
480   }
481 
482   if (HasFP) {
483     // Copy the base of the frame to R11.
484     BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R11D)
485       .addReg(SystemZ::R15D);
486 
487     // Add CFI for the new frame location.
488     unsigned HardFP = MRI->getDwarfRegNum(SystemZ::R11D, true);
489     unsigned CFIIndex = MF.addFrameInst(
490         MCCFIInstruction::createDefCfaRegister(nullptr, HardFP));
491     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
492         .addCFIIndex(CFIIndex);
493 
494     // Mark the FramePtr as live at the beginning of every block except
495     // the entry block.  (We'll have marked R11 as live on entry when
496     // saving the GPRs.)
497     for (auto I = std::next(MF.begin()), E = MF.end(); I != E; ++I)
498       I->addLiveIn(SystemZ::R11D);
499   }
500 
501   // Skip over the FPR/VR saves.
502   SmallVector<unsigned, 8> CFIIndexes;
503   for (auto &Save : CSI) {
504     unsigned Reg = Save.getReg();
505     if (SystemZ::FP64BitRegClass.contains(Reg)) {
506       if (MBBI != MBB.end() &&
507           (MBBI->getOpcode() == SystemZ::STD ||
508            MBBI->getOpcode() == SystemZ::STDY))
509         ++MBBI;
510       else
511         llvm_unreachable("Couldn't skip over FPR save");
512     } else if (SystemZ::VR128BitRegClass.contains(Reg)) {
513       if (MBBI != MBB.end() &&
514           MBBI->getOpcode() == SystemZ::VST)
515         ++MBBI;
516       else
517         llvm_unreachable("Couldn't skip over VR save");
518     } else
519       continue;
520 
521     // Add CFI for the this save.
522     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
523     Register IgnoredFrameReg;
524     int64_t Offset =
525         getFrameIndexReference(MF, Save.getFrameIdx(), IgnoredFrameReg);
526 
527     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
528           nullptr, DwarfReg, SPOffsetFromCFA + Offset));
529     CFIIndexes.push_back(CFIIndex);
530   }
531   // Complete the CFI for the FPR/VR saves, modelling them as taking effect
532   // after the last save.
533   for (auto CFIIndex : CFIIndexes) {
534     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
535         .addCFIIndex(CFIIndex);
536   }
537 }
538 
539 void SystemZFrameLowering::emitEpilogue(MachineFunction &MF,
540                                         MachineBasicBlock &MBB) const {
541   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
542   auto *ZII =
543       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
544   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
545   MachineFrameInfo &MFFrame = MF.getFrameInfo();
546 
547   // See SystemZFrameLowering::emitPrologue
548   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
549     return;
550 
551   // Skip the return instruction.
552   assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
553 
554   uint64_t StackSize = MFFrame.getStackSize();
555   if (ZFI->getRestoreGPRRegs().LowGPR) {
556     --MBBI;
557     unsigned Opcode = MBBI->getOpcode();
558     if (Opcode != SystemZ::LMG)
559       llvm_unreachable("Expected to see callee-save register restore code");
560 
561     unsigned AddrOpNo = 2;
562     DebugLoc DL = MBBI->getDebugLoc();
563     uint64_t Offset = StackSize + MBBI->getOperand(AddrOpNo + 1).getImm();
564     unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
565 
566     // If the offset is too large, use the largest stack-aligned offset
567     // and add the rest to the base register (the stack or frame pointer).
568     if (!NewOpcode) {
569       uint64_t NumBytes = Offset - 0x7fff8;
570       emitIncrement(MBB, MBBI, DL, MBBI->getOperand(AddrOpNo).getReg(),
571                     NumBytes, ZII);
572       Offset -= NumBytes;
573       NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
574       assert(NewOpcode && "No restore instruction available");
575     }
576 
577     MBBI->setDesc(ZII->get(NewOpcode));
578     MBBI->getOperand(AddrOpNo + 1).ChangeToImmediate(Offset);
579   } else if (StackSize) {
580     DebugLoc DL = MBBI->getDebugLoc();
581     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, StackSize, ZII);
582   }
583 }
584 
585 bool SystemZFrameLowering::hasFP(const MachineFunction &MF) const {
586   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
587           MF.getFrameInfo().hasVarSizedObjects() ||
588           MF.getInfo<SystemZMachineFunctionInfo>()->getManipulatesSP());
589 }
590 
591 bool
592 SystemZFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
593   // The ABI requires us to allocate 160 bytes of stack space for the callee,
594   // with any outgoing stack arguments being placed above that.  It seems
595   // better to make that area a permanent feature of the frame even if
596   // we're using a frame pointer.
597   return true;
598 }
599 
600 int SystemZFrameLowering::getFrameIndexReference(const MachineFunction &MF,
601                                                  int FI,
602                                                  Register &FrameReg) const {
603   // Our incoming SP is actually SystemZMC::CallFrameSize below the CFA, so
604   // add that difference here.
605   int64_t Offset =
606     TargetFrameLowering::getFrameIndexReference(MF, FI, FrameReg);
607   return Offset + SystemZMC::CallFrameSize;
608 }
609 
610 MachineBasicBlock::iterator SystemZFrameLowering::
611 eliminateCallFramePseudoInstr(MachineFunction &MF,
612                               MachineBasicBlock &MBB,
613                               MachineBasicBlock::iterator MI) const {
614   switch (MI->getOpcode()) {
615   case SystemZ::ADJCALLSTACKDOWN:
616   case SystemZ::ADJCALLSTACKUP:
617     assert(hasReservedCallFrame(MF) &&
618            "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
619     return MBB.erase(MI);
620     break;
621 
622   default:
623     llvm_unreachable("Unexpected call frame instruction");
624   }
625 }
626 
627 unsigned SystemZFrameLowering::getRegSpillOffset(MachineFunction &MF,
628                                                  Register Reg) const {
629   bool IsVarArg = MF.getFunction().isVarArg();
630   bool BackChain = MF.getFunction().hasFnAttribute("backchain");
631   bool SoftFloat = MF.getSubtarget<SystemZSubtarget>().hasSoftFloat();
632   unsigned Offset = RegSpillOffsets[Reg];
633   if (usePackedStack(MF) && !(IsVarArg && !SoftFloat)) {
634     if (SystemZ::GR64BitRegClass.contains(Reg))
635       // Put all GPRs at the top of the Register save area with packed
636       // stack. Make room for the backchain if needed.
637       Offset += BackChain ? 24 : 32;
638     else
639       Offset = 0;
640   }
641   return Offset;
642 }
643 
644 int SystemZFrameLowering::
645 getOrCreateFramePointerSaveIndex(MachineFunction &MF) const {
646   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
647   int FI = ZFI->getFramePointerSaveIndex();
648   if (!FI) {
649     MachineFrameInfo &MFFrame = MF.getFrameInfo();
650     // The back chain is stored topmost with packed-stack.
651     int Offset = usePackedStack(MF) ? -8 : -SystemZMC::CallFrameSize;
652     FI = MFFrame.CreateFixedObject(8, Offset, false);
653     ZFI->setFramePointerSaveIndex(FI);
654   }
655   return FI;
656 }
657 
658 bool SystemZFrameLowering::usePackedStack(MachineFunction &MF) const {
659   bool HasPackedStackAttr = MF.getFunction().hasFnAttribute("packed-stack");
660   bool BackChain = MF.getFunction().hasFnAttribute("backchain");
661   bool SoftFloat = MF.getSubtarget<SystemZSubtarget>().hasSoftFloat();
662   if (HasPackedStackAttr && BackChain && !SoftFloat)
663     report_fatal_error("packed-stack + backchain + hard-float is unsupported.");
664   bool CallConv = MF.getFunction().getCallingConv() != CallingConv::GHC;
665   return HasPackedStackAttr && CallConv;
666 }
667