1 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the PPC implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCFrameLowering.h"
15 #include "PPCInstrBuilder.h"
16 #include "PPCInstrInfo.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Target/TargetOptions.h"
30 /// VRRegNo - Map from a numbered VR register to its enum value.
32 static const uint16_t VRRegNo[] = {
33 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
34 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
35 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
36 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
39 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
40 if (STI.isDarwinABI())
41 return STI.isPPC64() ? 16 : 8;
43 return STI.isPPC64() ? 16 : 4;
46 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
47 return STI.isELFv2ABI() ? 24 : 40;
50 static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
51 // For the Darwin ABI:
52 // We cannot use the TOC save slot (offset +20) in the PowerPC linkage area
53 // for saving the frame pointer (if needed.) While the published ABI has
54 // not used this slot since at least MacOSX 10.2, there is older code
55 // around that does use it, and that needs to continue to work.
56 if (STI.isDarwinABI())
57 return STI.isPPC64() ? -8U : -4U;
59 // SVR4 ABI: First slot in the general register save area.
60 return STI.isPPC64() ? -8U : -4U;
63 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
64 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
65 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
66 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
67 TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
68 FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)) {}
70 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
71 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
72 unsigned &NumEntries) const {
73 if (Subtarget.isDarwinABI()) {
75 if (Subtarget.isPPC64()) {
76 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
77 return &darwin64Offsets;
79 static const SpillSlot darwinOffsets = {PPC::R31, -4};
80 return &darwinOffsets;
84 // Early exit if not using the SVR4 ABI.
85 if (!Subtarget.isSVR4ABI()) {
90 // Note that the offsets here overlap, but this is fixed up in
91 // processFunctionBeforeFrameFinalized.
93 static const SpillSlot Offsets[] = {
94 // Floating-point register save area offsets.
114 // General register save area offsets.
134 // CR save area offset. We map each of the nonvolatile CR fields
135 // to the slot for CR2, which is the first of the nonvolatile CR
136 // fields to be assigned, so that we only allocate one save slot.
137 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
140 // VRSAVE save area offset.
143 // Vector register save area
157 static const SpillSlot Offsets64[] = {
158 // Floating-point register save area offsets.
178 // General register save area offsets.
198 // VRSAVE save area offset.
201 // Vector register save area
215 if (Subtarget.isPPC64()) {
216 NumEntries = array_lengthof(Offsets64);
220 NumEntries = array_lengthof(Offsets);
226 /// RemoveVRSaveCode - We have found that this function does not need any code
227 /// to manipulate the VRSAVE register, even though it uses vector registers.
228 /// This can happen when the only registers used are known to be live in or out
229 /// of the function. Remove all of the VRSAVE related code from the function.
230 /// FIXME: The removal of the code results in a compile failure at -O0 when the
231 /// function contains a function call, as the GPR containing original VRSAVE
232 /// contents is spilled and reloaded around the call. Without the prolog code,
233 /// the spill instruction refers to an undefined register. This code needs
234 /// to account for all uses of that GPR.
235 static void RemoveVRSaveCode(MachineInstr *MI) {
236 MachineBasicBlock *Entry = MI->getParent();
237 MachineFunction *MF = Entry->getParent();
239 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
240 MachineBasicBlock::iterator MBBI = MI;
242 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
243 MBBI->eraseFromParent();
245 bool RemovedAllMTVRSAVEs = true;
246 // See if we can find and remove the MTVRSAVE instruction from all of the
248 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
249 // If last instruction is a return instruction, add an epilogue
250 if (!I->empty() && I->back().isReturn()) {
251 bool FoundIt = false;
252 for (MBBI = I->end(); MBBI != I->begin(); ) {
254 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
255 MBBI->eraseFromParent(); // remove it.
260 RemovedAllMTVRSAVEs &= FoundIt;
264 // If we found and removed all MTVRSAVE instructions, remove the read of
266 if (RemovedAllMTVRSAVEs) {
268 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
270 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
271 MBBI->eraseFromParent();
274 // Finally, nuke the UPDATE_VRSAVE.
275 MI->eraseFromParent();
278 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
279 // instruction selector. Based on the vector registers that have been used,
280 // transform this into the appropriate ORI instruction.
281 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
282 MachineFunction *MF = MI->getParent()->getParent();
283 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
284 DebugLoc dl = MI->getDebugLoc();
286 unsigned UsedRegMask = 0;
287 for (unsigned i = 0; i != 32; ++i)
288 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
289 UsedRegMask |= 1 << (31-i);
291 // Live in and live out values already must be in the mask, so don't bother
293 for (MachineRegisterInfo::livein_iterator
294 I = MF->getRegInfo().livein_begin(),
295 E = MF->getRegInfo().livein_end(); I != E; ++I) {
296 unsigned RegNo = TRI->getEncodingValue(I->first);
297 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
298 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
301 // Live out registers appear as use operands on return instructions.
302 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
303 UsedRegMask != 0 && BI != BE; ++BI) {
304 const MachineBasicBlock &MBB = *BI;
305 if (MBB.empty() || !MBB.back().isReturn())
307 const MachineInstr &Ret = MBB.back();
308 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
309 const MachineOperand &MO = Ret.getOperand(I);
310 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
312 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
313 UsedRegMask &= ~(1 << (31-RegNo));
317 // If no registers are used, turn this into a copy.
318 if (UsedRegMask == 0) {
319 // Remove all VRSAVE code.
320 RemoveVRSaveCode(MI);
324 unsigned SrcReg = MI->getOperand(1).getReg();
325 unsigned DstReg = MI->getOperand(0).getReg();
327 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
328 if (DstReg != SrcReg)
329 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
331 .addImm(UsedRegMask);
333 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
334 .addReg(SrcReg, RegState::Kill)
335 .addImm(UsedRegMask);
336 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
337 if (DstReg != SrcReg)
338 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
340 .addImm(UsedRegMask >> 16);
342 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
343 .addReg(SrcReg, RegState::Kill)
344 .addImm(UsedRegMask >> 16);
346 if (DstReg != SrcReg)
347 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
349 .addImm(UsedRegMask >> 16);
351 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
352 .addReg(SrcReg, RegState::Kill)
353 .addImm(UsedRegMask >> 16);
355 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
356 .addReg(DstReg, RegState::Kill)
357 .addImm(UsedRegMask & 0xFFFF);
360 // Remove the old UPDATE_VRSAVE instruction.
361 MI->eraseFromParent();
364 static bool spillsCR(const MachineFunction &MF) {
365 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
366 return FuncInfo->isCRSpilled();
369 static bool spillsVRSAVE(const MachineFunction &MF) {
370 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
371 return FuncInfo->isVRSAVESpilled();
374 static bool hasSpills(const MachineFunction &MF) {
375 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
376 return FuncInfo->hasSpills();
379 static bool hasNonRISpills(const MachineFunction &MF) {
380 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
381 return FuncInfo->hasNonRISpills();
384 /// MustSaveLR - Return true if this function requires that we save the LR
385 /// register onto the stack in the prolog and restore it in the epilog of the
387 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
388 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
390 // We need a save/restore of LR if there is any def of LR (which is
391 // defined by calls, including the PIC setup sequence), or if there is
392 // some use of the LR stack slot (e.g. for builtin_return_address).
393 // (LR comes in 32 and 64 bit versions.)
394 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
395 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
398 /// determineFrameLayout - Determine the size of the frame and maximum call
400 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
402 bool UseEstimate) const {
403 MachineFrameInfo *MFI = MF.getFrameInfo();
405 // Get the number of bytes to allocate from the FrameInfo
407 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
409 // Get stack alignments. The frame must be aligned to the greatest of these:
410 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
411 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
412 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
414 const PPCRegisterInfo *RegInfo =
415 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
417 // If we are a leaf function, and use up to 224 bytes of stack space,
418 // don't have a frame pointer, calls, or dynamic alloca then we do not need
419 // to adjust the stack pointer (we fit in the Red Zone).
420 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
421 // stackless code if all local vars are reg-allocated.
422 bool DisableRedZone = MF.getFunction()->getAttributes().
423 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
424 unsigned LR = RegInfo->getRARegister();
425 if (!DisableRedZone &&
426 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
427 !Subtarget.isSVR4ABI() || // allocated locals.
429 FrameSize <= 224 && // Fits in red zone.
430 !MFI->hasVarSizedObjects() && // No dynamic alloca.
431 !MFI->adjustsStack() && // No calls.
432 !MustSaveLR(MF, LR) &&
433 !RegInfo->hasBasePointer(MF)) { // No special alignment.
436 MFI->setStackSize(0);
440 // Get the maximum call frame size of all the calls.
441 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
443 // Maximum call frame needs to be at least big enough for linkage area.
444 unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
445 Subtarget.isDarwinABI(),
446 Subtarget.isELFv2ABI());
447 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
449 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
450 // that allocations will be aligned.
451 if (MFI->hasVarSizedObjects())
452 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
454 // Update maximum call frame size.
456 MFI->setMaxCallFrameSize(maxCallFrameSize);
458 // Include call frame size in total.
459 FrameSize += maxCallFrameSize;
461 // Make sure the frame is aligned.
462 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
464 // Update frame info.
466 MFI->setStackSize(FrameSize);
471 // hasFP - Return true if the specified function actually has a dedicated frame
473 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
474 const MachineFrameInfo *MFI = MF.getFrameInfo();
475 // FIXME: This is pretty much broken by design: hasFP() might be called really
476 // early, before the stack layout was calculated and thus hasFP() might return
477 // true or false here depending on the time of call.
478 return (MFI->getStackSize()) && needsFP(MF);
481 // needsFP - Return true if the specified function should have a dedicated frame
482 // pointer register. This is true if the function has variable sized allocas or
483 // if frame pointer elimination is disabled.
484 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
485 const MachineFrameInfo *MFI = MF.getFrameInfo();
487 // Naked functions have no stack frame pushed, so we don't have a frame
489 if (MF.getFunction()->getAttributes().hasAttribute(
490 AttributeSet::FunctionIndex, Attribute::Naked))
493 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
494 MFI->hasVarSizedObjects() ||
495 MFI->hasStackMap() || MFI->hasPatchPoint() ||
496 (MF.getTarget().Options.GuaranteedTailCallOpt &&
497 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
500 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
501 bool is31 = needsFP(MF);
502 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
503 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
505 const PPCRegisterInfo *RegInfo =
506 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
507 bool HasBP = RegInfo->hasBasePointer(MF);
508 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
509 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
511 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
513 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
515 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
516 MachineOperand &MO = MBBI->getOperand(I);
520 switch (MO.getReg()) {
539 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
540 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
541 MachineBasicBlock::iterator MBBI = MBB.begin();
542 MachineFrameInfo *MFI = MF.getFrameInfo();
543 const PPCInstrInfo &TII =
544 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
545 const PPCRegisterInfo *RegInfo =
546 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
548 MachineModuleInfo &MMI = MF.getMMI();
549 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
551 bool needsCFI = MMI.hasDebugInfo() ||
552 MF.getFunction()->needsUnwindTableEntry();
553 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
555 // Get processor type.
556 bool isPPC64 = Subtarget.isPPC64();
558 bool isDarwinABI = Subtarget.isDarwinABI();
559 bool isSVR4ABI = Subtarget.isSVR4ABI();
560 bool isELFv2ABI = Subtarget.isELFv2ABI();
561 assert((isDarwinABI || isSVR4ABI) &&
562 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
564 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
567 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
568 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
569 HandleVRSaveUpdate(MBBI, TII);
574 // Move MBBI back to the beginning of the function.
577 // Work out frame sizes.
578 unsigned FrameSize = determineFrameLayout(MF);
579 int NegFrameSize = -FrameSize;
580 if (!isInt<32>(NegFrameSize))
581 llvm_unreachable("Unhandled stack size!");
583 if (MFI->isFrameAddressTaken())
584 replaceFPWithRealFP(MF);
586 // Check if the link register (LR) must be saved.
587 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
588 bool MustSaveLR = FI->mustSaveLR();
589 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
590 // Do we have a frame pointer and/or base pointer for this function?
591 bool HasFP = hasFP(MF);
592 bool HasBP = RegInfo->hasBasePointer(MF);
594 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
595 unsigned BPReg = RegInfo->getBaseRegister(MF);
596 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
597 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
598 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
599 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
600 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
601 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
603 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
605 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
607 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
609 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
611 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
613 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
615 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
617 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
620 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
621 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
622 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
623 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
624 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
625 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
627 int LROffset = getReturnSaveOffset();
632 MachineFrameInfo *FFI = MF.getFrameInfo();
633 int FPIndex = FI->getFramePointerSaveIndex();
634 assert(FPIndex && "No Frame Pointer Save Slot!");
635 FPOffset = FFI->getObjectOffset(FPIndex);
637 FPOffset = getFramePointerSaveOffset();
644 MachineFrameInfo *FFI = MF.getFrameInfo();
645 int BPIndex = FI->getBasePointerSaveIndex();
646 assert(BPIndex && "No Base Pointer Save Slot!");
647 BPOffset = FFI->getObjectOffset(BPIndex);
650 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
657 if (FI->usesPICBase()) {
658 MachineFrameInfo *FFI = MF.getFrameInfo();
659 int PBPIndex = FI->getPICBasePointerSaveIndex();
660 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
661 PBPOffset = FFI->getObjectOffset(PBPIndex);
664 // Get stack alignments.
665 unsigned MaxAlign = MFI->getMaxAlignment();
666 if (HasBP && MaxAlign > 1)
667 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
668 "Invalid alignment!");
670 // Frames of 32KB & larger require special handling because they cannot be
671 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
672 bool isLargeFrame = !isInt<16>(NegFrameSize);
675 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
677 assert((isPPC64 || MustSaveCRs.empty()) &&
678 "Prologue CR saving supported only in 64-bit mode");
680 if (!MustSaveCRs.empty()) { // will only occur for PPC64
681 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
682 // If only one or two CR fields are clobbered, it could be more
683 // efficient to use mfocrf to selectively save just those fields.
684 MachineInstrBuilder MIB =
685 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
686 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
687 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
691 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
692 BuildMI(MBB, MBBI, dl, StoreInst)
697 if (FI->usesPICBase())
698 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
699 BuildMI(MBB, MBBI, dl, StoreInst)
705 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
706 BuildMI(MBB, MBBI, dl, StoreInst)
712 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
713 BuildMI(MBB, MBBI, dl, StoreInst)
718 if (!MustSaveCRs.empty()) // will only occur for PPC64
719 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
720 .addReg(TempReg, getKillRegState(true))
724 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
725 if (!FrameSize) return;
727 // Adjust stack pointer: r1 += NegFrameSize.
728 // If there is a preferred stack alignment, align R1 now
731 // Save a copy of r1 as the base pointer.
732 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
737 if (HasBP && MaxAlign > 1) {
739 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
742 .addImm(64 - Log2_32(MaxAlign));
744 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
747 .addImm(32 - Log2_32(MaxAlign))
750 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
751 .addReg(ScratchReg, RegState::Kill)
752 .addImm(NegFrameSize);
754 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
755 .addImm(NegFrameSize >> 16);
756 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
757 .addReg(TempReg, RegState::Kill)
758 .addImm(NegFrameSize & 0xFFFF);
759 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
760 .addReg(ScratchReg, RegState::Kill)
761 .addReg(TempReg, RegState::Kill);
763 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
764 .addReg(SPReg, RegState::Kill)
768 } else if (!isLargeFrame) {
769 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
771 .addImm(NegFrameSize)
775 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
776 .addImm(NegFrameSize >> 16);
777 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
778 .addReg(ScratchReg, RegState::Kill)
779 .addImm(NegFrameSize & 0xFFFF);
780 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
781 .addReg(SPReg, RegState::Kill)
786 // Add Call Frame Information for the instructions we generated above.
791 // Define CFA in terms of BP. Do this in preference to using FP/SP,
792 // because if the stack needed aligning then CFA won't be at a fixed
793 // offset from FP/SP.
794 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
795 CFIIndex = MMI.addFrameInst(
796 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
798 // Adjust the definition of CFA to account for the change in SP.
799 assert(NegFrameSize);
800 CFIIndex = MMI.addFrameInst(
801 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
803 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
804 .addCFIIndex(CFIIndex);
807 // Describe where FP was saved, at a fixed offset from CFA.
808 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
809 CFIIndex = MMI.addFrameInst(
810 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
811 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
812 .addCFIIndex(CFIIndex);
815 if (FI->usesPICBase()) {
816 // Describe where FP was saved, at a fixed offset from CFA.
817 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
818 CFIIndex = MMI.addFrameInst(
819 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
820 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
821 .addCFIIndex(CFIIndex);
825 // Describe where BP was saved, at a fixed offset from CFA.
826 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
827 CFIIndex = MMI.addFrameInst(
828 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
829 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
830 .addCFIIndex(CFIIndex);
834 // Describe where LR was saved, at a fixed offset from CFA.
835 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
836 CFIIndex = MMI.addFrameInst(
837 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
838 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
839 .addCFIIndex(CFIIndex);
843 // If there is a frame pointer, copy R1 into R31
845 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
849 if (!HasBP && needsCFI) {
850 // Change the definition of CFA from SP+offset to FP+offset, because SP
851 // will change at every alloca.
852 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
853 unsigned CFIIndex = MMI.addFrameInst(
854 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
856 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
857 .addCFIIndex(CFIIndex);
862 // Describe where callee saved registers were saved, at fixed offsets from
864 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
865 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
866 unsigned Reg = CSI[I].getReg();
867 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
869 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
870 // subregisters of CR2. We just need to emit a move of CR2.
871 if (PPC::CRBITRCRegClass.contains(Reg))
874 // For SVR4, don't emit a move for the CR spill slot if we haven't
876 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
877 && MustSaveCRs.empty())
880 // For 64-bit SVR4 when we have spilled CRs, the spill location
881 // is SP+8, not a frame-relative slot.
882 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
883 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
884 // the whole CR word. In the ELFv2 ABI, every CR that was
885 // actually saved gets its own CFI record.
886 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
887 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
888 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
889 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
890 .addCFIIndex(CFIIndex);
894 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
895 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
896 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
897 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
898 .addCFIIndex(CFIIndex);
903 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
904 MachineBasicBlock &MBB) const {
905 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
906 assert(MBBI != MBB.end() && "Returning block has no terminator");
907 const PPCInstrInfo &TII =
908 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
909 const PPCRegisterInfo *RegInfo =
910 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
912 unsigned RetOpcode = MBBI->getOpcode();
915 assert((RetOpcode == PPC::BLR ||
916 RetOpcode == PPC::BLR8 ||
917 RetOpcode == PPC::TCRETURNri ||
918 RetOpcode == PPC::TCRETURNdi ||
919 RetOpcode == PPC::TCRETURNai ||
920 RetOpcode == PPC::TCRETURNri8 ||
921 RetOpcode == PPC::TCRETURNdi8 ||
922 RetOpcode == PPC::TCRETURNai8) &&
923 "Can only insert epilog into returning blocks");
925 // Get alignment info so we know how to restore the SP.
926 const MachineFrameInfo *MFI = MF.getFrameInfo();
928 // Get the number of bytes allocated from the FrameInfo.
929 int FrameSize = MFI->getStackSize();
931 // Get processor type.
932 bool isPPC64 = Subtarget.isPPC64();
934 bool isDarwinABI = Subtarget.isDarwinABI();
935 bool isSVR4ABI = Subtarget.isSVR4ABI();
936 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
938 // Check if the link register (LR) has been saved.
939 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
940 bool MustSaveLR = FI->mustSaveLR();
941 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
942 // Do we have a frame pointer and/or base pointer for this function?
943 bool HasFP = hasFP(MF);
944 bool HasBP = RegInfo->hasBasePointer(MF);
946 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
947 unsigned BPReg = RegInfo->getBaseRegister(MF);
948 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
949 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
950 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
951 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
953 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
955 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
957 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
959 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
961 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
964 int LROffset = getReturnSaveOffset();
969 MachineFrameInfo *FFI = MF.getFrameInfo();
970 int FPIndex = FI->getFramePointerSaveIndex();
971 assert(FPIndex && "No Frame Pointer Save Slot!");
972 FPOffset = FFI->getObjectOffset(FPIndex);
974 FPOffset = getFramePointerSaveOffset();
981 MachineFrameInfo *FFI = MF.getFrameInfo();
982 int BPIndex = FI->getBasePointerSaveIndex();
983 assert(BPIndex && "No Base Pointer Save Slot!");
984 BPOffset = FFI->getObjectOffset(BPIndex);
987 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
994 if (FI->usesPICBase()) {
995 MachineFrameInfo *FFI = MF.getFrameInfo();
996 int PBPIndex = FI->getPICBasePointerSaveIndex();
997 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
998 PBPOffset = FFI->getObjectOffset(PBPIndex);
1001 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
1002 RetOpcode == PPC::TCRETURNdi ||
1003 RetOpcode == PPC::TCRETURNai ||
1004 RetOpcode == PPC::TCRETURNri8 ||
1005 RetOpcode == PPC::TCRETURNdi8 ||
1006 RetOpcode == PPC::TCRETURNai8;
1009 int MaxTCRetDelta = FI->getTailCallSPDelta();
1010 MachineOperand &StackAdjust = MBBI->getOperand(1);
1011 assert(StackAdjust.isImm() && "Expecting immediate value.");
1012 // Adjust stack pointer.
1013 int StackAdj = StackAdjust.getImm();
1014 int Delta = StackAdj - MaxTCRetDelta;
1015 assert((Delta >= 0) && "Delta must be positive");
1016 if (MaxTCRetDelta>0)
1017 FrameSize += (StackAdj +Delta);
1019 FrameSize += StackAdj;
1022 // Frames of 32KB & larger require special handling because they cannot be
1023 // indexed into with a simple LD/LWZ immediate offset operand.
1024 bool isLargeFrame = !isInt<16>(FrameSize);
1027 // In the prologue, the loaded (or persistent) stack pointer value is offset
1028 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
1030 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1031 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1032 // call which invalidates the stack pointer value in SP(0). So we use the
1033 // value of R31 in this case.
1034 if (FI->hasFastCall()) {
1035 assert(HasFP && "Expecting a valid frame pointer.");
1036 if (!isLargeFrame) {
1037 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1038 .addReg(FPReg).addImm(FrameSize);
1040 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1041 .addImm(FrameSize >> 16);
1042 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1043 .addReg(ScratchReg, RegState::Kill)
1044 .addImm(FrameSize & 0xFFFF);
1045 BuildMI(MBB, MBBI, dl, AddInst)
1048 .addReg(ScratchReg);
1050 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1051 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1055 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1063 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1067 assert((isPPC64 || MustSaveCRs.empty()) &&
1068 "Epilogue CR restoring supported only in 64-bit mode");
1070 if (!MustSaveCRs.empty()) // will only occur for PPC64
1071 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1076 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1080 if (FI->usesPICBase())
1081 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1082 BuildMI(MBB, MBBI, dl, LoadInst)
1088 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1092 if (!MustSaveCRs.empty()) // will only occur for PPC64
1093 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1094 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1095 .addReg(TempReg, getKillRegState(i == e-1));
1098 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1100 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1101 // call optimization
1102 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1103 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1104 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1105 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1106 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1108 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1109 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1110 .addReg(SPReg).addImm(CallerAllocatedAmt);
1112 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1113 .addImm(CallerAllocatedAmt >> 16);
1114 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1115 .addReg(ScratchReg, RegState::Kill)
1116 .addImm(CallerAllocatedAmt & 0xFFFF);
1117 BuildMI(MBB, MBBI, dl, AddInst)
1120 .addReg(ScratchReg);
1122 } else if (RetOpcode == PPC::TCRETURNdi) {
1123 MBBI = MBB.getLastNonDebugInstr();
1124 MachineOperand &JumpTarget = MBBI->getOperand(0);
1125 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1126 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1127 } else if (RetOpcode == PPC::TCRETURNri) {
1128 MBBI = MBB.getLastNonDebugInstr();
1129 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1130 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1131 } else if (RetOpcode == PPC::TCRETURNai) {
1132 MBBI = MBB.getLastNonDebugInstr();
1133 MachineOperand &JumpTarget = MBBI->getOperand(0);
1134 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1135 } else if (RetOpcode == PPC::TCRETURNdi8) {
1136 MBBI = MBB.getLastNonDebugInstr();
1137 MachineOperand &JumpTarget = MBBI->getOperand(0);
1138 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1139 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1140 } else if (RetOpcode == PPC::TCRETURNri8) {
1141 MBBI = MBB.getLastNonDebugInstr();
1142 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1143 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1144 } else if (RetOpcode == PPC::TCRETURNai8) {
1145 MBBI = MBB.getLastNonDebugInstr();
1146 MachineOperand &JumpTarget = MBBI->getOperand(0);
1147 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1152 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1153 RegScavenger *) const {
1154 const PPCRegisterInfo *RegInfo =
1155 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1157 // Save and clear the LR state.
1158 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1159 unsigned LR = RegInfo->getRARegister();
1160 FI->setMustSaveLR(MustSaveLR(MF, LR));
1161 MachineRegisterInfo &MRI = MF.getRegInfo();
1162 MRI.setPhysRegUnused(LR);
1164 // Save R31 if necessary
1165 int FPSI = FI->getFramePointerSaveIndex();
1166 bool isPPC64 = Subtarget.isPPC64();
1167 bool isDarwinABI = Subtarget.isDarwinABI();
1168 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1169 MachineFrameInfo *MFI = MF.getFrameInfo();
1171 // If the frame pointer save index hasn't been defined yet.
1172 if (!FPSI && needsFP(MF)) {
1173 // Find out what the fix offset of the frame pointer save area.
1174 int FPOffset = getFramePointerSaveOffset();
1175 // Allocate the frame index for frame pointer save area.
1176 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1178 FI->setFramePointerSaveIndex(FPSI);
1181 int BPSI = FI->getBasePointerSaveIndex();
1182 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1183 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1184 // Allocate the frame index for the base pointer save area.
1185 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1187 FI->setBasePointerSaveIndex(BPSI);
1190 // Reserve stack space for the PIC Base register (R30).
1191 // Only used in SVR4 32-bit.
1192 if (FI->usesPICBase()) {
1193 int PBPSI = FI->getPICBasePointerSaveIndex();
1194 PBPSI = MFI->CreateFixedObject(4, -8, true);
1195 FI->setPICBasePointerSaveIndex(PBPSI);
1198 // Reserve stack space to move the linkage area to in case of a tail call.
1200 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1201 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1202 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1205 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1206 // function uses CR 2, 3, or 4.
1207 if (!isPPC64 && !isDarwinABI &&
1208 (MRI.isPhysRegUsed(PPC::CR2) ||
1209 MRI.isPhysRegUsed(PPC::CR3) ||
1210 MRI.isPhysRegUsed(PPC::CR4))) {
1211 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1212 FI->setCRSpillFrameIndex(FrameIdx);
1216 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1217 RegScavenger *RS) const {
1218 // Early exit if not using the SVR4 ABI.
1219 if (!Subtarget.isSVR4ABI()) {
1220 addScavengingSpillSlot(MF, RS);
1224 // Get callee saved register information.
1225 MachineFrameInfo *FFI = MF.getFrameInfo();
1226 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1228 // Early exit if no callee saved registers are modified!
1229 if (CSI.empty() && !needsFP(MF)) {
1230 addScavengingSpillSlot(MF, RS);
1234 unsigned MinGPR = PPC::R31;
1235 unsigned MinG8R = PPC::X31;
1236 unsigned MinFPR = PPC::F31;
1237 unsigned MinVR = PPC::V31;
1239 bool HasGPSaveArea = false;
1240 bool HasG8SaveArea = false;
1241 bool HasFPSaveArea = false;
1242 bool HasVRSAVESaveArea = false;
1243 bool HasVRSaveArea = false;
1245 SmallVector<CalleeSavedInfo, 18> GPRegs;
1246 SmallVector<CalleeSavedInfo, 18> G8Regs;
1247 SmallVector<CalleeSavedInfo, 18> FPRegs;
1248 SmallVector<CalleeSavedInfo, 18> VRegs;
1250 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1251 unsigned Reg = CSI[i].getReg();
1252 if (PPC::GPRCRegClass.contains(Reg)) {
1253 HasGPSaveArea = true;
1255 GPRegs.push_back(CSI[i]);
1260 } else if (PPC::G8RCRegClass.contains(Reg)) {
1261 HasG8SaveArea = true;
1263 G8Regs.push_back(CSI[i]);
1268 } else if (PPC::F8RCRegClass.contains(Reg)) {
1269 HasFPSaveArea = true;
1271 FPRegs.push_back(CSI[i]);
1276 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1277 PPC::CRRCRegClass.contains(Reg)) {
1278 ; // do nothing, as we already know whether CRs are spilled
1279 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1280 HasVRSAVESaveArea = true;
1281 } else if (PPC::VRRCRegClass.contains(Reg)) {
1282 HasVRSaveArea = true;
1284 VRegs.push_back(CSI[i]);
1290 llvm_unreachable("Unknown RegisterClass!");
1294 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1295 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1297 int64_t LowerBound = 0;
1299 // Take into account stack space reserved for tail calls.
1301 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1302 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1303 LowerBound = TCSPDelta;
1306 // The Floating-point register save area is right below the back chain word
1307 // of the previous stack frame.
1308 if (HasFPSaveArea) {
1309 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1310 int FI = FPRegs[i].getFrameIdx();
1312 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1315 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1318 // Check whether the frame pointer register is allocated. If so, make sure it
1319 // is spilled to the correct offset.
1321 HasGPSaveArea = true;
1323 int FI = PFI->getFramePointerSaveIndex();
1324 assert(FI && "No Frame Pointer Save Slot!");
1326 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1329 if (PFI->usesPICBase()) {
1330 HasGPSaveArea = true;
1332 int FI = PFI->getPICBasePointerSaveIndex();
1333 assert(FI && "No PIC Base Pointer Save Slot!");
1335 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1338 const PPCRegisterInfo *RegInfo =
1339 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1340 if (RegInfo->hasBasePointer(MF)) {
1341 HasGPSaveArea = true;
1343 int FI = PFI->getBasePointerSaveIndex();
1344 assert(FI && "No Base Pointer Save Slot!");
1346 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1349 // General register save area starts right below the Floating-point
1350 // register save area.
1351 if (HasGPSaveArea || HasG8SaveArea) {
1352 // Move general register save area spill slots down, taking into account
1353 // the size of the Floating-point register save area.
1354 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1355 int FI = GPRegs[i].getFrameIdx();
1357 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1360 // Move general register save area spill slots down, taking into account
1361 // the size of the Floating-point register save area.
1362 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1363 int FI = G8Regs[i].getFrameIdx();
1365 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1369 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1370 TRI->getEncodingValue(MinG8R));
1372 if (Subtarget.isPPC64()) {
1373 LowerBound -= (31 - MinReg + 1) * 8;
1375 LowerBound -= (31 - MinReg + 1) * 4;
1379 // For 32-bit only, the CR save area is below the general register
1380 // save area. For 64-bit SVR4, the CR save area is addressed relative
1381 // to the stack pointer and hence does not need an adjustment here.
1382 // Only CR2 (the first nonvolatile spilled) has an associated frame
1383 // index so that we have a single uniform save area.
1384 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1385 // Adjust the frame index of the CR spill slot.
1386 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1387 unsigned Reg = CSI[i].getReg();
1389 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1390 // Leave Darwin logic as-is.
1391 || (!Subtarget.isSVR4ABI() &&
1392 (PPC::CRBITRCRegClass.contains(Reg) ||
1393 PPC::CRRCRegClass.contains(Reg)))) {
1394 int FI = CSI[i].getFrameIdx();
1396 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1400 LowerBound -= 4; // The CR save area is always 4 bytes long.
1403 if (HasVRSAVESaveArea) {
1404 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1405 // which have the VRSAVE register class?
1406 // Adjust the frame index of the VRSAVE spill slot.
1407 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1408 unsigned Reg = CSI[i].getReg();
1410 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1411 int FI = CSI[i].getFrameIdx();
1413 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1417 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1420 if (HasVRSaveArea) {
1421 // Insert alignment padding, we need 16-byte alignment.
1422 LowerBound = (LowerBound - 15) & ~(15);
1424 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1425 int FI = VRegs[i].getFrameIdx();
1427 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1431 addScavengingSpillSlot(MF, RS);
1435 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1436 RegScavenger *RS) const {
1437 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1438 // a large stack, which will require scavenging a register to materialize a
1441 // We need to have a scavenger spill slot for spills if the frame size is
1442 // large. In case there is no free register for large-offset addressing,
1443 // this slot is used for the necessary emergency spill. Also, we need the
1444 // slot for dynamic stack allocations.
1446 // The scavenger might be invoked if the frame offset does not fit into
1447 // the 16-bit immediate. We don't know the complete frame size here
1448 // because we've not yet computed callee-saved register spills or the
1449 // needed alignment padding.
1450 unsigned StackSize = determineFrameLayout(MF, false, true);
1451 MachineFrameInfo *MFI = MF.getFrameInfo();
1452 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1453 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1454 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1455 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1456 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1457 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1461 // Might we have over-aligned allocas?
1462 bool HasAlVars = MFI->hasVarSizedObjects() &&
1463 MFI->getMaxAlignment() > getStackAlignment();
1465 // These kinds of spills might need two registers.
1466 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1467 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1475 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1476 MachineBasicBlock::iterator MI,
1477 const std::vector<CalleeSavedInfo> &CSI,
1478 const TargetRegisterInfo *TRI) const {
1480 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1481 // Return false otherwise to maintain pre-existing behavior.
1482 if (!Subtarget.isSVR4ABI())
1485 MachineFunction *MF = MBB.getParent();
1486 const PPCInstrInfo &TII =
1487 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1489 bool CRSpilled = false;
1490 MachineInstrBuilder CRMIB;
1492 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1493 unsigned Reg = CSI[i].getReg();
1494 // Only Darwin actually uses the VRSAVE register, but it can still appear
1495 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1496 // Darwin, ignore it.
1497 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1500 // CR2 through CR4 are the nonvolatile CR fields.
1501 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1503 // Add the callee-saved register as live-in; it's killed at the spill.
1506 if (CRSpilled && IsCRField) {
1507 CRMIB.addReg(Reg, RegState::ImplicitKill);
1511 // Insert the spill to the stack frame.
1513 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1514 if (Subtarget.isPPC64()) {
1515 // The actual spill will happen at the start of the prologue.
1516 FuncInfo->addMustSaveCR(Reg);
1519 FuncInfo->setSpillsCR();
1521 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1522 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1523 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1524 .addReg(Reg, RegState::ImplicitKill);
1526 MBB.insert(MI, CRMIB);
1527 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1529 getKillRegState(true)),
1530 CSI[i].getFrameIdx()));
1533 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1534 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1535 CSI[i].getFrameIdx(), RC, TRI);
1542 restoreCRs(bool isPPC64, bool is31,
1543 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1544 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1545 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1547 MachineFunction *MF = MBB.getParent();
1548 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1550 unsigned RestoreOp, MoveReg;
1553 // This is handled during epilogue generation.
1556 // 32-bit: FP-relative
1557 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1559 CSI[CSIIndex].getFrameIdx()));
1560 RestoreOp = PPC::MTOCRF;
1565 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1566 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1569 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1570 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1573 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1574 .addReg(MoveReg, getKillRegState(true)));
1577 void PPCFrameLowering::
1578 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1579 MachineBasicBlock::iterator I) const {
1580 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1581 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1582 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1583 // Add (actually subtract) back the amount the callee popped on return.
1584 if (int CalleeAmt = I->getOperand(1).getImm()) {
1585 bool is64Bit = Subtarget.isPPC64();
1587 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1588 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1589 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1590 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1591 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1592 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1593 MachineInstr *MI = I;
1594 DebugLoc dl = MI->getDebugLoc();
1596 if (isInt<16>(CalleeAmt)) {
1597 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1598 .addReg(StackReg, RegState::Kill)
1601 MachineBasicBlock::iterator MBBI = I;
1602 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1603 .addImm(CalleeAmt >> 16);
1604 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1605 .addReg(TmpReg, RegState::Kill)
1606 .addImm(CalleeAmt & 0xFFFF);
1607 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1608 .addReg(StackReg, RegState::Kill)
1613 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1618 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1619 MachineBasicBlock::iterator MI,
1620 const std::vector<CalleeSavedInfo> &CSI,
1621 const TargetRegisterInfo *TRI) const {
1623 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1624 // Return false otherwise to maintain pre-existing behavior.
1625 if (!Subtarget.isSVR4ABI())
1628 MachineFunction *MF = MBB.getParent();
1629 const PPCInstrInfo &TII =
1630 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1631 bool CR2Spilled = false;
1632 bool CR3Spilled = false;
1633 bool CR4Spilled = false;
1634 unsigned CSIIndex = 0;
1636 // Initialize insertion-point logic; we will be restoring in reverse
1638 MachineBasicBlock::iterator I = MI, BeforeI = I;
1639 bool AtStart = I == MBB.begin();
1644 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1645 unsigned Reg = CSI[i].getReg();
1647 // Only Darwin actually uses the VRSAVE register, but it can still appear
1648 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1649 // Darwin, ignore it.
1650 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1653 if (Reg == PPC::CR2) {
1655 // The spill slot is associated only with CR2, which is the
1656 // first nonvolatile spilled. Save it here.
1659 } else if (Reg == PPC::CR3) {
1662 } else if (Reg == PPC::CR4) {
1666 // When we first encounter a non-CR register after seeing at
1667 // least one CR register, restore all spilled CRs together.
1668 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1669 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1670 bool is31 = needsFP(*MF);
1671 restoreCRs(Subtarget.isPPC64(), is31,
1672 CR2Spilled, CR3Spilled, CR4Spilled,
1673 MBB, I, CSI, CSIIndex);
1674 CR2Spilled = CR3Spilled = CR4Spilled = false;
1677 // Default behavior for non-CR saves.
1678 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1679 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1681 assert(I != MBB.begin() &&
1682 "loadRegFromStackSlot didn't insert any code!");
1685 // Insert in reverse order.
1694 // If we haven't yet spilled the CRs, do so now.
1695 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1696 bool is31 = needsFP(*MF);
1697 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1698 MBB, I, CSI, CSIIndex);