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 "SystemZInstrInfo.h"
12#include "SystemZMachineFunctionInfo.h"
13#include "SystemZRegisterInfo.h"
14#include "SystemZSubtarget.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/CodeGen/LivePhysRegs.h"
17#include "llvm/CodeGen/MachineInstrBuilder.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/CodeGen/RegisterScavenging.h"
21#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
22#include "llvm/IR/CallingConv.h"
23#include "llvm/IR/Function.h"
24#include "llvm/Target/TargetMachine.h"
25
26using namespace llvm;
27
28namespace {
29// The ABI-defined register save slots, relative to the CFA (i.e.
30// incoming stack pointer + SystemZMC::ELFCallFrameSize).
31static const TargetFrameLowering::SpillSlot ELFSpillOffsetTable[] = {
32 { .Reg: SystemZ::R2D, .Offset: 0x10 },
33 { .Reg: SystemZ::R3D, .Offset: 0x18 },
34 { .Reg: SystemZ::R4D, .Offset: 0x20 },
35 { .Reg: SystemZ::R5D, .Offset: 0x28 },
36 { .Reg: SystemZ::R6D, .Offset: 0x30 },
37 { .Reg: SystemZ::R7D, .Offset: 0x38 },
38 { .Reg: SystemZ::R8D, .Offset: 0x40 },
39 { .Reg: SystemZ::R9D, .Offset: 0x48 },
40 { .Reg: SystemZ::R10D, .Offset: 0x50 },
41 { .Reg: SystemZ::R11D, .Offset: 0x58 },
42 { .Reg: SystemZ::R12D, .Offset: 0x60 },
43 { .Reg: SystemZ::R13D, .Offset: 0x68 },
44 { .Reg: SystemZ::R14D, .Offset: 0x70 },
45 { .Reg: SystemZ::R15D, .Offset: 0x78 },
46 { .Reg: SystemZ::F0D, .Offset: 0x80 },
47 { .Reg: SystemZ::F2D, .Offset: 0x88 },
48 { .Reg: SystemZ::F4D, .Offset: 0x90 },
49 { .Reg: SystemZ::F6D, .Offset: 0x98 }
50};
51
52static const TargetFrameLowering::SpillSlot XPLINKSpillOffsetTable[] = {
53 {.Reg: SystemZ::R4D, .Offset: 0x00}, {.Reg: SystemZ::R5D, .Offset: 0x08}, {.Reg: SystemZ::R6D, .Offset: 0x10},
54 {.Reg: SystemZ::R7D, .Offset: 0x18}, {.Reg: SystemZ::R8D, .Offset: 0x20}, {.Reg: SystemZ::R9D, .Offset: 0x28},
55 {.Reg: SystemZ::R10D, .Offset: 0x30}, {.Reg: SystemZ::R11D, .Offset: 0x38}, {.Reg: SystemZ::R12D, .Offset: 0x40},
56 {.Reg: SystemZ::R13D, .Offset: 0x48}, {.Reg: SystemZ::R14D, .Offset: 0x50}, {.Reg: SystemZ::R15D, .Offset: 0x58}};
57} // end anonymous namespace
58
59SystemZFrameLowering::SystemZFrameLowering(StackDirection D, Align StackAl,
60 int LAO, Align TransAl,
61 bool StackReal, unsigned PointerSize)
62 : TargetFrameLowering(D, StackAl, LAO, TransAl, StackReal),
63 PointerSize(PointerSize) {}
64
65std::unique_ptr<SystemZFrameLowering>
66SystemZFrameLowering::create(const SystemZSubtarget &STI) {
67 unsigned PtrSz =
68 STI.getTargetLowering()->getTargetMachine().getPointerSize(AS: 0);
69 if (STI.isTargetXPLINK64())
70 return std::make_unique<SystemZXPLINKFrameLowering>(args&: PtrSz);
71 return std::make_unique<SystemZELFFrameLowering>(args&: PtrSz);
72}
73
74namespace {
75struct SZFrameSortingObj {
76 bool IsValid = false; // True if we care about this Object.
77 uint32_t ObjectIndex = 0; // Index of Object into MFI list.
78 uint64_t ObjectSize = 0; // Size of Object in bytes.
79 uint32_t D12Count = 0; // 12-bit displacement only.
80 uint32_t DPairCount = 0; // 12 or 20 bit displacement.
81};
82typedef std::vector<SZFrameSortingObj> SZFrameObjVec;
83} // namespace
84
85// TODO: Move to base class.
86void SystemZELFFrameLowering::orderFrameObjects(
87 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
88 const MachineFrameInfo &MFI = MF.getFrameInfo();
89 auto *TII = MF.getSubtarget<SystemZSubtarget>().getInstrInfo();
90
91 // Make a vector of sorting objects to track all MFI objects and mark those
92 // to be sorted as valid.
93 if (ObjectsToAllocate.size() <= 1)
94 return;
95 SZFrameObjVec SortingObjects(MFI.getObjectIndexEnd());
96 for (auto &Obj : ObjectsToAllocate) {
97 SortingObjects[Obj].IsValid = true;
98 SortingObjects[Obj].ObjectIndex = Obj;
99 SortingObjects[Obj].ObjectSize = MFI.getObjectSize(ObjectIdx: Obj);
100 }
101
102 // Examine uses for each object and record short (12-bit) and "pair"
103 // displacement types.
104 for (auto &MBB : MF)
105 for (auto &MI : MBB) {
106 if (MI.isDebugInstr())
107 continue;
108 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
109 const MachineOperand &MO = MI.getOperand(i: I);
110 if (!MO.isFI())
111 continue;
112 int Index = MO.getIndex();
113 if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
114 SortingObjects[Index].IsValid) {
115 if (TII->hasDisplacementPairInsn(Opcode: MI.getOpcode()))
116 SortingObjects[Index].DPairCount++;
117 else if (!(MI.getDesc().TSFlags & SystemZII::Has20BitOffset))
118 SortingObjects[Index].D12Count++;
119 }
120 }
121 }
122
123 // Sort all objects for short/paired displacements, which should be
124 // sufficient as it seems like all frame objects typically are within the
125 // long displacement range. Sorting works by computing the "density" as
126 // Count / ObjectSize. The comparisons of two such fractions are refactored
127 // by multiplying both sides with A.ObjectSize * B.ObjectSize, in order to
128 // eliminate the (fp) divisions. A higher density object needs to go after
129 // in the list in order for it to end up lower on the stack.
130 auto CmpD12 = [](const SZFrameSortingObj &A, const SZFrameSortingObj &B) {
131 // Put all invalid and variable sized objects at the end.
132 if (!A.IsValid || !B.IsValid)
133 return A.IsValid;
134 if (!A.ObjectSize || !B.ObjectSize)
135 return A.ObjectSize > 0;
136 uint64_t ADensityCmp = A.D12Count * B.ObjectSize;
137 uint64_t BDensityCmp = B.D12Count * A.ObjectSize;
138 if (ADensityCmp != BDensityCmp)
139 return ADensityCmp < BDensityCmp;
140 return A.DPairCount * B.ObjectSize < B.DPairCount * A.ObjectSize;
141 };
142 llvm::stable_sort(Range&: SortingObjects, C: CmpD12);
143
144 // Now modify the original list to represent the final order that
145 // we want.
146 unsigned Idx = 0;
147 for (auto &Obj : SortingObjects) {
148 // All invalid items are sorted at the end, so it's safe to stop.
149 if (!Obj.IsValid)
150 break;
151 ObjectsToAllocate[Idx++] = Obj.ObjectIndex;
152 }
153}
154
155bool SystemZFrameLowering::hasReservedCallFrame(
156 const MachineFunction &MF) const {
157 // The ELF ABI requires us to allocate 160 bytes of stack space for the
158 // callee, with any outgoing stack arguments being placed above that. It
159 // seems better to make that area a permanent feature of the frame even if
160 // we're using a frame pointer. Similarly, 64-bit XPLINK requires 96 bytes
161 // of stack space for the register save area.
162 return true;
163}
164
165bool SystemZELFFrameLowering::assignCalleeSavedSpillSlots(
166 MachineFunction &MF, const TargetRegisterInfo *TRI,
167 std::vector<CalleeSavedInfo> &CSI) const {
168 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
169 MachineFrameInfo &MFFrame = MF.getFrameInfo();
170 bool IsVarArg = MF.getFunction().isVarArg();
171 if (CSI.empty())
172 return true; // Early exit if no callee saved registers are modified!
173
174 unsigned LowGPR = 0;
175 unsigned HighGPR = SystemZ::R15D;
176 int StartSPOffset = SystemZMC::ELFCallFrameSize;
177 for (auto &CS : CSI) {
178 MCRegister Reg = CS.getReg();
179 int Offset = getRegSpillOffset(MF, Reg);
180 if (Offset) {
181 if (SystemZ::GR64BitRegClass.contains(Reg) && StartSPOffset > Offset) {
182 LowGPR = Reg;
183 StartSPOffset = Offset;
184 }
185 Offset -= SystemZMC::ELFCallFrameSize;
186 int FrameIdx =
187 MFFrame.CreateFixedSpillStackObject(Size: getPointerSize(), SPOffset: Offset);
188 CS.setFrameIdx(FrameIdx);
189 } else
190 CS.setFrameIdx(INT32_MAX);
191 }
192
193 // Save the range of call-saved registers, for use by the
194 // prologue/epilogue inserters.
195 ZFI->setRestoreGPRRegs(Low: LowGPR, High: HighGPR, Offs: StartSPOffset);
196 if (IsVarArg) {
197 // Also save the GPR varargs, if any. R6D is call-saved, so would
198 // already be included, but we also need to handle the call-clobbered
199 // argument registers.
200 Register FirstGPR = ZFI->getVarArgsFirstGPR();
201 if (FirstGPR < SystemZ::ELFNumArgGPRs) {
202 unsigned Reg = SystemZ::ELFArgGPRs[FirstGPR];
203 int Offset = getRegSpillOffset(MF, Reg);
204 if (StartSPOffset > Offset) {
205 LowGPR = Reg; StartSPOffset = Offset;
206 }
207 }
208 }
209 ZFI->setSpillGPRRegs(Low: LowGPR, High: HighGPR, Offs: StartSPOffset);
210
211 // Create fixed stack objects for the remaining registers.
212 int CurrOffset = -SystemZMC::ELFCallFrameSize;
213 if (usePackedStack(MF))
214 CurrOffset += StartSPOffset;
215
216 for (auto &CS : CSI) {
217 if (CS.getFrameIdx() != INT32_MAX)
218 continue;
219 MCRegister Reg = CS.getReg();
220 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
221 unsigned Size = TRI->getSpillSize(RC: *RC);
222 CurrOffset -= Size;
223 assert(CurrOffset % 8 == 0 &&
224 "8-byte alignment required for for all register save slots");
225 int FrameIdx = MFFrame.CreateFixedSpillStackObject(Size, SPOffset: CurrOffset);
226 CS.setFrameIdx(FrameIdx);
227 }
228
229 return true;
230}
231
232void SystemZELFFrameLowering::determineCalleeSaves(MachineFunction &MF,
233 BitVector &SavedRegs,
234 RegScavenger *RS) const {
235 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
236
237 MachineFrameInfo &MFFrame = MF.getFrameInfo();
238 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
239 bool HasFP = hasFP(MF);
240 SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
241 bool IsVarArg = MF.getFunction().isVarArg();
242
243 // va_start stores incoming FPR varargs in the normal way, but delegates
244 // the saving of incoming GPR varargs to spillCalleeSavedRegisters().
245 // Record these pending uses, which typically include the call-saved
246 // argument register R6D.
247 if (IsVarArg)
248 for (unsigned I = MFI->getVarArgsFirstGPR(); I < SystemZ::ELFNumArgGPRs; ++I)
249 SavedRegs.set(SystemZ::ELFArgGPRs[I]);
250
251 // If there are any landing pads, entering them will modify r6/r7.
252 if (!MF.getLandingPads().empty()) {
253 SavedRegs.set(SystemZ::R6D);
254 SavedRegs.set(SystemZ::R7D);
255 }
256
257 // If the function requires a frame pointer, record that the hard
258 // frame pointer will be clobbered.
259 if (HasFP)
260 SavedRegs.set(SystemZ::R11D);
261
262 // If the function calls other functions, record that the return
263 // address register will be clobbered.
264 if (MFFrame.hasCalls())
265 SavedRegs.set(SystemZ::R14D);
266
267 // If we are saving GPRs other than the stack pointer, we might as well
268 // save and restore the stack pointer at the same time, via STMG and LMG.
269 // This allows the deallocation to be done by the LMG, rather than needing
270 // a separate %r15 addition.
271 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(MF: &MF);
272 for (unsigned I = 0; CSRegs[I]; ++I) {
273 unsigned Reg = CSRegs[I];
274 if (SystemZ::GR64BitRegClass.contains(Reg) && SavedRegs.test(Idx: Reg)) {
275 SavedRegs.set(SystemZ::R15D);
276 break;
277 }
278 }
279}
280
281SystemZELFFrameLowering::SystemZELFFrameLowering(unsigned PointerSize)
282 : SystemZFrameLowering(TargetFrameLowering::StackGrowsDown, Align(8), 0,
283 Align(8), /* StackRealignable */ false, PointerSize),
284 RegSpillOffsets(0) {
285
286 // Due to the SystemZ ABI, the DWARF CFA (Canonical Frame Address) is not
287 // equal to the incoming stack pointer, but to incoming stack pointer plus
288 // 160. Instead of using a Local Area Offset, the Register save area will
289 // be occupied by fixed frame objects, and all offsets are actually
290 // relative to CFA.
291
292 // Create a mapping from register number to save slot offset.
293 // These offsets are relative to the start of the register save area.
294 RegSpillOffsets.grow(N: SystemZ::NUM_TARGET_REGS);
295 for (const auto &Entry : ELFSpillOffsetTable)
296 RegSpillOffsets[Entry.Reg] = Entry.Offset;
297}
298
299// Add GPR64 to the save instruction being built by MIB, which is in basic
300// block MBB. IsImplicit says whether this is an explicit operand to the
301// instruction, or an implicit one that comes between the explicit start
302// and end registers.
303static void addSavedGPR(MachineBasicBlock &MBB, MachineInstrBuilder &MIB,
304 unsigned GPR64, bool IsImplicit) {
305 const TargetRegisterInfo *RI =
306 MBB.getParent()->getSubtarget().getRegisterInfo();
307 Register GPR32 = RI->getSubReg(Reg: GPR64, Idx: SystemZ::subreg_l32);
308 bool IsLive = MBB.isLiveIn(Reg: GPR64) || MBB.isLiveIn(Reg: GPR32);
309 if (!IsLive || !IsImplicit) {
310 MIB.addReg(RegNo: GPR64, Flags: getImplRegState(B: IsImplicit) | getKillRegState(B: !IsLive));
311 if (!IsLive)
312 MBB.addLiveIn(PhysReg: GPR64);
313 }
314}
315
316bool SystemZELFFrameLowering::spillCalleeSavedRegisters(
317 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
318 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
319 if (CSI.empty())
320 return false;
321
322 MachineFunction &MF = *MBB.getParent();
323 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
324 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
325 bool IsVarArg = MF.getFunction().isVarArg();
326 DebugLoc DL;
327
328 // Save GPRs
329 SystemZ::GPRRegs SpillGPRs = ZFI->getSpillGPRRegs();
330 if (SpillGPRs.LowGPR) {
331 assert(SpillGPRs.LowGPR != SpillGPRs.HighGPR &&
332 "Should be saving %r15 and something else");
333
334 // Build an STMG instruction.
335 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::STMG));
336
337 // Add the explicit register operands.
338 addSavedGPR(MBB, MIB, GPR64: SpillGPRs.LowGPR, IsImplicit: false);
339 addSavedGPR(MBB, MIB, GPR64: SpillGPRs.HighGPR, IsImplicit: false);
340
341 // Add the address.
342 MIB.addReg(RegNo: SystemZ::R15D).addImm(Val: SpillGPRs.GPROffset);
343
344 // Make sure all call-saved GPRs are included as operands and are
345 // marked as live on entry.
346 for (const CalleeSavedInfo &I : CSI) {
347 MCRegister Reg = I.getReg();
348 if (SystemZ::GR64BitRegClass.contains(Reg))
349 addSavedGPR(MBB, MIB, GPR64: Reg, IsImplicit: true);
350 }
351
352 // ...likewise GPR varargs.
353 if (IsVarArg)
354 for (unsigned I = ZFI->getVarArgsFirstGPR(); I < SystemZ::ELFNumArgGPRs; ++I)
355 addSavedGPR(MBB, MIB, GPR64: SystemZ::ELFArgGPRs[I], IsImplicit: true);
356 }
357
358 // Save FPRs/VRs in the normal TargetInstrInfo way.
359 for (const CalleeSavedInfo &I : CSI) {
360 MCRegister Reg = I.getReg();
361 if (SystemZ::FP64BitRegClass.contains(Reg)) {
362 MBB.addLiveIn(PhysReg: Reg);
363 TII->storeRegToStackSlot(MBB, MI: MBBI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(),
364 RC: &SystemZ::FP64BitRegClass, VReg: Register());
365 }
366 if (SystemZ::VR128BitRegClass.contains(Reg)) {
367 MBB.addLiveIn(PhysReg: Reg);
368 TII->storeRegToStackSlot(MBB, MI: MBBI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(),
369 RC: &SystemZ::VR128BitRegClass, VReg: Register());
370 }
371 }
372
373 return true;
374}
375
376bool SystemZELFFrameLowering::restoreCalleeSavedRegisters(
377 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
378 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
379 if (CSI.empty())
380 return false;
381
382 MachineFunction &MF = *MBB.getParent();
383 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
384 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
385 bool HasFP = hasFP(MF);
386 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
387
388 // Restore FPRs/VRs in the normal TargetInstrInfo way.
389 for (const CalleeSavedInfo &I : CSI) {
390 MCRegister Reg = I.getReg();
391 if (SystemZ::FP64BitRegClass.contains(Reg))
392 TII->loadRegFromStackSlot(MBB, MI: MBBI, DestReg: Reg, FrameIndex: I.getFrameIdx(),
393 RC: &SystemZ::FP64BitRegClass, VReg: Register());
394 if (SystemZ::VR128BitRegClass.contains(Reg))
395 TII->loadRegFromStackSlot(MBB, MI: MBBI, DestReg: Reg, FrameIndex: I.getFrameIdx(),
396 RC: &SystemZ::VR128BitRegClass, VReg: Register());
397 }
398
399 // Restore call-saved GPRs (but not call-clobbered varargs, which at
400 // this point might hold return values).
401 SystemZ::GPRRegs RestoreGPRs = ZFI->getRestoreGPRRegs();
402 if (RestoreGPRs.LowGPR) {
403 // If we saved any of %r2-%r5 as varargs, we should also be saving
404 // and restoring %r6. If we're saving %r6 or above, we should be
405 // restoring it too.
406 assert(RestoreGPRs.LowGPR != RestoreGPRs.HighGPR &&
407 "Should be loading %r15 and something else");
408
409 // Build an LMG instruction.
410 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::LMG));
411
412 // Add the explicit register operands.
413 MIB.addReg(RegNo: RestoreGPRs.LowGPR, Flags: RegState::Define);
414 MIB.addReg(RegNo: RestoreGPRs.HighGPR, Flags: RegState::Define);
415
416 // Add the address.
417 MIB.addReg(RegNo: HasFP ? SystemZ::R11D : SystemZ::R15D);
418 MIB.addImm(Val: RestoreGPRs.GPROffset);
419
420 // Do a second scan adding regs as being defined by instruction
421 for (const CalleeSavedInfo &I : CSI) {
422 MCRegister Reg = I.getReg();
423 if (Reg != RestoreGPRs.LowGPR && Reg != RestoreGPRs.HighGPR &&
424 SystemZ::GR64BitRegClass.contains(Reg))
425 MIB.addReg(RegNo: Reg, Flags: RegState::ImplicitDefine);
426 }
427 }
428
429 return true;
430}
431
432void SystemZELFFrameLowering::processFunctionBeforeFrameFinalized(
433 MachineFunction &MF, RegScavenger *RS) const {
434 MachineFrameInfo &MFFrame = MF.getFrameInfo();
435 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
436 MachineRegisterInfo *MRI = &MF.getRegInfo();
437 bool BackChain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
438
439 if (!usePackedStack(MF) || BackChain)
440 // Create the incoming register save area.
441 getOrCreateFramePointerSaveIndex(MF);
442
443 // Get the size of our stack frame to be allocated ...
444 uint64_t StackSize = (MFFrame.estimateStackSize(MF) +
445 SystemZMC::ELFCallFrameSize);
446 // ... and the maximum offset we may need to reach into the
447 // caller's frame to access the save area or stack arguments.
448 int64_t MaxArgOffset = 0;
449 for (int I = MFFrame.getObjectIndexBegin(); I != 0; ++I)
450 if (MFFrame.getObjectOffset(ObjectIdx: I) >= 0) {
451 int64_t ArgOffset = MFFrame.getObjectOffset(ObjectIdx: I) +
452 MFFrame.getObjectSize(ObjectIdx: I);
453 MaxArgOffset = std::max(a: MaxArgOffset, b: ArgOffset);
454 }
455
456 uint64_t MaxReach = StackSize + MaxArgOffset;
457 if (!isUInt<12>(x: MaxReach)) {
458 // We may need register scavenging slots if some parts of the frame
459 // are outside the reach of an unsigned 12-bit displacement.
460 // Create 2 for the case where both addresses in an MVC are
461 // out of range.
462 RS->addScavengingFrameIndex(
463 FI: MFFrame.CreateSpillStackObject(Size: getPointerSize(), Alignment: Align(8)));
464 RS->addScavengingFrameIndex(
465 FI: MFFrame.CreateSpillStackObject(Size: getPointerSize(), Alignment: Align(8)));
466 }
467
468 // If R6 is used as an argument register it is still callee saved. If it in
469 // this case is not clobbered (and restored) it should never be marked as
470 // killed.
471 if (MF.front().isLiveIn(Reg: SystemZ::R6D) &&
472 ZFI->getRestoreGPRRegs().LowGPR != SystemZ::R6D)
473 for (auto &MO : MRI->use_nodbg_operands(Reg: SystemZ::R6D))
474 MO.setIsKill(false);
475}
476
477// Emit instructions before MBBI (in MBB) to add NumBytes to Reg.
478static void emitIncrement(MachineBasicBlock &MBB,
479 MachineBasicBlock::iterator &MBBI, const DebugLoc &DL,
480 Register Reg, int64_t NumBytes,
481 const TargetInstrInfo *TII) {
482 while (NumBytes) {
483 unsigned Opcode;
484 int64_t ThisVal = NumBytes;
485 if (isInt<16>(x: NumBytes))
486 Opcode = SystemZ::AGHI;
487 else {
488 Opcode = SystemZ::AGFI;
489 // Make sure we maintain 8-byte stack alignment.
490 int64_t MinVal = -uint64_t(1) << 31;
491 int64_t MaxVal = (int64_t(1) << 31) - 8;
492 if (ThisVal < MinVal)
493 ThisVal = MinVal;
494 else if (ThisVal > MaxVal)
495 ThisVal = MaxVal;
496 }
497 MachineInstr *MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode), DestReg: Reg)
498 .addReg(RegNo: Reg).addImm(Val: ThisVal);
499 // The CC implicit def is dead.
500 MI->getOperand(i: 3).setIsDead();
501 NumBytes -= ThisVal;
502 }
503}
504
505// Add CFI for the new CFA offset.
506static void buildCFAOffs(MachineBasicBlock &MBB,
507 MachineBasicBlock::iterator MBBI,
508 const DebugLoc &DL, int Offset,
509 const SystemZInstrInfo *ZII) {
510 unsigned CFIIndex = MBB.getParent()->addFrameInst(
511 Inst: MCCFIInstruction::cfiDefCfaOffset(L: nullptr, Offset: -Offset));
512 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: TargetOpcode::CFI_INSTRUCTION))
513 .addCFIIndex(CFIIndex);
514}
515
516// Add CFI for the new frame location.
517static void buildDefCFAReg(MachineBasicBlock &MBB,
518 MachineBasicBlock::iterator MBBI,
519 const DebugLoc &DL, unsigned Reg,
520 const SystemZInstrInfo *ZII) {
521 MachineFunction &MF = *MBB.getParent();
522 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
523 unsigned RegNum = MRI->getDwarfRegNum(Reg, isEH: true);
524 unsigned CFIIndex = MF.addFrameInst(
525 Inst: MCCFIInstruction::createDefCfaRegister(L: nullptr, Register: RegNum));
526 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: TargetOpcode::CFI_INSTRUCTION))
527 .addCFIIndex(CFIIndex);
528}
529
530void SystemZELFFrameLowering::emitPrologue(MachineFunction &MF,
531 MachineBasicBlock &MBB) const {
532 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
533 const SystemZSubtarget &STI = MF.getSubtarget<SystemZSubtarget>();
534 const SystemZTargetLowering &TLI = *STI.getTargetLowering();
535 MachineFrameInfo &MFFrame = MF.getFrameInfo();
536 auto *ZII = STI.getInstrInfo();
537 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
538 MachineBasicBlock::iterator MBBI = MBB.begin();
539 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
540 const std::vector<CalleeSavedInfo> &CSI = MFFrame.getCalleeSavedInfo();
541 bool HasFP = hasFP(MF);
542
543 // In GHC calling convention C stack space, including the ABI-defined
544 // 160-byte base area, is (de)allocated by GHC itself. This stack space may
545 // be used by LLVM as spill slots for the tail recursive GHC functions. Thus
546 // do not allocate stack space here, too.
547 if (MF.getFunction().getCallingConv() == CallingConv::GHC) {
548 if (MFFrame.getStackSize() > 2048 * sizeof(long)) {
549 report_fatal_error(
550 reason: "Pre allocated stack space for GHC function is too small");
551 }
552 if (HasFP) {
553 report_fatal_error(
554 reason: "In GHC calling convention a frame pointer is not supported");
555 }
556 MFFrame.setStackSize(MFFrame.getStackSize() + SystemZMC::ELFCallFrameSize);
557 return;
558 }
559
560 // Debug location must be unknown since the first debug location is used
561 // to determine the end of the prologue.
562 DebugLoc DL;
563 // Add mcount instrumentation if necessary.
564 if (MF.getFunction()
565 .getFnAttribute(Kind: "systemz-instrument-function-entry")
566 .getValueAsString() == "mcount") {
567
568 // Store return address 8 bytes above stack pointer.
569 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::STG))
570 .addReg(RegNo: SystemZ::R14D)
571 .addReg(RegNo: SystemZ::R15D)
572 .addImm(Val: 8)
573 .addReg(RegNo: 0);
574
575 // Call mcount (Regmask from CC AnyReg since mcount preserves all normal
576 // argument registers).
577 const uint32_t *Mask = MF.getSubtarget<SystemZSubtarget>()
578 .getSpecialRegisters()
579 ->getCallPreservedMask(MF, CC: CallingConv::AnyReg);
580 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::CallBRASL))
581 .addExternalSymbol(FnName: "mcount")
582 .addRegMask(Mask);
583
584 // Reload return address from 8 bytes above stack pointer.
585 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LG))
586 .addReg(RegNo: SystemZ::R14D, Flags: RegState::Define)
587 .addReg(RegNo: SystemZ::R15D)
588 .addImm(Val: 8)
589 .addReg(RegNo: 0);
590 }
591
592 // The current offset of the stack pointer from the CFA.
593 int64_t SPOffsetFromCFA = -SystemZMC::ELFCFAOffsetFromInitialSP;
594
595 if (ZFI->getSpillGPRRegs().LowGPR) {
596 // Skip over the GPR saves.
597 if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
598 ++MBBI;
599 else
600 llvm_unreachable("Couldn't skip over GPR saves");
601
602 // Add CFI for the GPR saves.
603 for (auto &Save : CSI) {
604 MCRegister Reg = Save.getReg();
605 if (SystemZ::GR64BitRegClass.contains(Reg)) {
606 int FI = Save.getFrameIdx();
607 int64_t Offset = MFFrame.getObjectOffset(ObjectIdx: FI);
608 unsigned CFIIndex = MF.addFrameInst(Inst: MCCFIInstruction::createOffset(
609 L: nullptr, Register: MRI->getDwarfRegNum(Reg, isEH: true), Offset));
610 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: TargetOpcode::CFI_INSTRUCTION))
611 .addCFIIndex(CFIIndex);
612 }
613 }
614 }
615
616 uint64_t StackSize = MFFrame.getStackSize();
617 // We need to allocate the ABI-defined 160-byte base area whenever
618 // we allocate stack space for our own use and whenever we call another
619 // function.
620 bool HasStackObject = false;
621 for (unsigned i = 0, e = MFFrame.getObjectIndexEnd(); i != e; ++i)
622 if (!MFFrame.isDeadObjectIndex(ObjectIdx: i)) {
623 HasStackObject = true;
624 break;
625 }
626 if (HasStackObject || MFFrame.hasCalls())
627 StackSize += SystemZMC::ELFCallFrameSize;
628 // Don't allocate the incoming reg save area.
629 StackSize = StackSize > SystemZMC::ELFCallFrameSize
630 ? StackSize - SystemZMC::ELFCallFrameSize
631 : 0;
632 MFFrame.setStackSize(StackSize);
633
634 if (StackSize) {
635 // Allocate StackSize bytes.
636 int64_t Delta = -int64_t(StackSize);
637 const unsigned ProbeSize = TLI.getStackProbeSize(MF);
638 bool FreeProbe = (ZFI->getSpillGPRRegs().GPROffset &&
639 (ZFI->getSpillGPRRegs().GPROffset + StackSize) < ProbeSize);
640 if (!FreeProbe &&
641 MF.getSubtarget().getTargetLowering()->hasInlineStackProbe(MF)) {
642 // Stack probing may involve looping, but splitting the prologue block
643 // is not possible at this point since it would invalidate the
644 // SaveBlocks / RestoreBlocks sets of PEI in the single block function
645 // case. Build a pseudo to be handled later by inlineStackProbe().
646 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::PROBED_STACKALLOC))
647 .addImm(Val: StackSize);
648 }
649 else {
650 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
651 // If we need backchain, save current stack pointer. R1 is free at
652 // this point.
653 if (StoreBackchain)
654 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
655 .addReg(RegNo: SystemZ::R1D, Flags: RegState::Define).addReg(RegNo: SystemZ::R15D);
656 emitIncrement(MBB, MBBI, DL, Reg: SystemZ::R15D, NumBytes: Delta, TII: ZII);
657 buildCFAOffs(MBB, MBBI, DL, Offset: SPOffsetFromCFA + Delta, ZII);
658 if (StoreBackchain)
659 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::STG))
660 .addReg(RegNo: SystemZ::R1D, Flags: RegState::Kill).addReg(RegNo: SystemZ::R15D)
661 .addImm(Val: getBackchainOffset(MF)).addReg(RegNo: 0);
662 }
663 SPOffsetFromCFA += Delta;
664 }
665
666 if (HasFP) {
667 // Copy the base of the frame to R11.
668 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR), DestReg: SystemZ::R11D)
669 .addReg(RegNo: SystemZ::R15D);
670
671 // Add CFI for the new frame location.
672 buildDefCFAReg(MBB, MBBI, DL, Reg: SystemZ::R11D, ZII);
673
674 // Mark the FramePtr as live at the beginning of every block except
675 // the entry block. (We'll have marked R11 as live on entry when
676 // saving the GPRs.)
677 for (MachineBasicBlock &MBBJ : llvm::drop_begin(RangeOrContainer&: MF))
678 MBBJ.addLiveIn(PhysReg: SystemZ::R11D);
679 }
680
681 // Skip over the FPR/VR saves.
682 SmallVector<unsigned, 8> CFIIndexes;
683 for (auto &Save : CSI) {
684 MCRegister Reg = Save.getReg();
685 if (SystemZ::FP64BitRegClass.contains(Reg)) {
686 if (MBBI != MBB.end() &&
687 (MBBI->getOpcode() == SystemZ::STD ||
688 MBBI->getOpcode() == SystemZ::STDY))
689 ++MBBI;
690 else
691 llvm_unreachable("Couldn't skip over FPR save");
692 } else if (SystemZ::VR128BitRegClass.contains(Reg)) {
693 if (MBBI != MBB.end() &&
694 MBBI->getOpcode() == SystemZ::VST)
695 ++MBBI;
696 else
697 llvm_unreachable("Couldn't skip over VR save");
698 } else
699 continue;
700
701 // Add CFI for the this save.
702 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, isEH: true);
703 Register IgnoredFrameReg;
704 int64_t Offset =
705 getFrameIndexReference(MF, FI: Save.getFrameIdx(), FrameReg&: IgnoredFrameReg)
706 .getFixed();
707
708 unsigned CFIIndex = MF.addFrameInst(Inst: MCCFIInstruction::createOffset(
709 L: nullptr, Register: DwarfReg, Offset: SPOffsetFromCFA + Offset));
710 CFIIndexes.push_back(Elt: CFIIndex);
711 }
712 // Complete the CFI for the FPR/VR saves, modelling them as taking effect
713 // after the last save.
714 for (auto CFIIndex : CFIIndexes) {
715 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: TargetOpcode::CFI_INSTRUCTION))
716 .addCFIIndex(CFIIndex);
717 }
718}
719
720void SystemZELFFrameLowering::emitEpilogue(MachineFunction &MF,
721 MachineBasicBlock &MBB) const {
722 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
723 auto *ZII =
724 static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
725 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
726 MachineFrameInfo &MFFrame = MF.getFrameInfo();
727
728 // See SystemZELFFrameLowering::emitPrologue
729 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
730 return;
731
732 // Skip the return instruction.
733 assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
734
735 uint64_t StackSize = MFFrame.getStackSize();
736 if (ZFI->getRestoreGPRRegs().LowGPR) {
737 --MBBI;
738 unsigned Opcode = MBBI->getOpcode();
739 if (Opcode != SystemZ::LMG)
740 llvm_unreachable("Expected to see callee-save register restore code");
741
742 unsigned AddrOpNo = 2;
743 DebugLoc DL = MBBI->getDebugLoc();
744 uint64_t Offset = StackSize + MBBI->getOperand(i: AddrOpNo + 1).getImm();
745 unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
746
747 // If the offset is too large, use the largest stack-aligned offset
748 // and add the rest to the base register (the stack or frame pointer).
749 if (!NewOpcode) {
750 uint64_t NumBytes = Offset - 0x7fff8;
751 emitIncrement(MBB, MBBI, DL, Reg: MBBI->getOperand(i: AddrOpNo).getReg(),
752 NumBytes, TII: ZII);
753 Offset -= NumBytes;
754 NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
755 assert(NewOpcode && "No restore instruction available");
756 }
757
758 MBBI->setDesc(ZII->get(Opcode: NewOpcode));
759 MBBI->getOperand(i: AddrOpNo + 1).ChangeToImmediate(ImmVal: Offset);
760 } else if (StackSize) {
761 DebugLoc DL = MBBI->getDebugLoc();
762 emitIncrement(MBB, MBBI, DL, Reg: SystemZ::R15D, NumBytes: StackSize, TII: ZII);
763 }
764}
765
766void SystemZELFFrameLowering::inlineStackProbe(
767 MachineFunction &MF, MachineBasicBlock &PrologMBB) const {
768 auto *ZII =
769 static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
770 const SystemZSubtarget &STI = MF.getSubtarget<SystemZSubtarget>();
771 const SystemZTargetLowering &TLI = *STI.getTargetLowering();
772
773 MachineInstr *StackAllocMI = nullptr;
774 for (MachineInstr &MI : PrologMBB)
775 if (MI.getOpcode() == SystemZ::PROBED_STACKALLOC) {
776 StackAllocMI = &MI;
777 break;
778 }
779 if (StackAllocMI == nullptr)
780 return;
781 uint64_t StackSize = StackAllocMI->getOperand(i: 0).getImm();
782 const unsigned ProbeSize = TLI.getStackProbeSize(MF);
783 uint64_t NumFullBlocks = StackSize / ProbeSize;
784 uint64_t Residual = StackSize % ProbeSize;
785 int64_t SPOffsetFromCFA = -SystemZMC::ELFCFAOffsetFromInitialSP;
786 MachineBasicBlock *MBB = &PrologMBB;
787 MachineBasicBlock::iterator MBBI = StackAllocMI;
788 const DebugLoc DL = StackAllocMI->getDebugLoc();
789
790 // Allocate a block of Size bytes on the stack and probe it.
791 auto allocateAndProbe = [&](MachineBasicBlock &InsMBB,
792 MachineBasicBlock::iterator InsPt, unsigned Size,
793 bool EmitCFI) -> void {
794 emitIncrement(MBB&: InsMBB, MBBI&: InsPt, DL, Reg: SystemZ::R15D, NumBytes: -int64_t(Size), TII: ZII);
795 if (EmitCFI) {
796 SPOffsetFromCFA -= Size;
797 buildCFAOffs(MBB&: InsMBB, MBBI: InsPt, DL, Offset: SPOffsetFromCFA, ZII);
798 }
799 // Probe by means of a volatile compare.
800 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo: MachinePointerInfo(),
801 F: MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad, Size: 8, BaseAlignment: Align(1));
802 BuildMI(BB&: InsMBB, I: InsPt, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::CG))
803 .addReg(RegNo: SystemZ::R0D, Flags: RegState::Undef)
804 .addReg(RegNo: SystemZ::R15D).addImm(Val: Size - 8).addReg(RegNo: 0)
805 .addMemOperand(MMO);
806 };
807
808 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
809 if (StoreBackchain)
810 BuildMI(BB&: *MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
811 .addReg(RegNo: SystemZ::R1D, Flags: RegState::Define).addReg(RegNo: SystemZ::R15D);
812
813 MachineBasicBlock *DoneMBB = nullptr;
814 MachineBasicBlock *LoopMBB = nullptr;
815 if (NumFullBlocks < 3) {
816 // Emit unrolled probe statements.
817 for (unsigned int i = 0; i < NumFullBlocks; i++)
818 allocateAndProbe(*MBB, MBBI, ProbeSize, true/*EmitCFI*/);
819 } else {
820 // Emit a loop probing the pages.
821 uint64_t LoopAlloc = ProbeSize * NumFullBlocks;
822 SPOffsetFromCFA -= LoopAlloc;
823
824 // Use R0D to hold the exit value.
825 BuildMI(BB&: *MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR), DestReg: SystemZ::R0D)
826 .addReg(RegNo: SystemZ::R15D);
827 buildDefCFAReg(MBB&: *MBB, MBBI, DL, Reg: SystemZ::R0D, ZII);
828 emitIncrement(MBB&: *MBB, MBBI, DL, Reg: SystemZ::R0D, NumBytes: -int64_t(LoopAlloc), TII: ZII);
829 buildCFAOffs(MBB&: *MBB, MBBI, DL, Offset: -int64_t(SystemZMC::ELFCallFrameSize + LoopAlloc),
830 ZII);
831
832 DoneMBB = SystemZ::splitBlockBefore(MI: MBBI, MBB);
833 LoopMBB = SystemZ::emitBlockAfter(MBB);
834 MBB->addSuccessor(Succ: LoopMBB);
835 LoopMBB->addSuccessor(Succ: LoopMBB);
836 LoopMBB->addSuccessor(Succ: DoneMBB);
837
838 MBB = LoopMBB;
839 allocateAndProbe(*MBB, MBB->end(), ProbeSize, false/*EmitCFI*/);
840 BuildMI(BB&: *MBB, I: MBB->end(), MIMD: DL, MCID: ZII->get(Opcode: SystemZ::CLGR))
841 .addReg(RegNo: SystemZ::R15D).addReg(RegNo: SystemZ::R0D);
842 BuildMI(BB&: *MBB, I: MBB->end(), MIMD: DL, MCID: ZII->get(Opcode: SystemZ::BRC))
843 .addImm(Val: SystemZ::CCMASK_ICMP).addImm(Val: SystemZ::CCMASK_CMP_GT).addMBB(MBB);
844
845 MBB = DoneMBB;
846 MBBI = DoneMBB->begin();
847 buildDefCFAReg(MBB&: *MBB, MBBI, DL, Reg: SystemZ::R15D, ZII);
848 }
849
850 if (Residual)
851 allocateAndProbe(*MBB, MBBI, Residual, true/*EmitCFI*/);
852
853 if (StoreBackchain)
854 BuildMI(BB&: *MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::STG))
855 .addReg(RegNo: SystemZ::R1D, Flags: RegState::Kill).addReg(RegNo: SystemZ::R15D)
856 .addImm(Val: getBackchainOffset(MF)).addReg(RegNo: 0);
857
858 StackAllocMI->eraseFromParent();
859 if (DoneMBB != nullptr) {
860 // Compute the live-in lists for the new blocks.
861 fullyRecomputeLiveIns(MBBs: {DoneMBB, LoopMBB});
862 }
863}
864
865bool SystemZELFFrameLowering::hasFPImpl(const MachineFunction &MF) const {
866 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
867 MF.getFrameInfo().hasVarSizedObjects());
868}
869
870StackOffset SystemZELFFrameLowering::getFrameIndexReference(
871 const MachineFunction &MF, int FI, Register &FrameReg) const {
872 // Our incoming SP is actually SystemZMC::ELFCallFrameSize below the CFA, so
873 // add that difference here.
874 StackOffset Offset =
875 TargetFrameLowering::getFrameIndexReference(MF, FI, FrameReg);
876 return Offset + StackOffset::getFixed(Fixed: SystemZMC::ELFCallFrameSize);
877}
878
879unsigned SystemZELFFrameLowering::getRegSpillOffset(MachineFunction &MF,
880 Register Reg) const {
881 bool IsVarArg = MF.getFunction().isVarArg();
882 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
883 bool BackChain = Subtarget.hasBackChain();
884 bool SoftFloat = Subtarget.hasSoftFloat();
885 unsigned Offset = RegSpillOffsets[Reg];
886 if (usePackedStack(MF) && !(IsVarArg && !SoftFloat)) {
887 if (SystemZ::GR64BitRegClass.contains(Reg))
888 // Put all GPRs at the top of the Register save area with packed
889 // stack. Make room for the backchain if needed.
890 Offset += BackChain ? 24 : 32;
891 else
892 Offset = 0;
893 }
894 return Offset;
895}
896
897int SystemZELFFrameLowering::getOrCreateFramePointerSaveIndex(
898 MachineFunction &MF) const {
899 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
900 int FI = ZFI->getFramePointerSaveIndex();
901 if (!FI) {
902 MachineFrameInfo &MFFrame = MF.getFrameInfo();
903 int Offset = getBackchainOffset(MF) - SystemZMC::ELFCallFrameSize;
904 FI = MFFrame.CreateFixedObject(Size: getPointerSize(), SPOffset: Offset, IsImmutable: false);
905 ZFI->setFramePointerSaveIndex(FI);
906 }
907 return FI;
908}
909
910bool SystemZELFFrameLowering::usePackedStack(MachineFunction &MF) const {
911 bool HasPackedStackAttr = MF.getFunction().hasFnAttribute(Kind: "packed-stack");
912 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
913 bool BackChain = Subtarget.hasBackChain();
914 bool SoftFloat = Subtarget.hasSoftFloat();
915 if (HasPackedStackAttr && BackChain && !SoftFloat)
916 report_fatal_error(reason: "packed-stack + backchain + hard-float is unsupported.");
917 bool CallConv = MF.getFunction().getCallingConv() != CallingConv::GHC;
918 return HasPackedStackAttr && CallConv;
919}
920
921SystemZXPLINKFrameLowering::SystemZXPLINKFrameLowering(unsigned PointerSize)
922 : SystemZFrameLowering(TargetFrameLowering::StackGrowsDown, Align(32), 0,
923 Align(32), /* StackRealignable */ false,
924 PointerSize),
925 RegSpillOffsets(-1) {
926
927 // Create a mapping from register number to save slot offset.
928 // These offsets are relative to the start of the local are area.
929 RegSpillOffsets.grow(N: SystemZ::NUM_TARGET_REGS);
930 for (const auto &Entry : XPLINKSpillOffsetTable)
931 RegSpillOffsets[Entry.Reg] = Entry.Offset;
932}
933
934int SystemZXPLINKFrameLowering::getOrCreateFramePointerSaveIndex(
935 MachineFunction &MF) const {
936 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
937 int FI = ZFI->getFramePointerSaveIndex();
938 if (!FI) {
939 MachineFrameInfo &MFFrame = MF.getFrameInfo();
940 FI = MFFrame.CreateFixedObject(Size: getPointerSize(), SPOffset: 0, IsImmutable: false);
941 MFFrame.setStackID(ObjectIdx: FI, ID: TargetStackID::NoAlloc);
942 ZFI->setFramePointerSaveIndex(FI);
943 }
944 return FI;
945}
946
947// Checks if the function is a potential candidate for being a XPLeaf routine.
948static bool isXPLeafCandidate(const MachineFunction &MF) {
949 const MachineFrameInfo &MFFrame = MF.getFrameInfo();
950 const MachineRegisterInfo &MRI = MF.getRegInfo();
951 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
952 auto *Regs =
953 static_cast<SystemZXPLINK64Registers *>(Subtarget.getSpecialRegisters());
954
955 // If function calls other functions including alloca, then it is not a XPLeaf
956 // routine.
957 if (MFFrame.hasCalls())
958 return false;
959
960 // If the function has var Sized Objects, then it is not a XPLeaf routine.
961 if (MFFrame.hasVarSizedObjects())
962 return false;
963
964 // If the function adjusts the stack, then it is not a XPLeaf routine.
965 if (MFFrame.adjustsStack())
966 return false;
967
968 // If function modifies the stack pointer register, then it is not a XPLeaf
969 // routine.
970 if (MRI.isPhysRegModified(PhysReg: Regs->getStackPointerRegister()))
971 return false;
972
973 // If function modifies the ADA register, then it is not a XPLeaf routine.
974 if (MRI.isPhysRegModified(PhysReg: Regs->getAddressOfCalleeRegister()))
975 return false;
976
977 // If function modifies the return address register, then it is not a XPLeaf
978 // routine.
979 if (MRI.isPhysRegModified(PhysReg: Regs->getReturnFunctionAddressRegister()))
980 return false;
981
982 // If the backchain pointer should be stored, then it is not a XPLeaf routine.
983 if (MF.getSubtarget<SystemZSubtarget>().hasBackChain())
984 return false;
985
986 // If function acquires its own stack frame, then it is not a XPLeaf routine.
987 // At the time this function is called, only slots for local variables are
988 // allocated, so this is a very rough estimate.
989 if (MFFrame.estimateStackSize(MF) > 0)
990 return false;
991
992 return true;
993}
994
995bool SystemZXPLINKFrameLowering::assignCalleeSavedSpillSlots(
996 MachineFunction &MF, const TargetRegisterInfo *TRI,
997 std::vector<CalleeSavedInfo> &CSI) const {
998 MachineFrameInfo &MFFrame = MF.getFrameInfo();
999 SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
1000 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1001 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1002 auto &GRRegClass = SystemZ::GR64BitRegClass;
1003
1004 // At this point, the result of isXPLeafCandidate() is not accurate because
1005 // the size of the save area has not yet been determined. If
1006 // isXPLeafCandidate() indicates a potential leaf function, and there are no
1007 // callee-save registers, then it is indeed a leaf function, and we can early
1008 // exit.
1009 // TODO: It is possible for leaf functions to use callee-saved registers.
1010 // It can use the 0-2k range between R4 and the caller's stack frame without
1011 // acquiring its own stack frame.
1012 bool IsLeaf = CSI.empty() && isXPLeafCandidate(MF);
1013 if (IsLeaf)
1014 return true;
1015
1016 // For non-leaf functions:
1017 // - the address of callee (entry point) register R6 must be saved
1018 CSI.push_back(x: CalleeSavedInfo(Regs.getAddressOfCalleeRegister()));
1019 CSI.back().setRestored(false);
1020
1021 // The return address register R7 must be saved and restored.
1022 CSI.push_back(x: CalleeSavedInfo(Regs.getReturnFunctionAddressRegister()));
1023
1024 // If the function needs a frame pointer, or if the backchain pointer should
1025 // be stored, then save the stack pointer register R4.
1026 if (hasFP(MF) || Subtarget.hasBackChain())
1027 CSI.push_back(x: CalleeSavedInfo(Regs.getStackPointerRegister()));
1028
1029 // If this function has an associated personality function then the
1030 // environment register R5 must be saved in the DSA.
1031 if (!MF.getLandingPads().empty()) {
1032 CSI.push_back(x: CalleeSavedInfo(Regs.getADARegister()));
1033 CSI.back().setRestored(false);
1034 }
1035
1036 // Scan the call-saved GPRs and find the bounds of the register spill area.
1037 Register LowRestoreGPR = 0;
1038 int LowRestoreOffset = INT32_MAX;
1039 Register LowSpillGPR = 0;
1040 int LowSpillOffset = INT32_MAX;
1041 Register HighGPR = 0;
1042 int HighOffset = -1;
1043
1044 // Query index of the saved frame pointer.
1045 int FPSI = MFI->getFramePointerSaveIndex();
1046
1047 for (auto &CS : CSI) {
1048 MCRegister Reg = CS.getReg();
1049 int Offset = RegSpillOffsets[Reg];
1050 if (Offset >= 0) {
1051 if (GRRegClass.contains(Reg)) {
1052 if (LowSpillOffset > Offset) {
1053 LowSpillOffset = Offset;
1054 LowSpillGPR = Reg;
1055 }
1056 if (CS.isRestored() && LowRestoreOffset > Offset) {
1057 LowRestoreOffset = Offset;
1058 LowRestoreGPR = Reg;
1059 }
1060
1061 if (Offset > HighOffset) {
1062 HighOffset = Offset;
1063 HighGPR = Reg;
1064 }
1065 // Non-volatile GPRs are saved in the dedicated register save area at
1066 // the bottom of the stack and are not truly part of the "normal" stack
1067 // frame. Mark the frame index as NoAlloc to indicate it as such.
1068 unsigned RegSize = getPointerSize();
1069 int FrameIdx =
1070 (FPSI && Offset == 0)
1071 ? FPSI
1072 : MFFrame.CreateFixedSpillStackObject(Size: RegSize, SPOffset: Offset);
1073 CS.setFrameIdx(FrameIdx);
1074 MFFrame.setStackID(ObjectIdx: FrameIdx, ID: TargetStackID::NoAlloc);
1075 }
1076 } else {
1077 MCRegister Reg = CS.getReg();
1078 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1079 Align Alignment = TRI->getSpillAlign(RC: *RC);
1080 unsigned Size = TRI->getSpillSize(RC: *RC);
1081 Alignment = std::min(a: Alignment, b: getStackAlign());
1082 int FrameIdx = MFFrame.CreateStackObject(Size, Alignment, isSpillSlot: true);
1083 CS.setFrameIdx(FrameIdx);
1084 }
1085 }
1086
1087 // Save the range of call-saved registers, for use by the
1088 // prologue/epilogue inserters.
1089 if (LowRestoreGPR)
1090 MFI->setRestoreGPRRegs(Low: LowRestoreGPR, High: HighGPR, Offs: LowRestoreOffset);
1091
1092 // Save the range of call-saved registers, for use by the epilogue inserter.
1093 assert(LowSpillGPR && "Expected registers to spill");
1094 MFI->setSpillGPRRegs(Low: LowSpillGPR, High: HighGPR, Offs: LowSpillOffset);
1095
1096 return true;
1097}
1098
1099void SystemZXPLINKFrameLowering::determineCalleeSaves(MachineFunction &MF,
1100 BitVector &SavedRegs,
1101 RegScavenger *RS) const {
1102 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1103
1104 bool HasFP = hasFP(MF);
1105 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1106 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1107
1108 // If the function requires a frame pointer, record that the hard
1109 // frame pointer will be clobbered.
1110 if (HasFP)
1111 SavedRegs.set(Regs.getFramePointerRegister());
1112}
1113
1114bool SystemZXPLINKFrameLowering::spillCalleeSavedRegisters(
1115 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1116 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1117 if (CSI.empty())
1118 return true;
1119
1120 MachineFunction &MF = *MBB.getParent();
1121 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1122 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1123 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1124 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1125 SystemZ::GPRRegs SpillGPRs = ZFI->getSpillGPRRegs();
1126 DebugLoc DL;
1127
1128 // Save GPRs
1129 if (SpillGPRs.LowGPR) {
1130 assert(SpillGPRs.LowGPR != SpillGPRs.HighGPR &&
1131 "Should be saving multiple registers");
1132
1133 // Build an STM/STMG instruction.
1134 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::STMG));
1135
1136 // Add the explicit register operands.
1137 addSavedGPR(MBB, MIB, GPR64: SpillGPRs.LowGPR, IsImplicit: false);
1138 addSavedGPR(MBB, MIB, GPR64: SpillGPRs.HighGPR, IsImplicit: false);
1139
1140 // Add the address r4
1141 MIB.addReg(RegNo: Regs.getStackPointerRegister());
1142
1143 // Add the partial offset
1144 // We cannot add the actual offset as, at the stack is not finalized
1145 MIB.addImm(Val: SpillGPRs.GPROffset);
1146
1147 // Make sure all call-saved GPRs are included as operands and are
1148 // marked as live on entry.
1149 auto &GRRegClass = SystemZ::GR64BitRegClass;
1150 for (const CalleeSavedInfo &I : CSI) {
1151 MCRegister Reg = I.getReg();
1152 if (GRRegClass.contains(Reg))
1153 addSavedGPR(MBB, MIB, GPR64: Reg, IsImplicit: true);
1154 }
1155 }
1156
1157 // Spill FPRs to the stack in the normal TargetInstrInfo way
1158 // Registers in CSI are in inverted order so registers with large
1159 // numbers will be assigned to high address.
1160 // Reverse the order at spilling and restoring so instructions on
1161 // registers with small numbers are emitted first.
1162 for (const CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
1163 MCRegister Reg = I.getReg();
1164 if (SystemZ::FP64BitRegClass.contains(Reg)) {
1165 MBB.addLiveIn(PhysReg: Reg);
1166 TII->storeRegToStackSlot(MBB, MI: MBBI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(),
1167 RC: &SystemZ::FP64BitRegClass, VReg: Register());
1168 }
1169 if (SystemZ::VR128BitRegClass.contains(Reg)) {
1170 MBB.addLiveIn(PhysReg: Reg);
1171 TII->storeRegToStackSlot(MBB, MI: MBBI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(),
1172 RC: &SystemZ::VR128BitRegClass, VReg: Register());
1173 }
1174 }
1175
1176 return true;
1177}
1178
1179bool SystemZXPLINKFrameLowering::restoreCalleeSavedRegisters(
1180 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1181 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1182
1183 if (CSI.empty())
1184 return false;
1185
1186 MachineFunction &MF = *MBB.getParent();
1187 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1188 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1189 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1190 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1191
1192 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1193
1194 // Restore FPRs in the normal TargetInstrInfo way.
1195 for (const CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
1196 MCRegister Reg = I.getReg();
1197 if (SystemZ::FP64BitRegClass.contains(Reg))
1198 TII->loadRegFromStackSlot(MBB, MI: MBBI, DestReg: Reg, FrameIndex: I.getFrameIdx(),
1199 RC: &SystemZ::FP64BitRegClass, VReg: Register());
1200 if (SystemZ::VR128BitRegClass.contains(Reg))
1201 TII->loadRegFromStackSlot(MBB, MI: MBBI, DestReg: Reg, FrameIndex: I.getFrameIdx(),
1202 RC: &SystemZ::VR128BitRegClass, VReg: Register());
1203 }
1204
1205 // Restore call-saved GPRs (but not call-clobbered varargs, which at
1206 // this point might hold return values).
1207 SystemZ::GPRRegs RestoreGPRs = ZFI->getRestoreGPRRegs();
1208 if (RestoreGPRs.LowGPR) {
1209 assert(isInt<20>(Regs.getStackPointerBias() + RestoreGPRs.GPROffset));
1210 if (RestoreGPRs.LowGPR == RestoreGPRs.HighGPR)
1211 // Build an LG/L instruction.
1212 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::LG), DestReg: RestoreGPRs.LowGPR)
1213 .addReg(RegNo: Regs.getStackPointerRegister())
1214 .addImm(Val: Regs.getStackPointerBias() + RestoreGPRs.GPROffset)
1215 .addReg(RegNo: 0);
1216 else {
1217 // Build an LMG/LM instruction.
1218 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::LMG));
1219
1220 // Add the explicit register operands.
1221 MIB.addReg(RegNo: RestoreGPRs.LowGPR, Flags: RegState::Define);
1222 MIB.addReg(RegNo: RestoreGPRs.HighGPR, Flags: RegState::Define);
1223
1224 // Add the address.
1225 MIB.addReg(RegNo: Regs.getStackPointerRegister());
1226 MIB.addImm(Val: Regs.getStackPointerBias() + RestoreGPRs.GPROffset);
1227
1228 // Do a second scan adding regs as being defined by instruction
1229 for (const CalleeSavedInfo &I : CSI) {
1230 MCRegister Reg = I.getReg();
1231 if (Reg > RestoreGPRs.LowGPR && Reg < RestoreGPRs.HighGPR)
1232 MIB.addReg(RegNo: Reg, Flags: RegState::ImplicitDefine);
1233 }
1234 }
1235 }
1236
1237 return true;
1238}
1239
1240void SystemZXPLINKFrameLowering::emitPrologue(MachineFunction &MF,
1241 MachineBasicBlock &MBB) const {
1242 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
1243 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1244 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1245 MachineBasicBlock::iterator MBBI = MBB.begin();
1246 auto *ZII = Subtarget.getInstrInfo();
1247 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1248 MachineFrameInfo &MFFrame = MF.getFrameInfo();
1249 MachineInstr *StoreInstr = nullptr;
1250
1251 determineFrameLayout(MF);
1252
1253 bool HasFP = hasFP(MF);
1254 // Debug location must be unknown since the first debug location is used
1255 // to determine the end of the prologue.
1256 DebugLoc DL;
1257 uint64_t Offset = 0;
1258
1259 const uint64_t StackSize = MFFrame.getStackSize();
1260
1261 if (ZFI->getSpillGPRRegs().LowGPR) {
1262 // Skip over the GPR saves.
1263 if ((MBBI != MBB.end()) && ((MBBI->getOpcode() == SystemZ::STMG))) {
1264 const int Operand = 3;
1265 // Now we can set the offset for the operation, since now the Stack
1266 // has been finalized.
1267 Offset = Regs.getStackPointerBias() + MBBI->getOperand(i: Operand).getImm();
1268 // Maximum displacement for STMG instruction.
1269 if (isInt<20>(x: Offset - StackSize))
1270 Offset -= StackSize;
1271 else
1272 StoreInstr = &*MBBI;
1273 MBBI->getOperand(i: Operand).setImm(Offset);
1274 ++MBBI;
1275 } else
1276 llvm_unreachable("Couldn't skip over GPR saves");
1277 }
1278
1279 if (StackSize) {
1280 MachineBasicBlock::iterator InsertPt = StoreInstr ? StoreInstr : MBBI;
1281 // Allocate StackSize bytes.
1282 int64_t Delta = -int64_t(StackSize);
1283
1284 // In case the STM(G) instruction also stores SP (R4), but the displacement
1285 // is too large, the SP register is manipulated first before storing,
1286 // resulting in the wrong value stored and retrieved later. In this case, we
1287 // need to temporarily save the value of SP, and store it later to memory.
1288 if (StoreInstr && HasFP) {
1289 // Insert LR r0,r4 before STMG instruction.
1290 BuildMI(BB&: MBB, I: InsertPt, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
1291 .addReg(RegNo: SystemZ::R0D, Flags: RegState::Define)
1292 .addReg(RegNo: SystemZ::R4D);
1293 // Insert ST r0,xxx(,r4) after STMG instruction.
1294 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::STG))
1295 .addReg(RegNo: SystemZ::R0D, Flags: RegState::Kill)
1296 .addReg(RegNo: SystemZ::R4D)
1297 .addImm(Val: Offset)
1298 .addReg(RegNo: 0);
1299 }
1300
1301 emitIncrement(MBB, MBBI&: InsertPt, DL, Reg: Regs.getStackPointerRegister(), NumBytes: Delta,
1302 TII: ZII);
1303
1304 // If the requested stack size is larger than the guard page, then we need
1305 // to check if we need to call the stack extender. This requires adding a
1306 // conditional branch, but splitting the prologue block is not possible at
1307 // this point since it would invalidate the SaveBlocks / RestoreBlocks sets
1308 // of PEI in the single block function case. Build a pseudo to be handled
1309 // later by inlineStackProbe().
1310 const uint64_t GuardPageSize = 1024 * 1024;
1311 if (StackSize > GuardPageSize) {
1312 assert(StoreInstr && "Wrong insertion point");
1313 BuildMI(BB&: MBB, I: InsertPt, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::XPLINK_STACKALLOC));
1314 }
1315 }
1316
1317 if (HasFP) {
1318 // Copy the base of the frame to Frame Pointer Register.
1319 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR),
1320 DestReg: Regs.getFramePointerRegister())
1321 .addReg(RegNo: Regs.getStackPointerRegister());
1322
1323 // Mark the FramePtr as live at the beginning of every block except
1324 // the entry block. (We'll have marked R8 as live on entry when
1325 // saving the GPRs.)
1326 for (MachineBasicBlock &B : llvm::drop_begin(RangeOrContainer&: MF))
1327 B.addLiveIn(PhysReg: Regs.getFramePointerRegister());
1328 }
1329
1330 // Save GPRs used for varargs, if any.
1331 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1332 bool IsVarArg = MF.getFunction().isVarArg();
1333
1334 if (IsVarArg) {
1335 // FixedRegs is the number of used registers, accounting for shadow
1336 // registers.
1337 unsigned FixedRegs = ZFI->getVarArgsFirstGPR() + ZFI->getVarArgsFirstFPR();
1338 auto &GPRs = SystemZ::XPLINK64ArgGPRs;
1339 for (unsigned I = FixedRegs; I < SystemZ::XPLINK64NumArgGPRs; I++) {
1340 uint64_t StartOffset = MFFrame.getOffsetAdjustment() +
1341 MFFrame.getStackSize() + Regs.getCallFrameSize() +
1342 getOffsetOfLocalArea() + I * getPointerSize();
1343 unsigned Reg = GPRs[I];
1344 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII->get(Opcode: SystemZ::STG))
1345 .addReg(RegNo: Reg)
1346 .addReg(RegNo: Regs.getStackPointerRegister())
1347 .addImm(Val: StartOffset)
1348 .addReg(RegNo: 0);
1349 if (!MBB.isLiveIn(Reg))
1350 MBB.addLiveIn(PhysReg: Reg);
1351 }
1352 }
1353}
1354
1355void SystemZXPLINKFrameLowering::emitEpilogue(MachineFunction &MF,
1356 MachineBasicBlock &MBB) const {
1357 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1358 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1359 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1360 MachineFrameInfo &MFFrame = MF.getFrameInfo();
1361 auto *ZII = Subtarget.getInstrInfo();
1362 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1363
1364 // Skip the return instruction.
1365 assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
1366
1367 uint64_t StackSize = MFFrame.getStackSize();
1368 if (StackSize) {
1369 unsigned SPReg = Regs.getStackPointerRegister();
1370 if (ZFI->getRestoreGPRRegs().LowGPR != SPReg) {
1371 DebugLoc DL = MBBI->getDebugLoc();
1372 emitIncrement(MBB, MBBI, DL, Reg: SPReg, NumBytes: StackSize, TII: ZII);
1373 }
1374 }
1375}
1376
1377// Emit a compare of the stack pointer against the stack floor, and a call to
1378// the LE stack extender if needed.
1379void SystemZXPLINKFrameLowering::inlineStackProbe(
1380 MachineFunction &MF, MachineBasicBlock &PrologMBB) const {
1381 auto *ZII =
1382 static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
1383
1384 MachineInstr *StackAllocMI = nullptr;
1385 for (MachineInstr &MI : PrologMBB)
1386 if (MI.getOpcode() == SystemZ::XPLINK_STACKALLOC) {
1387 StackAllocMI = &MI;
1388 break;
1389 }
1390 if (StackAllocMI == nullptr)
1391 return;
1392
1393 bool NeedSaveSP = hasFP(MF);
1394 bool NeedSaveArg = PrologMBB.isLiveIn(Reg: SystemZ::R3D);
1395 const int64_t SaveSlotR3 = 2192;
1396
1397 MachineBasicBlock &MBB = PrologMBB;
1398 const DebugLoc DL = StackAllocMI->getDebugLoc();
1399
1400 // The 2nd half of block MBB after split.
1401 MachineBasicBlock *NextMBB;
1402
1403 // Add new basic block for the call to the stack overflow function.
1404 MachineBasicBlock *StackExtMBB =
1405 MF.CreateMachineBasicBlock(BB: MBB.getBasicBlock());
1406 MF.push_back(MBB: StackExtMBB);
1407
1408 // LG r3,72(,r3)
1409 BuildMI(BB: StackExtMBB, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LG), DestReg: SystemZ::R3D)
1410 .addReg(RegNo: SystemZ::R3D)
1411 .addImm(Val: 72)
1412 .addReg(RegNo: 0);
1413 // BASR r3,r3
1414 BuildMI(BB: StackExtMBB, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::CallBASR_STACKEXT))
1415 .addReg(RegNo: SystemZ::R3D);
1416 if (NeedSaveArg) {
1417 if (!NeedSaveSP) {
1418 // LGR r0,r3
1419 BuildMI(BB&: MBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
1420 .addReg(RegNo: SystemZ::R0D, Flags: RegState::Define)
1421 .addReg(RegNo: SystemZ::R3D);
1422 } else {
1423 // In this case, the incoming value of r4 is saved in r0 so the
1424 // latter register is unavailable. Store r3 in its corresponding
1425 // slot in the parameter list instead. Do this at the start of
1426 // the prolog before r4 is manipulated by anything else.
1427 // STG r3, 2192(r4)
1428 BuildMI(BB&: MBB, I: MBB.begin(), MIMD: DL, MCID: ZII->get(Opcode: SystemZ::STG))
1429 .addReg(RegNo: SystemZ::R3D)
1430 .addReg(RegNo: SystemZ::R4D)
1431 .addImm(Val: SaveSlotR3)
1432 .addReg(RegNo: 0);
1433 }
1434 }
1435 // LLGT r3,1208
1436 BuildMI(BB&: MBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LLGT), DestReg: SystemZ::R3D)
1437 .addReg(RegNo: 0)
1438 .addImm(Val: 1208)
1439 .addReg(RegNo: 0);
1440 // CG r4,64(,r3)
1441 BuildMI(BB&: MBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::CG))
1442 .addReg(RegNo: SystemZ::R4D)
1443 .addReg(RegNo: SystemZ::R3D)
1444 .addImm(Val: 64)
1445 .addReg(RegNo: 0);
1446 // JLL b'0100',F'37'
1447 BuildMI(BB&: MBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::BRC))
1448 .addImm(Val: SystemZ::CCMASK_ICMP)
1449 .addImm(Val: SystemZ::CCMASK_CMP_LT)
1450 .addMBB(MBB: StackExtMBB);
1451
1452 NextMBB = SystemZ::splitBlockBefore(MI: StackAllocMI, MBB: &MBB);
1453 MBB.addSuccessor(Succ: NextMBB);
1454 MBB.addSuccessor(Succ: StackExtMBB);
1455 if (NeedSaveArg) {
1456 if (!NeedSaveSP) {
1457 // LGR r3, r0
1458 BuildMI(BB&: *NextMBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
1459 .addReg(RegNo: SystemZ::R3D, Flags: RegState::Define)
1460 .addReg(RegNo: SystemZ::R0D, Flags: RegState::Kill);
1461 } else {
1462 // In this case, the incoming value of r4 is saved in r0 so the
1463 // latter register is unavailable. We stored r3 in its corresponding
1464 // slot in the parameter list instead and we now restore it from there.
1465 // LGR r3, r0
1466 BuildMI(BB&: *NextMBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LGR))
1467 .addReg(RegNo: SystemZ::R3D, Flags: RegState::Define)
1468 .addReg(RegNo: SystemZ::R0D);
1469 // LG r3, 2192(r3)
1470 BuildMI(BB&: *NextMBB, I: StackAllocMI, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::LG))
1471 .addReg(RegNo: SystemZ::R3D, Flags: RegState::Define)
1472 .addReg(RegNo: SystemZ::R3D)
1473 .addImm(Val: SaveSlotR3)
1474 .addReg(RegNo: 0);
1475 }
1476 }
1477
1478 // Add jump back from stack extension BB.
1479 BuildMI(BB: StackExtMBB, MIMD: DL, MCID: ZII->get(Opcode: SystemZ::J)).addMBB(MBB: NextMBB);
1480 StackExtMBB->addSuccessor(Succ: NextMBB);
1481
1482 StackAllocMI->eraseFromParent();
1483
1484 // Compute the live-in lists for the new blocks.
1485 fullyRecomputeLiveIns(MBBs: {StackExtMBB, NextMBB});
1486}
1487
1488bool SystemZXPLINKFrameLowering::hasFPImpl(const MachineFunction &MF) const {
1489 return (MF.getFrameInfo().hasVarSizedObjects());
1490}
1491
1492void SystemZXPLINKFrameLowering::processFunctionBeforeFrameFinalized(
1493 MachineFunction &MF, RegScavenger *RS) const {
1494 MachineFrameInfo &MFFrame = MF.getFrameInfo();
1495 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1496 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1497
1498 // Setup stack frame offset
1499 MFFrame.setOffsetAdjustment(Regs.getStackPointerBias());
1500
1501 // Nothing to do for leaf functions.
1502 uint64_t StackSize = MFFrame.estimateStackSize(MF);
1503 if (StackSize == 0 && MFFrame.getCalleeSavedInfo().empty())
1504 return;
1505
1506 // Although the XPLINK specifications for AMODE64 state that minimum size
1507 // of the param area is minimum 32 bytes and no rounding is otherwise
1508 // specified, we round this area in 64 bytes increments to be compatible
1509 // with existing compilers.
1510 MFFrame.setMaxCallFrameSize(
1511 std::max(a: 64U, b: (unsigned)alignTo(Value: MFFrame.getMaxCallFrameSize(), Align: 64)));
1512
1513 // Add frame values with positive object offsets. Since the displacement from
1514 // the SP/FP is calculated by ObjectOffset + StackSize + Bias, object offsets
1515 // with positive values are in the caller's stack frame. We need to include
1516 // that since it is accessed by displacement to SP/FP.
1517 int64_t LargestArgOffset = 0;
1518 for (int I = MFFrame.getObjectIndexBegin(); I != 0; ++I) {
1519 if (MFFrame.getObjectOffset(ObjectIdx: I) >= 0) {
1520 int64_t ObjOffset = MFFrame.getObjectOffset(ObjectIdx: I) + MFFrame.getObjectSize(ObjectIdx: I);
1521 LargestArgOffset = std::max(a: ObjOffset, b: LargestArgOffset);
1522 }
1523 }
1524
1525 uint64_t MaxReach = (StackSize + Regs.getCallFrameSize() +
1526 Regs.getStackPointerBias() + LargestArgOffset);
1527
1528 if (!isUInt<12>(x: MaxReach)) {
1529 // We may need register scavenging slots if some parts of the frame
1530 // are outside the reach of an unsigned 12-bit displacement.
1531 RS->addScavengingFrameIndex(FI: MFFrame.CreateSpillStackObject(Size: 8, Alignment: Align(8)));
1532 RS->addScavengingFrameIndex(FI: MFFrame.CreateSpillStackObject(Size: 8, Alignment: Align(8)));
1533 }
1534}
1535
1536// Determines the size of the frame, and creates the deferred spill objects.
1537void SystemZXPLINKFrameLowering::determineFrameLayout(
1538 MachineFunction &MF) const {
1539 MachineFrameInfo &MFFrame = MF.getFrameInfo();
1540 const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1541 auto *Regs =
1542 static_cast<SystemZXPLINK64Registers *>(Subtarget.getSpecialRegisters());
1543
1544 uint64_t StackSize = MFFrame.getStackSize();
1545 if (StackSize == 0)
1546 return;
1547
1548 // Add the size of the register save area and the reserved area to the size.
1549 StackSize += Regs->getCallFrameSize();
1550 MFFrame.setStackSize(StackSize);
1551
1552 // We now know the stack size. Update the stack objects for the register save
1553 // area now. This has no impact on the stack frame layout, as this is already
1554 // computed. However, it makes sure that all callee saved registers have a
1555 // valid offset assigned.
1556 for (int FrameIdx = MFFrame.getObjectIndexBegin(); FrameIdx != 0;
1557 ++FrameIdx) {
1558 if (MFFrame.getStackID(ObjectIdx: FrameIdx) == TargetStackID::NoAlloc) {
1559 int64_t SPOffset = MFFrame.getObjectOffset(ObjectIdx: FrameIdx);
1560 SPOffset -= StackSize;
1561 MFFrame.setObjectOffset(ObjectIdx: FrameIdx, SPOffset);
1562 }
1563 }
1564}
1565