[SystemZ] Clean up register scavenging code
[oota-llvm.git] / lib / Target / SystemZ / SystemZFrameLowering.cpp
1 //===-- SystemZFrameLowering.cpp - Frame lowering for SystemZ -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "SystemZFrameLowering.h"
11 #include "SystemZCallingConv.h"
12 #include "SystemZInstrBuilder.h"
13 #include "SystemZMachineFunctionInfo.h"
14 #include "SystemZTargetMachine.h"
15 #include "llvm/CodeGen/MachineModuleInfo.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/CodeGen/RegisterScavenging.h"
18 #include "llvm/IR/Function.h"
19
20 using namespace llvm;
21
22 namespace {
23   // The ABI-defined register save slots, relative to the incoming stack
24   // pointer.
25   static const TargetFrameLowering::SpillSlot SpillOffsetTable[] = {
26     { SystemZ::R2D,  0x10 },
27     { SystemZ::R3D,  0x18 },
28     { SystemZ::R4D,  0x20 },
29     { SystemZ::R5D,  0x28 },
30     { SystemZ::R6D,  0x30 },
31     { SystemZ::R7D,  0x38 },
32     { SystemZ::R8D,  0x40 },
33     { SystemZ::R9D,  0x48 },
34     { SystemZ::R10D, 0x50 },
35     { SystemZ::R11D, 0x58 },
36     { SystemZ::R12D, 0x60 },
37     { SystemZ::R13D, 0x68 },
38     { SystemZ::R14D, 0x70 },
39     { SystemZ::R15D, 0x78 },
40     { SystemZ::F0D,  0x80 },
41     { SystemZ::F2D,  0x88 },
42     { SystemZ::F4D,  0x90 },
43     { SystemZ::F6D,  0x98 }
44   };
45 }
46
47 SystemZFrameLowering::SystemZFrameLowering(const SystemZTargetMachine &tm,
48                                            const SystemZSubtarget &sti)
49   : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 8,
50                         -SystemZMC::CallFrameSize, 8),
51     TM(tm), STI(sti) {
52   // Create a mapping from register number to save slot offset.
53   RegSpillOffsets.grow(SystemZ::NUM_TARGET_REGS);
54   for (unsigned I = 0, E = array_lengthof(SpillOffsetTable); I != E; ++I)
55     RegSpillOffsets[SpillOffsetTable[I].Reg] = SpillOffsetTable[I].Offset;
56 }
57
58 const TargetFrameLowering::SpillSlot *
59 SystemZFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
60   NumEntries = array_lengthof(SpillOffsetTable);
61   return SpillOffsetTable;
62 }
63
64 void SystemZFrameLowering::
65 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
66                                      RegScavenger *RS) const {
67   MachineFrameInfo *MFFrame = MF.getFrameInfo();
68   MachineRegisterInfo &MRI = MF.getRegInfo();
69   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
70   bool HasFP = hasFP(MF);
71   SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
72   bool IsVarArg = MF.getFunction()->isVarArg();
73
74   // va_start stores incoming FPR varargs in the normal way, but delegates
75   // the saving of incoming GPR varargs to spillCalleeSavedRegisters().
76   // Record these pending uses, which typically include the call-saved
77   // argument register R6D.
78   if (IsVarArg)
79     for (unsigned I = MFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
80       MRI.setPhysRegUsed(SystemZ::ArgGPRs[I]);
81
82   // If the function requires a frame pointer, record that the hard
83   // frame pointer will be clobbered.
84   if (HasFP)
85     MRI.setPhysRegUsed(SystemZ::R11D);
86
87   // If the function calls other functions, record that the return
88   // address register will be clobbered.
89   if (MFFrame->hasCalls())
90     MRI.setPhysRegUsed(SystemZ::R14D);
91
92   // If we are saving GPRs other than the stack pointer, we might as well
93   // save and restore the stack pointer at the same time, via STMG and LMG.
94   // This allows the deallocation to be done by the LMG, rather than needing
95   // a separate %r15 addition.
96   const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
97   for (unsigned I = 0; CSRegs[I]; ++I) {
98     unsigned Reg = CSRegs[I];
99     if (SystemZ::GR64BitRegClass.contains(Reg) && MRI.isPhysRegUsed(Reg)) {
100       MRI.setPhysRegUsed(SystemZ::R15D);
101       break;
102     }
103   }
104 }
105
106 // Add GPR64 to the save instruction being built by MIB, which is in basic
107 // block MBB.  IsImplicit says whether this is an explicit operand to the
108 // instruction, or an implicit one that comes between the explicit start
109 // and end registers.
110 static void addSavedGPR(MachineBasicBlock &MBB, MachineInstrBuilder &MIB,
111                         const SystemZTargetMachine &TM,
112                         unsigned GPR64, bool IsImplicit) {
113   const SystemZRegisterInfo *RI = TM.getRegisterInfo();
114   unsigned GPR32 = RI->getSubReg(GPR64, SystemZ::subreg_32bit);
115   bool IsLive = MBB.isLiveIn(GPR64) || MBB.isLiveIn(GPR32);
116   if (!IsLive || !IsImplicit) {
117     MIB.addReg(GPR64, getImplRegState(IsImplicit) | getKillRegState(!IsLive));
118     if (!IsLive)
119       MBB.addLiveIn(GPR64);
120   }
121 }
122
123 bool SystemZFrameLowering::
124 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
125                           MachineBasicBlock::iterator MBBI,
126                           const std::vector<CalleeSavedInfo> &CSI,
127                           const TargetRegisterInfo *TRI) const {
128   if (CSI.empty())
129     return false;
130
131   MachineFunction &MF = *MBB.getParent();
132   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
133   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
134   bool IsVarArg = MF.getFunction()->isVarArg();
135   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
136
137   // Scan the call-saved GPRs and find the bounds of the register spill area.
138   unsigned LowGPR = 0;
139   unsigned HighGPR = SystemZ::R15D;
140   unsigned StartOffset = -1U;
141   for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
142     unsigned Reg = CSI[I].getReg();
143     if (SystemZ::GR64BitRegClass.contains(Reg)) {
144       unsigned Offset = RegSpillOffsets[Reg];
145       assert(Offset && "Unexpected GPR save");
146       if (StartOffset > Offset) {
147         LowGPR = Reg;
148         StartOffset = Offset;
149       }
150     }
151   }
152
153   // Save the range of call-saved registers, for use by the epilogue inserter.
154   ZFI->setLowSavedGPR(LowGPR);
155   ZFI->setHighSavedGPR(HighGPR);
156
157   // Include the GPR varargs, if any.  R6D is call-saved, so would
158   // be included by the loop above, but we also need to handle the
159   // call-clobbered argument registers.
160   if (IsVarArg) {
161     unsigned FirstGPR = ZFI->getVarArgsFirstGPR();
162     if (FirstGPR < SystemZ::NumArgGPRs) {
163       unsigned Reg = SystemZ::ArgGPRs[FirstGPR];
164       unsigned Offset = RegSpillOffsets[Reg];
165       if (StartOffset > Offset) {
166         LowGPR = Reg; StartOffset = Offset;
167       }
168     }
169   }
170
171   // Save GPRs
172   if (LowGPR) {
173     assert(LowGPR != HighGPR && "Should be saving %r15 and something else");
174
175     // Build an STMG instruction.
176     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STMG));
177
178     // Add the explicit register operands.
179     addSavedGPR(MBB, MIB, TM, LowGPR, false);
180     addSavedGPR(MBB, MIB, TM, HighGPR, false);
181
182     // Add the address.
183     MIB.addReg(SystemZ::R15D).addImm(StartOffset);
184
185     // Make sure all call-saved GPRs are included as operands and are
186     // marked as live on entry.
187     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
188       unsigned Reg = CSI[I].getReg();
189       if (SystemZ::GR64BitRegClass.contains(Reg))
190         addSavedGPR(MBB, MIB, TM, Reg, true);
191     }
192
193     // ...likewise GPR varargs.
194     if (IsVarArg)
195       for (unsigned I = ZFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
196         addSavedGPR(MBB, MIB, TM, SystemZ::ArgGPRs[I], true);
197   }
198
199   // Save FPRs in the normal TargetInstrInfo way.
200   for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
201     unsigned Reg = CSI[I].getReg();
202     if (SystemZ::FP64BitRegClass.contains(Reg)) {
203       MBB.addLiveIn(Reg);
204       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, CSI[I].getFrameIdx(),
205                                &SystemZ::FP64BitRegClass, TRI);
206     }
207   }
208
209   return true;
210 }
211
212 bool SystemZFrameLowering::
213 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
214                             MachineBasicBlock::iterator MBBI,
215                             const std::vector<CalleeSavedInfo> &CSI,
216                             const TargetRegisterInfo *TRI) const {
217   if (CSI.empty())
218     return false;
219
220   MachineFunction &MF = *MBB.getParent();
221   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
222   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
223   bool HasFP = hasFP(MF);
224   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
225
226   // Restore FPRs in the normal TargetInstrInfo way.
227   for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
228     unsigned Reg = CSI[I].getReg();
229     if (SystemZ::FP64BitRegClass.contains(Reg))
230       TII->loadRegFromStackSlot(MBB, MBBI, Reg, CSI[I].getFrameIdx(),
231                                 &SystemZ::FP64BitRegClass, TRI);
232   }
233
234   // Restore call-saved GPRs (but not call-clobbered varargs, which at
235   // this point might hold return values).
236   unsigned LowGPR = ZFI->getLowSavedGPR();
237   unsigned HighGPR = ZFI->getHighSavedGPR();
238   unsigned StartOffset = RegSpillOffsets[LowGPR];
239   if (LowGPR) {
240     // If we saved any of %r2-%r5 as varargs, we should also be saving
241     // and restoring %r6.  If we're saving %r6 or above, we should be
242     // restoring it too.
243     assert(LowGPR != HighGPR && "Should be loading %r15 and something else");
244
245     // Build an LMG instruction.
246     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LMG));
247
248     // Add the explicit register operands.
249     MIB.addReg(LowGPR, RegState::Define);
250     MIB.addReg(HighGPR, RegState::Define);
251
252     // Add the address.
253     MIB.addReg(HasFP ? SystemZ::R11D : SystemZ::R15D);
254     MIB.addImm(StartOffset);
255
256     // Do a second scan adding regs as being defined by instruction
257     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
258       unsigned Reg = CSI[I].getReg();
259       if (Reg != LowGPR && Reg != HighGPR)
260         MIB.addReg(Reg, RegState::ImplicitDefine);
261     }
262   }
263
264   return true;
265 }
266
267 void SystemZFrameLowering::
268 processFunctionBeforeFrameFinalized(MachineFunction &MF,
269                                     RegScavenger *RS) const {
270   MachineFrameInfo *MFFrame = MF.getFrameInfo();
271   uint64_t MaxReach = (MFFrame->estimateStackSize(MF) +
272                        SystemZMC::CallFrameSize * 2);
273   if (!isUInt<12>(MaxReach))
274     // We may need a register scavenging slot if some parts of the frame
275     // are outside the reach of an unsigned 12-bit displacement.
276     RS->addScavengingFrameIndex(MFFrame->CreateStackObject(8, 8, false));
277 }
278
279 // Emit instructions before MBBI (in MBB) to add NumBytes to Reg.
280 static void emitIncrement(MachineBasicBlock &MBB,
281                           MachineBasicBlock::iterator &MBBI,
282                           const DebugLoc &DL,
283                           unsigned Reg, int64_t NumBytes,
284                           const TargetInstrInfo *TII) {
285   while (NumBytes) {
286     unsigned Opcode;
287     int64_t ThisVal = NumBytes;
288     if (isInt<16>(NumBytes))
289       Opcode = SystemZ::AGHI;
290     else {
291       Opcode = SystemZ::AGFI;
292       // Make sure we maintain 8-byte stack alignment.
293       int64_t MinVal = -int64_t(1) << 31;
294       int64_t MaxVal = (int64_t(1) << 31) - 8;
295       if (ThisVal < MinVal)
296         ThisVal = MinVal;
297       else if (ThisVal > MaxVal)
298         ThisVal = MaxVal;
299     }
300     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII->get(Opcode), Reg)
301       .addReg(Reg).addImm(ThisVal);
302     // The CC implicit def is dead.
303     MI->getOperand(3).setIsDead();
304     NumBytes -= ThisVal;
305   }
306 }
307
308 void SystemZFrameLowering::emitPrologue(MachineFunction &MF) const {
309   MachineBasicBlock &MBB = MF.front();
310   MachineFrameInfo *MFFrame = MF.getFrameInfo();
311   const SystemZInstrInfo *ZII =
312     static_cast<const SystemZInstrInfo*>(MF.getTarget().getInstrInfo());
313   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
314   MachineBasicBlock::iterator MBBI = MBB.begin();
315   MachineModuleInfo &MMI = MF.getMMI();
316   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
317   const std::vector<CalleeSavedInfo> &CSI = MFFrame->getCalleeSavedInfo();
318   bool HasFP = hasFP(MF);
319   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
320
321   // The current offset of the stack pointer from the CFA.
322   int64_t SPOffsetFromCFA = -SystemZMC::CFAOffsetFromInitialSP;
323
324   if (ZFI->getLowSavedGPR()) {
325     // Skip over the GPR saves.
326     if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
327       ++MBBI;
328     else
329       llvm_unreachable("Couldn't skip over GPR saves");
330
331     // Add CFI for the GPR saves.
332     MCSymbol *GPRSaveLabel = MMI.getContext().CreateTempSymbol();
333     BuildMI(MBB, MBBI, DL,
334             ZII->get(TargetOpcode::PROLOG_LABEL)).addSym(GPRSaveLabel);
335     for (std::vector<CalleeSavedInfo>::const_iterator
336            I = CSI.begin(), E = CSI.end(); I != E; ++I) {
337       unsigned Reg = I->getReg();
338       if (SystemZ::GR64BitRegClass.contains(Reg)) {
339         int64_t Offset = SPOffsetFromCFA + RegSpillOffsets[Reg];
340         MMI.addFrameInst(MCCFIInstruction::createOffset(
341             GPRSaveLabel, MRI->getDwarfRegNum(Reg, true), Offset));
342       }
343     }
344   }
345
346   uint64_t StackSize = getAllocatedStackSize(MF);
347   if (StackSize) {
348     // Allocate StackSize bytes.
349     int64_t Delta = -int64_t(StackSize);
350     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, Delta, ZII);
351
352     // Add CFI for the allocation.
353     MCSymbol *AdjustSPLabel = MMI.getContext().CreateTempSymbol();
354     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::PROLOG_LABEL))
355       .addSym(AdjustSPLabel);
356     MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(
357         AdjustSPLabel, SPOffsetFromCFA + Delta));
358     SPOffsetFromCFA += Delta;
359   }
360
361   if (HasFP) {
362     // Copy the base of the frame to R11.
363     BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R11D)
364       .addReg(SystemZ::R15D);
365
366     // Add CFI for the new frame location.
367     MCSymbol *SetFPLabel = MMI.getContext().CreateTempSymbol();
368     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::PROLOG_LABEL))
369       .addSym(SetFPLabel);
370     unsigned HardFP = MRI->getDwarfRegNum(SystemZ::R11D, true);
371     MMI.addFrameInst(
372         MCCFIInstruction::createDefCfaRegister(SetFPLabel, HardFP));
373
374     // Mark the FramePtr as live at the beginning of every block except
375     // the entry block.  (We'll have marked R11 as live on entry when
376     // saving the GPRs.)
377     for (MachineFunction::iterator
378            I = llvm::next(MF.begin()), E = MF.end(); I != E; ++I)
379       I->addLiveIn(SystemZ::R11D);
380   }
381
382   // Skip over the FPR saves.
383   MCSymbol *FPRSaveLabel = 0;
384   for (std::vector<CalleeSavedInfo>::const_iterator
385          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
386     unsigned Reg = I->getReg();
387     if (SystemZ::FP64BitRegClass.contains(Reg)) {
388       if (MBBI != MBB.end() &&
389           (MBBI->getOpcode() == SystemZ::STD ||
390            MBBI->getOpcode() == SystemZ::STDY))
391         ++MBBI;
392       else
393         llvm_unreachable("Couldn't skip over FPR save");
394
395       // Add CFI for the this save.
396       if (!FPRSaveLabel)
397         FPRSaveLabel = MMI.getContext().CreateTempSymbol();
398       unsigned Reg = MRI->getDwarfRegNum(I->getReg(), true);
399       int64_t Offset = getFrameIndexOffset(MF, I->getFrameIdx());
400       MMI.addFrameInst(MCCFIInstruction::createOffset(
401           FPRSaveLabel, Reg, SPOffsetFromCFA + Offset));
402     }
403   }
404   // Complete the CFI for the FPR saves, modelling them as taking effect
405   // after the last save.
406   if (FPRSaveLabel)
407     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::PROLOG_LABEL))
408       .addSym(FPRSaveLabel);
409 }
410
411 void SystemZFrameLowering::emitEpilogue(MachineFunction &MF,
412                                         MachineBasicBlock &MBB) const {
413   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
414   const SystemZInstrInfo *ZII =
415     static_cast<const SystemZInstrInfo*>(MF.getTarget().getInstrInfo());
416   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
417
418   // Skip the return instruction.
419   assert(MBBI->getOpcode() == SystemZ::RET &&
420          "Can only insert epilogue into returning blocks");
421
422   uint64_t StackSize = getAllocatedStackSize(MF);
423   if (ZFI->getLowSavedGPR()) {
424     --MBBI;
425     unsigned Opcode = MBBI->getOpcode();
426     if (Opcode != SystemZ::LMG)
427       llvm_unreachable("Expected to see callee-save register restore code");
428
429     unsigned AddrOpNo = 2;
430     DebugLoc DL = MBBI->getDebugLoc();
431     uint64_t Offset = StackSize + MBBI->getOperand(AddrOpNo + 1).getImm();
432     unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
433
434     // If the offset is too large, use the largest stack-aligned offset
435     // and add the rest to the base register (the stack or frame pointer).
436     if (!NewOpcode) {
437       uint64_t NumBytes = Offset - 0x7fff8;
438       emitIncrement(MBB, MBBI, DL, MBBI->getOperand(AddrOpNo).getReg(),
439                     NumBytes, ZII);
440       Offset -= NumBytes;
441       NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
442       assert(NewOpcode && "No restore instruction available");
443     }
444
445     MBBI->setDesc(ZII->get(NewOpcode));
446     MBBI->getOperand(AddrOpNo + 1).ChangeToImmediate(Offset);
447   } else if (StackSize) {
448     DebugLoc DL = MBBI->getDebugLoc();
449     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, StackSize, ZII);
450   }
451 }
452
453 bool SystemZFrameLowering::hasFP(const MachineFunction &MF) const {
454   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
455           MF.getFrameInfo()->hasVarSizedObjects() ||
456           MF.getInfo<SystemZMachineFunctionInfo>()->getManipulatesSP());
457 }
458
459 int SystemZFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
460                                               int FI) const {
461   const MachineFrameInfo *MFFrame = MF.getFrameInfo();
462
463   // Start with the offset of FI from the top of the caller-allocated frame
464   // (i.e. the top of the 160 bytes allocated by the caller).  This initial
465   // offset is therefore negative.
466   int64_t Offset = (MFFrame->getObjectOffset(FI) +
467                     MFFrame->getOffsetAdjustment());
468
469   // Make the offset relative to the incoming stack pointer.
470   Offset -= getOffsetOfLocalArea();
471
472   // Make the offset relative to the bottom of the frame.
473   Offset += getAllocatedStackSize(MF);
474
475   return Offset;
476 }
477
478 uint64_t SystemZFrameLowering::
479 getAllocatedStackSize(const MachineFunction &MF) const {
480   const MachineFrameInfo *MFFrame = MF.getFrameInfo();
481
482   // Start with the size of the local variables and spill slots.
483   uint64_t StackSize = MFFrame->getStackSize();
484
485   // We need to allocate the ABI-defined 160-byte base area whenever
486   // we allocate stack space for our own use and whenever we call another
487   // function.
488   if (StackSize || MFFrame->hasVarSizedObjects() || MFFrame->hasCalls())
489     StackSize += SystemZMC::CallFrameSize;
490
491   return StackSize;
492 }
493
494 bool
495 SystemZFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
496   // The ABI requires us to allocate 160 bytes of stack space for the callee,
497   // with any outgoing stack arguments being placed above that.  It seems
498   // better to make that area a permanent feature of the frame even if
499   // we're using a frame pointer.
500   return true;
501 }
502
503 void SystemZFrameLowering::
504 eliminateCallFramePseudoInstr(MachineFunction &MF,
505                               MachineBasicBlock &MBB,
506                               MachineBasicBlock::iterator MI) const {
507   switch (MI->getOpcode()) {
508   case SystemZ::ADJCALLSTACKDOWN:
509   case SystemZ::ADJCALLSTACKUP:
510     assert(hasReservedCallFrame(MF) &&
511            "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
512     MBB.erase(MI);
513     break;
514
515   default:
516     llvm_unreachable("Unexpected call frame instruction");
517   }
518 }