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 "PPCTargetMachine.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Target/TargetOptions.h"
31 /// VRRegNo - Map from a numbered VR register to its enum value.
33 static const uint16_t VRRegNo[] = {
34 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
35 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
36 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
37 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
40 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
41 if (STI.isDarwinABI())
42 return STI.isPPC64() ? 16 : 8;
44 return STI.isPPC64() ? 16 : 4;
47 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
48 return STI.isELFv2ABI() ? 24 : 40;
51 static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
52 // For the Darwin ABI:
53 // We cannot use the TOC save slot (offset +20) in the PowerPC linkage area
54 // for saving the frame pointer (if needed.) While the published ABI has
55 // not used this slot since at least MacOSX 10.2, there is older code
56 // around that does use it, and that needs to continue to work.
57 if (STI.isDarwinABI())
58 return STI.isPPC64() ? -8U : -4U;
60 // SVR4 ABI: First slot in the general register save area.
61 return STI.isPPC64() ? -8U : -4U;
64 static unsigned computeLinkageSize(const PPCSubtarget &STI) {
65 if (STI.isDarwinABI() || STI.isPPC64())
66 return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
72 static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
73 if (STI.isDarwinABI())
74 return STI.isPPC64() ? -16U : -8U;
76 // SVR4 ABI: First slot in the general register save area.
79 : (STI.getTargetMachine().getRelocationModel() == Reloc::PIC_)
84 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
85 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
86 STI.getPlatformStackAlignment(), 0),
87 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
88 TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
89 FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
90 LinkageSize(computeLinkageSize(Subtarget)),
91 BasePointerSaveOffset(computeBasePointerSaveOffset(STI)) {}
93 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
94 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
95 unsigned &NumEntries) const {
96 if (Subtarget.isDarwinABI()) {
98 if (Subtarget.isPPC64()) {
99 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
100 return &darwin64Offsets;
102 static const SpillSlot darwinOffsets = {PPC::R31, -4};
103 return &darwinOffsets;
107 // Early exit if not using the SVR4 ABI.
108 if (!Subtarget.isSVR4ABI()) {
113 // Note that the offsets here overlap, but this is fixed up in
114 // processFunctionBeforeFrameFinalized.
116 static const SpillSlot Offsets[] = {
117 // Floating-point register save area offsets.
137 // General register save area offsets.
157 // CR save area offset. We map each of the nonvolatile CR fields
158 // to the slot for CR2, which is the first of the nonvolatile CR
159 // fields to be assigned, so that we only allocate one save slot.
160 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
163 // VRSAVE save area offset.
166 // Vector register save area
180 static const SpillSlot Offsets64[] = {
181 // Floating-point register save area offsets.
201 // General register save area offsets.
221 // VRSAVE save area offset.
224 // Vector register save area
238 if (Subtarget.isPPC64()) {
239 NumEntries = array_lengthof(Offsets64);
243 NumEntries = array_lengthof(Offsets);
249 /// RemoveVRSaveCode - We have found that this function does not need any code
250 /// to manipulate the VRSAVE register, even though it uses vector registers.
251 /// This can happen when the only registers used are known to be live in or out
252 /// of the function. Remove all of the VRSAVE related code from the function.
253 /// FIXME: The removal of the code results in a compile failure at -O0 when the
254 /// function contains a function call, as the GPR containing original VRSAVE
255 /// contents is spilled and reloaded around the call. Without the prolog code,
256 /// the spill instruction refers to an undefined register. This code needs
257 /// to account for all uses of that GPR.
258 static void RemoveVRSaveCode(MachineInstr *MI) {
259 MachineBasicBlock *Entry = MI->getParent();
260 MachineFunction *MF = Entry->getParent();
262 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
263 MachineBasicBlock::iterator MBBI = MI;
265 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
266 MBBI->eraseFromParent();
268 bool RemovedAllMTVRSAVEs = true;
269 // See if we can find and remove the MTVRSAVE instruction from all of the
271 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
272 // If last instruction is a return instruction, add an epilogue
273 if (I->isReturnBlock()) {
274 bool FoundIt = false;
275 for (MBBI = I->end(); MBBI != I->begin(); ) {
277 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
278 MBBI->eraseFromParent(); // remove it.
283 RemovedAllMTVRSAVEs &= FoundIt;
287 // If we found and removed all MTVRSAVE instructions, remove the read of
289 if (RemovedAllMTVRSAVEs) {
291 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
293 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
294 MBBI->eraseFromParent();
297 // Finally, nuke the UPDATE_VRSAVE.
298 MI->eraseFromParent();
301 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
302 // instruction selector. Based on the vector registers that have been used,
303 // transform this into the appropriate ORI instruction.
304 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
305 MachineFunction *MF = MI->getParent()->getParent();
306 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
307 DebugLoc dl = MI->getDebugLoc();
309 const MachineRegisterInfo &MRI = MF->getRegInfo();
310 unsigned UsedRegMask = 0;
311 for (unsigned i = 0; i != 32; ++i)
312 if (MRI.isPhysRegModified(VRRegNo[i]))
313 UsedRegMask |= 1 << (31-i);
315 // Live in and live out values already must be in the mask, so don't bother
317 for (MachineRegisterInfo::livein_iterator
318 I = MF->getRegInfo().livein_begin(),
319 E = MF->getRegInfo().livein_end(); I != E; ++I) {
320 unsigned RegNo = TRI->getEncodingValue(I->first);
321 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
322 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
325 // Live out registers appear as use operands on return instructions.
326 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
327 UsedRegMask != 0 && BI != BE; ++BI) {
328 const MachineBasicBlock &MBB = *BI;
329 if (!MBB.isReturnBlock())
331 const MachineInstr &Ret = MBB.back();
332 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
333 const MachineOperand &MO = Ret.getOperand(I);
334 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
336 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
337 UsedRegMask &= ~(1 << (31-RegNo));
341 // If no registers are used, turn this into a copy.
342 if (UsedRegMask == 0) {
343 // Remove all VRSAVE code.
344 RemoveVRSaveCode(MI);
348 unsigned SrcReg = MI->getOperand(1).getReg();
349 unsigned DstReg = MI->getOperand(0).getReg();
351 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
352 if (DstReg != SrcReg)
353 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
355 .addImm(UsedRegMask);
357 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
358 .addReg(SrcReg, RegState::Kill)
359 .addImm(UsedRegMask);
360 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
361 if (DstReg != SrcReg)
362 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
364 .addImm(UsedRegMask >> 16);
366 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
367 .addReg(SrcReg, RegState::Kill)
368 .addImm(UsedRegMask >> 16);
370 if (DstReg != SrcReg)
371 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
373 .addImm(UsedRegMask >> 16);
375 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
376 .addReg(SrcReg, RegState::Kill)
377 .addImm(UsedRegMask >> 16);
379 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
380 .addReg(DstReg, RegState::Kill)
381 .addImm(UsedRegMask & 0xFFFF);
384 // Remove the old UPDATE_VRSAVE instruction.
385 MI->eraseFromParent();
388 static bool spillsCR(const MachineFunction &MF) {
389 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
390 return FuncInfo->isCRSpilled();
393 static bool spillsVRSAVE(const MachineFunction &MF) {
394 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
395 return FuncInfo->isVRSAVESpilled();
398 static bool hasSpills(const MachineFunction &MF) {
399 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
400 return FuncInfo->hasSpills();
403 static bool hasNonRISpills(const MachineFunction &MF) {
404 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
405 return FuncInfo->hasNonRISpills();
408 /// MustSaveLR - Return true if this function requires that we save the LR
409 /// register onto the stack in the prolog and restore it in the epilog of the
411 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
412 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
414 // We need a save/restore of LR if there is any def of LR (which is
415 // defined by calls, including the PIC setup sequence), or if there is
416 // some use of the LR stack slot (e.g. for builtin_return_address).
417 // (LR comes in 32 and 64 bit versions.)
418 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
419 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
422 /// determineFrameLayout - Determine the size of the frame and maximum call
424 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
426 bool UseEstimate) const {
427 MachineFrameInfo *MFI = MF.getFrameInfo();
429 // Get the number of bytes to allocate from the FrameInfo
431 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
433 // Get stack alignments. The frame must be aligned to the greatest of these:
434 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
435 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
436 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
438 const PPCRegisterInfo *RegInfo =
439 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
441 // If we are a leaf function, and use up to 224 bytes of stack space,
442 // don't have a frame pointer, calls, or dynamic alloca then we do not need
443 // to adjust the stack pointer (we fit in the Red Zone).
444 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
445 // stackless code if all local vars are reg-allocated.
446 bool DisableRedZone = MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
447 unsigned LR = RegInfo->getRARegister();
448 if (!DisableRedZone &&
449 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
450 !Subtarget.isSVR4ABI() || // allocated locals.
452 FrameSize <= 224 && // Fits in red zone.
453 !MFI->hasVarSizedObjects() && // No dynamic alloca.
454 !MFI->adjustsStack() && // No calls.
455 !MustSaveLR(MF, LR) &&
456 !RegInfo->hasBasePointer(MF)) { // No special alignment.
459 MFI->setStackSize(0);
463 // Get the maximum call frame size of all the calls.
464 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
466 // Maximum call frame needs to be at least big enough for linkage area.
467 unsigned minCallFrameSize = getLinkageSize();
468 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
470 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
471 // that allocations will be aligned.
472 if (MFI->hasVarSizedObjects())
473 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
475 // Update maximum call frame size.
477 MFI->setMaxCallFrameSize(maxCallFrameSize);
479 // Include call frame size in total.
480 FrameSize += maxCallFrameSize;
482 // Make sure the frame is aligned.
483 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
485 // Update frame info.
487 MFI->setStackSize(FrameSize);
492 // hasFP - Return true if the specified function actually has a dedicated frame
494 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
495 const MachineFrameInfo *MFI = MF.getFrameInfo();
496 // FIXME: This is pretty much broken by design: hasFP() might be called really
497 // early, before the stack layout was calculated and thus hasFP() might return
498 // true or false here depending on the time of call.
499 return (MFI->getStackSize()) && needsFP(MF);
502 // needsFP - Return true if the specified function should have a dedicated frame
503 // pointer register. This is true if the function has variable sized allocas or
504 // if frame pointer elimination is disabled.
505 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
506 const MachineFrameInfo *MFI = MF.getFrameInfo();
508 // Naked functions have no stack frame pushed, so we don't have a frame
510 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
513 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
514 MFI->hasVarSizedObjects() ||
515 MFI->hasStackMap() || MFI->hasPatchPoint() ||
516 (MF.getTarget().Options.GuaranteedTailCallOpt &&
517 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
520 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
521 bool is31 = needsFP(MF);
522 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
523 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
525 const PPCRegisterInfo *RegInfo =
526 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
527 bool HasBP = RegInfo->hasBasePointer(MF);
528 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
529 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
531 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
533 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
535 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
536 MachineOperand &MO = MBBI->getOperand(I);
540 switch (MO.getReg()) {
559 bool PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
561 unsigned *ScratchRegister) const {
563 unsigned R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
566 *ScratchRegister = R0;
568 // If MBB is an entry or exit block, use R0 as the scratch register
569 if ((UseAtEnd && MBB->isReturnBlock()) ||
570 (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
574 RS.enterBasicBlock(MBB);
576 if (UseAtEnd && !MBB->empty()) {
577 // The scratch register will be used at the end of the block, so must consider
578 // all registers used within the block
580 MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
581 // If no terminator, back iterator up to previous instruction.
582 if (MBBI == MBB->end())
583 MBBI = std::prev(MBBI);
585 if (MBBI != MBB->begin())
589 if (!RS.isRegUsed(R0))
592 unsigned Reg = RS.FindUnusedReg(Subtarget.isPPC64() ? &PPC::G8RCRegClass
593 : &PPC::GPRCRegClass);
595 // Make sure the register scavenger was able to find an available register
596 // If not, use R0 but return false to indicate no register was available and
597 // R0 must be used (as recommended by the ABI)
602 *ScratchRegister = Reg;
607 bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
608 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
610 return findScratchRegister(TmpMBB, false, nullptr);
613 bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
614 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
616 return findScratchRegister(TmpMBB, true, nullptr);
619 void PPCFrameLowering::emitPrologue(MachineFunction &MF,
620 MachineBasicBlock &MBB) const {
621 MachineBasicBlock::iterator MBBI = MBB.begin();
622 MachineFrameInfo *MFI = MF.getFrameInfo();
623 const PPCInstrInfo &TII =
624 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
625 const PPCRegisterInfo *RegInfo =
626 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
628 MachineModuleInfo &MMI = MF.getMMI();
629 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
631 bool needsCFI = MMI.hasDebugInfo() ||
632 MF.getFunction()->needsUnwindTableEntry();
634 // Get processor type.
635 bool isPPC64 = Subtarget.isPPC64();
637 bool isSVR4ABI = Subtarget.isSVR4ABI();
638 bool isELFv2ABI = Subtarget.isELFv2ABI();
639 assert((Subtarget.isDarwinABI() || isSVR4ABI) &&
640 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
642 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
645 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
646 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
647 HandleVRSaveUpdate(MBBI, TII);
652 // Move MBBI back to the beginning of the prologue block.
655 // Work out frame sizes.
656 unsigned FrameSize = determineFrameLayout(MF);
657 int NegFrameSize = -FrameSize;
658 if (!isInt<32>(NegFrameSize))
659 llvm_unreachable("Unhandled stack size!");
661 if (MFI->isFrameAddressTaken())
662 replaceFPWithRealFP(MF);
664 // Check if the link register (LR) must be saved.
665 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
666 bool MustSaveLR = FI->mustSaveLR();
667 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
668 // Do we have a frame pointer and/or base pointer for this function?
669 bool HasFP = hasFP(MF);
670 bool HasBP = RegInfo->hasBasePointer(MF);
672 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
673 unsigned BPReg = RegInfo->getBaseRegister(MF);
674 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
675 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
676 unsigned ScratchReg = 0;
677 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
678 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
679 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
681 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
683 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
685 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
687 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
689 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
691 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
693 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
695 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
698 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
699 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
700 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
701 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
702 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
703 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
705 findScratchRegister(&MBB, false, &ScratchReg);
706 assert(ScratchReg && "No scratch register!");
708 int LROffset = getReturnSaveOffset();
713 MachineFrameInfo *FFI = MF.getFrameInfo();
714 int FPIndex = FI->getFramePointerSaveIndex();
715 assert(FPIndex && "No Frame Pointer Save Slot!");
716 FPOffset = FFI->getObjectOffset(FPIndex);
718 FPOffset = getFramePointerSaveOffset();
725 MachineFrameInfo *FFI = MF.getFrameInfo();
726 int BPIndex = FI->getBasePointerSaveIndex();
727 assert(BPIndex && "No Base Pointer Save Slot!");
728 BPOffset = FFI->getObjectOffset(BPIndex);
730 BPOffset = getBasePointerSaveOffset();
735 if (FI->usesPICBase()) {
736 MachineFrameInfo *FFI = MF.getFrameInfo();
737 int PBPIndex = FI->getPICBasePointerSaveIndex();
738 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
739 PBPOffset = FFI->getObjectOffset(PBPIndex);
742 // Get stack alignments.
743 unsigned MaxAlign = MFI->getMaxAlignment();
744 if (HasBP && MaxAlign > 1)
745 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
746 "Invalid alignment!");
748 // Frames of 32KB & larger require special handling because they cannot be
749 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
750 bool isLargeFrame = !isInt<16>(NegFrameSize);
753 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
755 assert((isPPC64 || MustSaveCRs.empty()) &&
756 "Prologue CR saving supported only in 64-bit mode");
758 if (!MustSaveCRs.empty()) { // will only occur for PPC64
759 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
760 // If only one or two CR fields are clobbered, it could be more
761 // efficient to use mfocrf to selectively save just those fields.
762 MachineInstrBuilder MIB =
763 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
764 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
765 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
769 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
770 BuildMI(MBB, MBBI, dl, StoreInst)
775 if (FI->usesPICBase())
776 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
777 BuildMI(MBB, MBBI, dl, StoreInst)
783 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
784 BuildMI(MBB, MBBI, dl, StoreInst)
790 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
791 BuildMI(MBB, MBBI, dl, StoreInst)
796 if (!MustSaveCRs.empty()) // will only occur for PPC64
797 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
798 .addReg(TempReg, getKillRegState(true))
802 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
803 if (!FrameSize) return;
805 // Adjust stack pointer: r1 += NegFrameSize.
806 // If there is a preferred stack alignment, align R1 now
809 // Save a copy of r1 as the base pointer.
810 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
815 if (HasBP && MaxAlign > 1) {
817 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
820 .addImm(64 - Log2_32(MaxAlign));
822 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
825 .addImm(32 - Log2_32(MaxAlign))
828 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
829 .addReg(ScratchReg, RegState::Kill)
830 .addImm(NegFrameSize);
832 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
833 .addImm(NegFrameSize >> 16);
834 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
835 .addReg(TempReg, RegState::Kill)
836 .addImm(NegFrameSize & 0xFFFF);
837 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
838 .addReg(ScratchReg, RegState::Kill)
839 .addReg(TempReg, RegState::Kill);
841 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
842 .addReg(SPReg, RegState::Kill)
846 } else if (!isLargeFrame) {
847 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
849 .addImm(NegFrameSize)
853 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
854 .addImm(NegFrameSize >> 16);
855 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
856 .addReg(ScratchReg, RegState::Kill)
857 .addImm(NegFrameSize & 0xFFFF);
858 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
859 .addReg(SPReg, RegState::Kill)
864 // Add Call Frame Information for the instructions we generated above.
869 // Define CFA in terms of BP. Do this in preference to using FP/SP,
870 // because if the stack needed aligning then CFA won't be at a fixed
871 // offset from FP/SP.
872 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
873 CFIIndex = MMI.addFrameInst(
874 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
876 // Adjust the definition of CFA to account for the change in SP.
877 assert(NegFrameSize);
878 CFIIndex = MMI.addFrameInst(
879 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
881 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
882 .addCFIIndex(CFIIndex);
885 // Describe where FP was saved, at a fixed offset from CFA.
886 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
887 CFIIndex = MMI.addFrameInst(
888 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
889 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
890 .addCFIIndex(CFIIndex);
893 if (FI->usesPICBase()) {
894 // Describe where FP was saved, at a fixed offset from CFA.
895 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
896 CFIIndex = MMI.addFrameInst(
897 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
898 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
899 .addCFIIndex(CFIIndex);
903 // Describe where BP was saved, at a fixed offset from CFA.
904 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
905 CFIIndex = MMI.addFrameInst(
906 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
907 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
908 .addCFIIndex(CFIIndex);
912 // Describe where LR was saved, at a fixed offset from CFA.
913 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
914 CFIIndex = MMI.addFrameInst(
915 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
916 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
917 .addCFIIndex(CFIIndex);
921 // If there is a frame pointer, copy R1 into R31
923 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
927 if (!HasBP && needsCFI) {
928 // Change the definition of CFA from SP+offset to FP+offset, because SP
929 // will change at every alloca.
930 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
931 unsigned CFIIndex = MMI.addFrameInst(
932 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
934 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
935 .addCFIIndex(CFIIndex);
940 // Describe where callee saved registers were saved, at fixed offsets from
942 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
943 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
944 unsigned Reg = CSI[I].getReg();
945 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
947 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
948 // subregisters of CR2. We just need to emit a move of CR2.
949 if (PPC::CRBITRCRegClass.contains(Reg))
952 // For SVR4, don't emit a move for the CR spill slot if we haven't
954 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
955 && MustSaveCRs.empty())
958 // For 64-bit SVR4 when we have spilled CRs, the spill location
959 // is SP+8, not a frame-relative slot.
960 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
961 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
962 // the whole CR word. In the ELFv2 ABI, every CR that was
963 // actually saved gets its own CFI record.
964 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
965 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
966 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
967 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
968 .addCFIIndex(CFIIndex);
972 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
973 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
974 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
975 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
976 .addCFIIndex(CFIIndex);
981 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
982 MachineBasicBlock &MBB) const {
983 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
986 if (MBBI != MBB.end())
987 dl = MBBI->getDebugLoc();
989 const PPCInstrInfo &TII =
990 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
991 const PPCRegisterInfo *RegInfo =
992 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
994 // Get alignment info so we know how to restore the SP.
995 const MachineFrameInfo *MFI = MF.getFrameInfo();
997 // Get the number of bytes allocated from the FrameInfo.
998 int FrameSize = MFI->getStackSize();
1000 // Get processor type.
1001 bool isPPC64 = Subtarget.isPPC64();
1003 bool isSVR4ABI = Subtarget.isSVR4ABI();
1005 // Check if the link register (LR) has been saved.
1006 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1007 bool MustSaveLR = FI->mustSaveLR();
1008 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
1009 // Do we have a frame pointer and/or base pointer for this function?
1010 bool HasFP = hasFP(MF);
1011 bool HasBP = RegInfo->hasBasePointer(MF);
1013 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
1014 unsigned BPReg = RegInfo->getBaseRegister(MF);
1015 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
1016 unsigned ScratchReg = 0;
1017 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
1018 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
1020 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
1022 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
1024 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
1026 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
1028 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
1031 int LROffset = getReturnSaveOffset();
1035 findScratchRegister(&MBB, true, &ScratchReg);
1036 assert(ScratchReg && "No scratch register!");
1040 MachineFrameInfo *FFI = MF.getFrameInfo();
1041 int FPIndex = FI->getFramePointerSaveIndex();
1042 assert(FPIndex && "No Frame Pointer Save Slot!");
1043 FPOffset = FFI->getObjectOffset(FPIndex);
1045 FPOffset = getFramePointerSaveOffset();
1052 MachineFrameInfo *FFI = MF.getFrameInfo();
1053 int BPIndex = FI->getBasePointerSaveIndex();
1054 assert(BPIndex && "No Base Pointer Save Slot!");
1055 BPOffset = FFI->getObjectOffset(BPIndex);
1057 BPOffset = getBasePointerSaveOffset();
1062 if (FI->usesPICBase()) {
1063 MachineFrameInfo *FFI = MF.getFrameInfo();
1064 int PBPIndex = FI->getPICBasePointerSaveIndex();
1065 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1066 PBPOffset = FFI->getObjectOffset(PBPIndex);
1069 bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
1071 if (IsReturnBlock) {
1072 unsigned RetOpcode = MBBI->getOpcode();
1073 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
1074 RetOpcode == PPC::TCRETURNdi ||
1075 RetOpcode == PPC::TCRETURNai ||
1076 RetOpcode == PPC::TCRETURNri8 ||
1077 RetOpcode == PPC::TCRETURNdi8 ||
1078 RetOpcode == PPC::TCRETURNai8;
1081 int MaxTCRetDelta = FI->getTailCallSPDelta();
1082 MachineOperand &StackAdjust = MBBI->getOperand(1);
1083 assert(StackAdjust.isImm() && "Expecting immediate value.");
1084 // Adjust stack pointer.
1085 int StackAdj = StackAdjust.getImm();
1086 int Delta = StackAdj - MaxTCRetDelta;
1087 assert((Delta >= 0) && "Delta must be positive");
1088 if (MaxTCRetDelta>0)
1089 FrameSize += (StackAdj +Delta);
1091 FrameSize += StackAdj;
1095 // Frames of 32KB & larger require special handling because they cannot be
1096 // indexed into with a simple LD/LWZ immediate offset operand.
1097 bool isLargeFrame = !isInt<16>(FrameSize);
1100 // In the prologue, the loaded (or persistent) stack pointer value is offset
1101 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
1103 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1104 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1105 // call which invalidates the stack pointer value in SP(0). So we use the
1106 // value of R31 in this case.
1107 if (FI->hasFastCall()) {
1108 assert(HasFP && "Expecting a valid frame pointer.");
1109 if (!isLargeFrame) {
1110 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1111 .addReg(FPReg).addImm(FrameSize);
1113 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1114 .addImm(FrameSize >> 16);
1115 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1116 .addReg(ScratchReg, RegState::Kill)
1117 .addImm(FrameSize & 0xFFFF);
1118 BuildMI(MBB, MBBI, dl, AddInst)
1121 .addReg(ScratchReg);
1123 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1124 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1128 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1135 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1139 assert((isPPC64 || MustSaveCRs.empty()) &&
1140 "Epilogue CR restoring supported only in 64-bit mode");
1142 if (!MustSaveCRs.empty()) // will only occur for PPC64
1143 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1148 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1152 if (FI->usesPICBase())
1153 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1154 BuildMI(MBB, MBBI, dl, LoadInst)
1160 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1164 if (!MustSaveCRs.empty()) // will only occur for PPC64
1165 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1166 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1167 .addReg(TempReg, getKillRegState(i == e-1));
1170 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1172 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1173 // call optimization
1174 if (IsReturnBlock) {
1175 unsigned RetOpcode = MBBI->getOpcode();
1176 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1177 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1178 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1179 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1180 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1182 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1183 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1184 .addReg(SPReg).addImm(CallerAllocatedAmt);
1186 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1187 .addImm(CallerAllocatedAmt >> 16);
1188 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1189 .addReg(ScratchReg, RegState::Kill)
1190 .addImm(CallerAllocatedAmt & 0xFFFF);
1191 BuildMI(MBB, MBBI, dl, AddInst)
1194 .addReg(ScratchReg);
1196 } else if (RetOpcode == PPC::TCRETURNdi) {
1197 MBBI = MBB.getLastNonDebugInstr();
1198 MachineOperand &JumpTarget = MBBI->getOperand(0);
1199 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1200 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1201 } else if (RetOpcode == PPC::TCRETURNri) {
1202 MBBI = MBB.getLastNonDebugInstr();
1203 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1204 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1205 } else if (RetOpcode == PPC::TCRETURNai) {
1206 MBBI = MBB.getLastNonDebugInstr();
1207 MachineOperand &JumpTarget = MBBI->getOperand(0);
1208 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1209 } else if (RetOpcode == PPC::TCRETURNdi8) {
1210 MBBI = MBB.getLastNonDebugInstr();
1211 MachineOperand &JumpTarget = MBBI->getOperand(0);
1212 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1213 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1214 } else if (RetOpcode == PPC::TCRETURNri8) {
1215 MBBI = MBB.getLastNonDebugInstr();
1216 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1217 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1218 } else if (RetOpcode == PPC::TCRETURNai8) {
1219 MBBI = MBB.getLastNonDebugInstr();
1220 MachineOperand &JumpTarget = MBBI->getOperand(0);
1221 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1226 void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,
1227 BitVector &SavedRegs,
1228 RegScavenger *RS) const {
1229 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1231 const PPCRegisterInfo *RegInfo =
1232 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1234 // Save and clear the LR state.
1235 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1236 unsigned LR = RegInfo->getRARegister();
1237 FI->setMustSaveLR(MustSaveLR(MF, LR));
1238 SavedRegs.reset(LR);
1240 // Save R31 if necessary
1241 int FPSI = FI->getFramePointerSaveIndex();
1242 bool isPPC64 = Subtarget.isPPC64();
1243 bool isDarwinABI = Subtarget.isDarwinABI();
1244 MachineFrameInfo *MFI = MF.getFrameInfo();
1246 // If the frame pointer save index hasn't been defined yet.
1247 if (!FPSI && needsFP(MF)) {
1248 // Find out what the fix offset of the frame pointer save area.
1249 int FPOffset = getFramePointerSaveOffset();
1250 // Allocate the frame index for frame pointer save area.
1251 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1253 FI->setFramePointerSaveIndex(FPSI);
1256 int BPSI = FI->getBasePointerSaveIndex();
1257 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1258 int BPOffset = getBasePointerSaveOffset();
1259 // Allocate the frame index for the base pointer save area.
1260 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1262 FI->setBasePointerSaveIndex(BPSI);
1265 // Reserve stack space for the PIC Base register (R30).
1266 // Only used in SVR4 32-bit.
1267 if (FI->usesPICBase()) {
1268 int PBPSI = MFI->CreateFixedObject(4, -8, true);
1269 FI->setPICBasePointerSaveIndex(PBPSI);
1272 // Reserve stack space to move the linkage area to in case of a tail call.
1274 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1275 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1276 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1279 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1280 // function uses CR 2, 3, or 4.
1281 if (!isPPC64 && !isDarwinABI &&
1282 (SavedRegs.test(PPC::CR2) ||
1283 SavedRegs.test(PPC::CR3) ||
1284 SavedRegs.test(PPC::CR4))) {
1285 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1286 FI->setCRSpillFrameIndex(FrameIdx);
1290 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1291 RegScavenger *RS) const {
1292 // Early exit if not using the SVR4 ABI.
1293 if (!Subtarget.isSVR4ABI()) {
1294 addScavengingSpillSlot(MF, RS);
1298 // Get callee saved register information.
1299 MachineFrameInfo *FFI = MF.getFrameInfo();
1300 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1302 // Early exit if no callee saved registers are modified!
1303 if (CSI.empty() && !needsFP(MF)) {
1304 addScavengingSpillSlot(MF, RS);
1308 unsigned MinGPR = PPC::R31;
1309 unsigned MinG8R = PPC::X31;
1310 unsigned MinFPR = PPC::F31;
1311 unsigned MinVR = PPC::V31;
1313 bool HasGPSaveArea = false;
1314 bool HasG8SaveArea = false;
1315 bool HasFPSaveArea = false;
1316 bool HasVRSAVESaveArea = false;
1317 bool HasVRSaveArea = false;
1319 SmallVector<CalleeSavedInfo, 18> GPRegs;
1320 SmallVector<CalleeSavedInfo, 18> G8Regs;
1321 SmallVector<CalleeSavedInfo, 18> FPRegs;
1322 SmallVector<CalleeSavedInfo, 18> VRegs;
1324 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1325 unsigned Reg = CSI[i].getReg();
1326 if (PPC::GPRCRegClass.contains(Reg)) {
1327 HasGPSaveArea = true;
1329 GPRegs.push_back(CSI[i]);
1334 } else if (PPC::G8RCRegClass.contains(Reg)) {
1335 HasG8SaveArea = true;
1337 G8Regs.push_back(CSI[i]);
1342 } else if (PPC::F8RCRegClass.contains(Reg)) {
1343 HasFPSaveArea = true;
1345 FPRegs.push_back(CSI[i]);
1350 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1351 PPC::CRRCRegClass.contains(Reg)) {
1352 ; // do nothing, as we already know whether CRs are spilled
1353 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1354 HasVRSAVESaveArea = true;
1355 } else if (PPC::VRRCRegClass.contains(Reg)) {
1356 HasVRSaveArea = true;
1358 VRegs.push_back(CSI[i]);
1364 llvm_unreachable("Unknown RegisterClass!");
1368 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1369 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1371 int64_t LowerBound = 0;
1373 // Take into account stack space reserved for tail calls.
1375 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1376 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1377 LowerBound = TCSPDelta;
1380 // The Floating-point register save area is right below the back chain word
1381 // of the previous stack frame.
1382 if (HasFPSaveArea) {
1383 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1384 int FI = FPRegs[i].getFrameIdx();
1386 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1389 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1392 // Check whether the frame pointer register is allocated. If so, make sure it
1393 // is spilled to the correct offset.
1395 HasGPSaveArea = true;
1397 int FI = PFI->getFramePointerSaveIndex();
1398 assert(FI && "No Frame Pointer Save Slot!");
1400 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1403 if (PFI->usesPICBase()) {
1404 HasGPSaveArea = true;
1406 int FI = PFI->getPICBasePointerSaveIndex();
1407 assert(FI && "No PIC Base Pointer Save Slot!");
1409 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1412 const PPCRegisterInfo *RegInfo =
1413 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1414 if (RegInfo->hasBasePointer(MF)) {
1415 HasGPSaveArea = true;
1417 int FI = PFI->getBasePointerSaveIndex();
1418 assert(FI && "No Base Pointer Save Slot!");
1420 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1423 // General register save area starts right below the Floating-point
1424 // register save area.
1425 if (HasGPSaveArea || HasG8SaveArea) {
1426 // Move general register save area spill slots down, taking into account
1427 // the size of the Floating-point register save area.
1428 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1429 int FI = GPRegs[i].getFrameIdx();
1431 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1434 // Move general register save area spill slots down, taking into account
1435 // the size of the Floating-point register save area.
1436 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1437 int FI = G8Regs[i].getFrameIdx();
1439 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1443 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1444 TRI->getEncodingValue(MinG8R));
1446 if (Subtarget.isPPC64()) {
1447 LowerBound -= (31 - MinReg + 1) * 8;
1449 LowerBound -= (31 - MinReg + 1) * 4;
1453 // For 32-bit only, the CR save area is below the general register
1454 // save area. For 64-bit SVR4, the CR save area is addressed relative
1455 // to the stack pointer and hence does not need an adjustment here.
1456 // Only CR2 (the first nonvolatile spilled) has an associated frame
1457 // index so that we have a single uniform save area.
1458 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1459 // Adjust the frame index of the CR spill slot.
1460 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1461 unsigned Reg = CSI[i].getReg();
1463 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1464 // Leave Darwin logic as-is.
1465 || (!Subtarget.isSVR4ABI() &&
1466 (PPC::CRBITRCRegClass.contains(Reg) ||
1467 PPC::CRRCRegClass.contains(Reg)))) {
1468 int FI = CSI[i].getFrameIdx();
1470 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1474 LowerBound -= 4; // The CR save area is always 4 bytes long.
1477 if (HasVRSAVESaveArea) {
1478 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1479 // which have the VRSAVE register class?
1480 // Adjust the frame index of the VRSAVE spill slot.
1481 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1482 unsigned Reg = CSI[i].getReg();
1484 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1485 int FI = CSI[i].getFrameIdx();
1487 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1491 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1494 if (HasVRSaveArea) {
1495 // Insert alignment padding, we need 16-byte alignment.
1496 LowerBound = (LowerBound - 15) & ~(15);
1498 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1499 int FI = VRegs[i].getFrameIdx();
1501 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1505 addScavengingSpillSlot(MF, RS);
1509 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1510 RegScavenger *RS) const {
1511 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1512 // a large stack, which will require scavenging a register to materialize a
1515 // We need to have a scavenger spill slot for spills if the frame size is
1516 // large. In case there is no free register for large-offset addressing,
1517 // this slot is used for the necessary emergency spill. Also, we need the
1518 // slot for dynamic stack allocations.
1520 // The scavenger might be invoked if the frame offset does not fit into
1521 // the 16-bit immediate. We don't know the complete frame size here
1522 // because we've not yet computed callee-saved register spills or the
1523 // needed alignment padding.
1524 unsigned StackSize = determineFrameLayout(MF, false, true);
1525 MachineFrameInfo *MFI = MF.getFrameInfo();
1526 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1527 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1528 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1529 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1530 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1531 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1535 // Might we have over-aligned allocas?
1536 bool HasAlVars = MFI->hasVarSizedObjects() &&
1537 MFI->getMaxAlignment() > getStackAlignment();
1539 // These kinds of spills might need two registers.
1540 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1541 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1549 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1550 MachineBasicBlock::iterator MI,
1551 const std::vector<CalleeSavedInfo> &CSI,
1552 const TargetRegisterInfo *TRI) const {
1554 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1555 // Return false otherwise to maintain pre-existing behavior.
1556 if (!Subtarget.isSVR4ABI())
1559 MachineFunction *MF = MBB.getParent();
1560 const PPCInstrInfo &TII =
1561 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1563 bool CRSpilled = false;
1564 MachineInstrBuilder CRMIB;
1566 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1567 unsigned Reg = CSI[i].getReg();
1568 // Only Darwin actually uses the VRSAVE register, but it can still appear
1569 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1570 // Darwin, ignore it.
1571 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1574 // CR2 through CR4 are the nonvolatile CR fields.
1575 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1577 // Add the callee-saved register as live-in; it's killed at the spill.
1580 if (CRSpilled && IsCRField) {
1581 CRMIB.addReg(Reg, RegState::ImplicitKill);
1585 // Insert the spill to the stack frame.
1587 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1588 if (Subtarget.isPPC64()) {
1589 // The actual spill will happen at the start of the prologue.
1590 FuncInfo->addMustSaveCR(Reg);
1593 FuncInfo->setSpillsCR();
1595 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1596 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1597 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1598 .addReg(Reg, RegState::ImplicitKill);
1600 MBB.insert(MI, CRMIB);
1601 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1603 getKillRegState(true)),
1604 CSI[i].getFrameIdx()));
1607 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1608 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1609 CSI[i].getFrameIdx(), RC, TRI);
1616 restoreCRs(bool isPPC64, bool is31,
1617 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1618 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1619 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1621 MachineFunction *MF = MBB.getParent();
1622 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1624 unsigned RestoreOp, MoveReg;
1627 // This is handled during epilogue generation.
1630 // 32-bit: FP-relative
1631 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1633 CSI[CSIIndex].getFrameIdx()));
1634 RestoreOp = PPC::MTOCRF;
1639 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1640 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1643 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1644 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1647 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1648 .addReg(MoveReg, getKillRegState(true)));
1651 void PPCFrameLowering::
1652 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1653 MachineBasicBlock::iterator I) const {
1654 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1655 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1656 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1657 // Add (actually subtract) back the amount the callee popped on return.
1658 if (int CalleeAmt = I->getOperand(1).getImm()) {
1659 bool is64Bit = Subtarget.isPPC64();
1661 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1662 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1663 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1664 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1665 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1666 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1667 MachineInstr *MI = I;
1668 DebugLoc dl = MI->getDebugLoc();
1670 if (isInt<16>(CalleeAmt)) {
1671 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1672 .addReg(StackReg, RegState::Kill)
1675 MachineBasicBlock::iterator MBBI = I;
1676 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1677 .addImm(CalleeAmt >> 16);
1678 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1679 .addReg(TmpReg, RegState::Kill)
1680 .addImm(CalleeAmt & 0xFFFF);
1681 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1682 .addReg(StackReg, RegState::Kill)
1687 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1692 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1693 MachineBasicBlock::iterator MI,
1694 const std::vector<CalleeSavedInfo> &CSI,
1695 const TargetRegisterInfo *TRI) const {
1697 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1698 // Return false otherwise to maintain pre-existing behavior.
1699 if (!Subtarget.isSVR4ABI())
1702 MachineFunction *MF = MBB.getParent();
1703 const PPCInstrInfo &TII =
1704 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1705 bool CR2Spilled = false;
1706 bool CR3Spilled = false;
1707 bool CR4Spilled = false;
1708 unsigned CSIIndex = 0;
1710 // Initialize insertion-point logic; we will be restoring in reverse
1712 MachineBasicBlock::iterator I = MI, BeforeI = I;
1713 bool AtStart = I == MBB.begin();
1718 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1719 unsigned Reg = CSI[i].getReg();
1721 // Only Darwin actually uses the VRSAVE register, but it can still appear
1722 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1723 // Darwin, ignore it.
1724 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1727 if (Reg == PPC::CR2) {
1729 // The spill slot is associated only with CR2, which is the
1730 // first nonvolatile spilled. Save it here.
1733 } else if (Reg == PPC::CR3) {
1736 } else if (Reg == PPC::CR4) {
1740 // When we first encounter a non-CR register after seeing at
1741 // least one CR register, restore all spilled CRs together.
1742 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1743 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1744 bool is31 = needsFP(*MF);
1745 restoreCRs(Subtarget.isPPC64(), is31,
1746 CR2Spilled, CR3Spilled, CR4Spilled,
1747 MBB, I, CSI, CSIIndex);
1748 CR2Spilled = CR3Spilled = CR4Spilled = false;
1751 // Default behavior for non-CR saves.
1752 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1753 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1755 assert(I != MBB.begin() &&
1756 "loadRegFromStackSlot didn't insert any code!");
1759 // Insert in reverse order.
1768 // If we haven't yet spilled the CRs, do so now.
1769 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1770 bool is31 = needsFP(*MF);
1771 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1772 MBB, I, CSI, CSIIndex);
1778 bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1779 return (MF.getSubtarget<PPCSubtarget>().isSVR4ABI() &&
1780 MF.getSubtarget<PPCSubtarget>().isPPC64());