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 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
40 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
41 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
44 unsigned PPCFrameLowering::getMinCallArgumentsSize(bool isPPC64,
46 // For the Darwin ABI / 64-bit SVR4 ABI:
47 // The prolog code of the callee may store up to 8 GPR argument registers to
48 // the stack, allowing va_start to index over them in memory if its varargs.
49 // Because we cannot tell if this is needed on the caller side, we have to
50 // conservatively assume that it is needed. As such, make sure we have at
51 // least enough stack space for the caller to store the 8 GPRs.
52 if (isDarwinABI || isPPC64)
53 return 8 * (isPPC64 ? 8 : 4);
56 // There is no default stack allocated for the 8 first GPR arguments.
60 /// getMinCallFrameSize - Return the minimum size a call frame can be using
62 unsigned PPCFrameLowering::getMinCallFrameSize(bool isPPC64, bool isDarwinABI) {
63 // The call frame needs to be at least big enough for linkage and 8 args.
64 return PPCFrameLowering::getLinkageSize(isPPC64, isDarwinABI) +
65 PPCFrameLowering::getMinCallArgumentsSize(isPPC64, isDarwinABI);
68 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
69 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
70 unsigned &NumEntries) const {
71 if (Subtarget.isDarwinABI()) {
73 if (Subtarget.isPPC64()) {
74 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
75 return &darwin64Offsets;
77 static const SpillSlot darwinOffsets = {PPC::R31, -4};
78 return &darwinOffsets;
82 // Early exit if not using the SVR4 ABI.
83 if (!Subtarget.isSVR4ABI()) {
88 // Note that the offsets here overlap, but this is fixed up in
89 // processFunctionBeforeFrameFinalized.
91 static const SpillSlot Offsets[] = {
92 // Floating-point register save area offsets.
112 // General register save area offsets.
132 // CR save area offset. We map each of the nonvolatile CR fields
133 // to the slot for CR2, which is the first of the nonvolatile CR
134 // fields to be assigned, so that we only allocate one save slot.
135 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
138 // VRSAVE save area offset.
141 // Vector register save area
155 static const SpillSlot Offsets64[] = {
156 // Floating-point register save area offsets.
176 // General register save area offsets.
196 // VRSAVE save area offset.
199 // Vector register save area
213 if (Subtarget.isPPC64()) {
214 NumEntries = array_lengthof(Offsets64);
218 NumEntries = array_lengthof(Offsets);
224 /// RemoveVRSaveCode - We have found that this function does not need any code
225 /// to manipulate the VRSAVE register, even though it uses vector registers.
226 /// This can happen when the only registers used are known to be live in or out
227 /// of the function. Remove all of the VRSAVE related code from the function.
228 /// FIXME: The removal of the code results in a compile failure at -O0 when the
229 /// function contains a function call, as the GPR containing original VRSAVE
230 /// contents is spilled and reloaded around the call. Without the prolog code,
231 /// the spill instruction refers to an undefined register. This code needs
232 /// to account for all uses of that GPR.
233 static void RemoveVRSaveCode(MachineInstr *MI) {
234 MachineBasicBlock *Entry = MI->getParent();
235 MachineFunction *MF = Entry->getParent();
237 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
238 MachineBasicBlock::iterator MBBI = MI;
240 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
241 MBBI->eraseFromParent();
243 bool RemovedAllMTVRSAVEs = true;
244 // See if we can find and remove the MTVRSAVE instruction from all of the
246 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
247 // If last instruction is a return instruction, add an epilogue
248 if (!I->empty() && I->back().isReturn()) {
249 bool FoundIt = false;
250 for (MBBI = I->end(); MBBI != I->begin(); ) {
252 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
253 MBBI->eraseFromParent(); // remove it.
258 RemovedAllMTVRSAVEs &= FoundIt;
262 // If we found and removed all MTVRSAVE instructions, remove the read of
264 if (RemovedAllMTVRSAVEs) {
266 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
268 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
269 MBBI->eraseFromParent();
272 // Finally, nuke the UPDATE_VRSAVE.
273 MI->eraseFromParent();
276 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
277 // instruction selector. Based on the vector registers that have been used,
278 // transform this into the appropriate ORI instruction.
279 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
280 MachineFunction *MF = MI->getParent()->getParent();
281 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
282 DebugLoc dl = MI->getDebugLoc();
284 unsigned UsedRegMask = 0;
285 for (unsigned i = 0; i != 32; ++i)
286 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
287 UsedRegMask |= 1 << (31-i);
289 // Live in and live out values already must be in the mask, so don't bother
291 for (MachineRegisterInfo::livein_iterator
292 I = MF->getRegInfo().livein_begin(),
293 E = MF->getRegInfo().livein_end(); I != E; ++I) {
294 unsigned RegNo = TRI->getEncodingValue(I->first);
295 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
296 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
299 // Live out registers appear as use operands on return instructions.
300 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
301 UsedRegMask != 0 && BI != BE; ++BI) {
302 const MachineBasicBlock &MBB = *BI;
303 if (MBB.empty() || !MBB.back().isReturn())
305 const MachineInstr &Ret = MBB.back();
306 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
307 const MachineOperand &MO = Ret.getOperand(I);
308 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
310 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
311 UsedRegMask &= ~(1 << (31-RegNo));
315 // If no registers are used, turn this into a copy.
316 if (UsedRegMask == 0) {
317 // Remove all VRSAVE code.
318 RemoveVRSaveCode(MI);
322 unsigned SrcReg = MI->getOperand(1).getReg();
323 unsigned DstReg = MI->getOperand(0).getReg();
325 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
326 if (DstReg != SrcReg)
327 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
329 .addImm(UsedRegMask);
331 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
332 .addReg(SrcReg, RegState::Kill)
333 .addImm(UsedRegMask);
334 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
335 if (DstReg != SrcReg)
336 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
338 .addImm(UsedRegMask >> 16);
340 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
341 .addReg(SrcReg, RegState::Kill)
342 .addImm(UsedRegMask >> 16);
344 if (DstReg != SrcReg)
345 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
347 .addImm(UsedRegMask >> 16);
349 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
350 .addReg(SrcReg, RegState::Kill)
351 .addImm(UsedRegMask >> 16);
353 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
354 .addReg(DstReg, RegState::Kill)
355 .addImm(UsedRegMask & 0xFFFF);
358 // Remove the old UPDATE_VRSAVE instruction.
359 MI->eraseFromParent();
362 static bool spillsCR(const MachineFunction &MF) {
363 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
364 return FuncInfo->isCRSpilled();
367 static bool spillsVRSAVE(const MachineFunction &MF) {
368 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
369 return FuncInfo->isVRSAVESpilled();
372 static bool hasSpills(const MachineFunction &MF) {
373 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
374 return FuncInfo->hasSpills();
377 static bool hasNonRISpills(const MachineFunction &MF) {
378 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
379 return FuncInfo->hasNonRISpills();
382 /// determineFrameLayout - Determine the size of the frame and maximum call
384 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
386 bool UseEstimate) const {
387 MachineFrameInfo *MFI = MF.getFrameInfo();
389 // Get the number of bytes to allocate from the FrameInfo
391 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
393 // Get stack alignments. The frame must be aligned to the greatest of these:
394 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
395 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
396 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
398 const PPCRegisterInfo *RegInfo =
399 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
401 // If we are a leaf function, and use up to 224 bytes of stack space,
402 // don't have a frame pointer, calls, or dynamic alloca then we do not need
403 // to adjust the stack pointer (we fit in the Red Zone).
404 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
405 // stackless code if all local vars are reg-allocated.
406 bool DisableRedZone = MF.getFunction()->getAttributes().
407 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
408 if (!DisableRedZone &&
409 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
410 !Subtarget.isSVR4ABI() || // allocated locals.
412 FrameSize <= 224 && // Fits in red zone.
413 !MFI->hasVarSizedObjects() && // No dynamic alloca.
414 !MFI->adjustsStack() && // No calls.
415 !RegInfo->hasBasePointer(MF)) { // No special alignment.
418 MFI->setStackSize(0);
422 // Get the maximum call frame size of all the calls.
423 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
425 // Maximum call frame needs to be at least big enough for linkage and 8 args.
426 unsigned minCallFrameSize = getMinCallFrameSize(Subtarget.isPPC64(),
427 Subtarget.isDarwinABI());
428 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
430 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
431 // that allocations will be aligned.
432 if (MFI->hasVarSizedObjects())
433 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
435 // Update maximum call frame size.
437 MFI->setMaxCallFrameSize(maxCallFrameSize);
439 // Include call frame size in total.
440 FrameSize += maxCallFrameSize;
442 // Make sure the frame is aligned.
443 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
445 // Update frame info.
447 MFI->setStackSize(FrameSize);
452 // hasFP - Return true if the specified function actually has a dedicated frame
454 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
455 const MachineFrameInfo *MFI = MF.getFrameInfo();
456 // FIXME: This is pretty much broken by design: hasFP() might be called really
457 // early, before the stack layout was calculated and thus hasFP() might return
458 // true or false here depending on the time of call.
459 return (MFI->getStackSize()) && needsFP(MF);
462 // needsFP - Return true if the specified function should have a dedicated frame
463 // pointer register. This is true if the function has variable sized allocas or
464 // if frame pointer elimination is disabled.
465 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
466 const MachineFrameInfo *MFI = MF.getFrameInfo();
468 // Naked functions have no stack frame pushed, so we don't have a frame
470 if (MF.getFunction()->getAttributes().hasAttribute(
471 AttributeSet::FunctionIndex, Attribute::Naked))
474 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
475 MFI->hasVarSizedObjects() ||
476 (MF.getTarget().Options.GuaranteedTailCallOpt &&
477 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
480 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
481 bool is31 = needsFP(MF);
482 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
483 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
485 const PPCRegisterInfo *RegInfo =
486 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
487 bool HasBP = RegInfo->hasBasePointer(MF);
488 unsigned BPReg = HasBP ? (unsigned) PPC::R30 : FPReg;
489 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
491 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
493 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
495 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
496 MachineOperand &MO = MBBI->getOperand(I);
500 switch (MO.getReg()) {
519 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
520 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
521 MachineBasicBlock::iterator MBBI = MBB.begin();
522 MachineFrameInfo *MFI = MF.getFrameInfo();
523 const PPCInstrInfo &TII =
524 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
525 const PPCRegisterInfo *RegInfo =
526 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
528 MachineModuleInfo &MMI = MF.getMMI();
529 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
531 bool needsFrameMoves = MMI.hasDebugInfo() ||
532 MF.getFunction()->needsUnwindTableEntry();
534 // Get processor type.
535 bool isPPC64 = Subtarget.isPPC64();
537 bool isDarwinABI = Subtarget.isDarwinABI();
538 bool isSVR4ABI = Subtarget.isSVR4ABI();
539 assert((isDarwinABI || isSVR4ABI) &&
540 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
542 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
545 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
546 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
547 HandleVRSaveUpdate(MBBI, TII);
552 // Move MBBI back to the beginning of the function.
555 // Work out frame sizes.
556 unsigned FrameSize = determineFrameLayout(MF);
557 int NegFrameSize = -FrameSize;
558 if (!isInt<32>(NegFrameSize))
559 llvm_unreachable("Unhandled stack size!");
561 if (MFI->isFrameAddressTaken())
562 replaceFPWithRealFP(MF);
564 // Check if the link register (LR) must be saved.
565 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
566 bool MustSaveLR = FI->mustSaveLR();
567 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
568 // Do we have a frame pointer and/or base pointer for this function?
569 bool HasFP = hasFP(MF);
570 bool HasBP = RegInfo->hasBasePointer(MF);
572 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
573 unsigned BPReg = isPPC64 ? PPC::X30 : PPC::R30;
574 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
575 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
576 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
577 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
578 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
579 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
581 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
583 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
585 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
587 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
589 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
591 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
593 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
595 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
598 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
599 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
600 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
601 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
602 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
603 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
605 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
610 MachineFrameInfo *FFI = MF.getFrameInfo();
611 int FPIndex = FI->getFramePointerSaveIndex();
612 assert(FPIndex && "No Frame Pointer Save Slot!");
613 FPOffset = FFI->getObjectOffset(FPIndex);
616 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
623 MachineFrameInfo *FFI = MF.getFrameInfo();
624 int BPIndex = FI->getBasePointerSaveIndex();
625 assert(BPIndex && "No Base Pointer Save Slot!");
626 BPOffset = FFI->getObjectOffset(BPIndex);
629 PPCFrameLowering::getBasePointerSaveOffset(isPPC64, isDarwinABI);
633 // Get stack alignments.
634 unsigned MaxAlign = MFI->getMaxAlignment();
635 if (HasBP && MaxAlign > 1)
636 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
637 "Invalid alignment!");
639 // Frames of 32KB & larger require special handling because they cannot be
640 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
641 bool isLargeFrame = !isInt<16>(NegFrameSize);
644 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
646 assert((isPPC64 || MustSaveCRs.empty()) &&
647 "Prologue CR saving supported only in 64-bit mode");
649 if (!MustSaveCRs.empty()) { // will only occur for PPC64
650 MachineInstrBuilder MIB =
651 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
652 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
653 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
657 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
658 BuildMI(MBB, MBBI, dl, StoreInst)
664 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
665 BuildMI(MBB, MBBI, dl, StoreInst)
671 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
672 BuildMI(MBB, MBBI, dl, StoreInst)
677 if (!MustSaveCRs.empty()) // will only occur for PPC64
678 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
679 .addReg(TempReg, getKillRegState(true))
683 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
684 if (!FrameSize) return;
686 // Adjust stack pointer: r1 += NegFrameSize.
687 // If there is a preferred stack alignment, align R1 now
690 // Save a copy of r1 as the base pointer.
691 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
696 if (HasBP && MaxAlign > 1) {
698 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
701 .addImm(64 - Log2_32(MaxAlign));
703 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
706 .addImm(32 - Log2_32(MaxAlign))
709 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
710 .addReg(ScratchReg, RegState::Kill)
711 .addImm(NegFrameSize);
713 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
714 .addImm(NegFrameSize >> 16);
715 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
716 .addReg(TempReg, RegState::Kill)
717 .addImm(NegFrameSize & 0xFFFF);
718 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
719 .addReg(ScratchReg, RegState::Kill)
720 .addReg(TempReg, RegState::Kill);
722 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
723 .addReg(SPReg, RegState::Kill)
727 } else if (!isLargeFrame) {
728 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
730 .addImm(NegFrameSize)
734 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
735 .addImm(NegFrameSize >> 16);
736 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
737 .addReg(ScratchReg, RegState::Kill)
738 .addImm(NegFrameSize & 0xFFFF);
739 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
740 .addReg(SPReg, RegState::Kill)
745 // Add the "machine moves" for the instructions we generated above, but in
747 if (needsFrameMoves) {
748 // Show update of SP.
749 assert(NegFrameSize);
750 unsigned CFIIndex = MMI.addFrameInst(
751 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
752 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
753 .addCFIIndex(CFIIndex);
756 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
757 CFIIndex = MMI.addFrameInst(
758 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
759 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
760 .addCFIIndex(CFIIndex);
764 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
765 CFIIndex = MMI.addFrameInst(
766 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
767 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
768 .addCFIIndex(CFIIndex);
772 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
773 CFIIndex = MMI.addFrameInst(
774 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
775 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
776 .addCFIIndex(CFIIndex);
780 // If there is a frame pointer, copy R1 into R31
782 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
786 if (needsFrameMoves) {
787 // Mark effective beginning of when frame pointer is ready.
788 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
789 unsigned CFIIndex = MMI.addFrameInst(
790 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
792 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
793 .addCFIIndex(CFIIndex);
797 if (needsFrameMoves) {
798 // Add callee saved registers to move list.
799 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
800 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
801 unsigned Reg = CSI[I].getReg();
802 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
804 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
805 // subregisters of CR2. We just need to emit a move of CR2.
806 if (PPC::CRBITRCRegClass.contains(Reg))
809 // For SVR4, don't emit a move for the CR spill slot if we haven't
811 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
812 && MustSaveCRs.empty())
815 // For 64-bit SVR4 when we have spilled CRs, the spill location
816 // is SP+8, not a frame-relative slot.
817 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
818 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
819 nullptr, MRI->getDwarfRegNum(PPC::CR2, true), 8));
820 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
821 .addCFIIndex(CFIIndex);
825 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
826 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
827 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
828 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
829 .addCFIIndex(CFIIndex);
834 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
835 MachineBasicBlock &MBB) const {
836 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
837 assert(MBBI != MBB.end() && "Returning block has no terminator");
838 const PPCInstrInfo &TII =
839 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
840 const PPCRegisterInfo *RegInfo =
841 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
843 unsigned RetOpcode = MBBI->getOpcode();
846 assert((RetOpcode == PPC::BLR ||
847 RetOpcode == PPC::TCRETURNri ||
848 RetOpcode == PPC::TCRETURNdi ||
849 RetOpcode == PPC::TCRETURNai ||
850 RetOpcode == PPC::TCRETURNri8 ||
851 RetOpcode == PPC::TCRETURNdi8 ||
852 RetOpcode == PPC::TCRETURNai8) &&
853 "Can only insert epilog into returning blocks");
855 // Get alignment info so we know how to restore the SP.
856 const MachineFrameInfo *MFI = MF.getFrameInfo();
858 // Get the number of bytes allocated from the FrameInfo.
859 int FrameSize = MFI->getStackSize();
861 // Get processor type.
862 bool isPPC64 = Subtarget.isPPC64();
864 bool isDarwinABI = Subtarget.isDarwinABI();
865 bool isSVR4ABI = Subtarget.isSVR4ABI();
867 // Check if the link register (LR) has been saved.
868 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
869 bool MustSaveLR = FI->mustSaveLR();
870 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
871 // Do we have a frame pointer and/or base pointer for this function?
872 bool HasFP = hasFP(MF);
873 bool HasBP = RegInfo->hasBasePointer(MF);
875 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
876 unsigned BPReg = isPPC64 ? PPC::X30 : PPC::R30;
877 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
878 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
879 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
880 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
882 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
884 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
886 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
888 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
890 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
893 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
898 MachineFrameInfo *FFI = MF.getFrameInfo();
899 int FPIndex = FI->getFramePointerSaveIndex();
900 assert(FPIndex && "No Frame Pointer Save Slot!");
901 FPOffset = FFI->getObjectOffset(FPIndex);
904 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
911 MachineFrameInfo *FFI = MF.getFrameInfo();
912 int BPIndex = FI->getBasePointerSaveIndex();
913 assert(BPIndex && "No Base Pointer Save Slot!");
914 BPOffset = FFI->getObjectOffset(BPIndex);
917 PPCFrameLowering::getBasePointerSaveOffset(isPPC64, isDarwinABI);
921 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
922 RetOpcode == PPC::TCRETURNdi ||
923 RetOpcode == PPC::TCRETURNai ||
924 RetOpcode == PPC::TCRETURNri8 ||
925 RetOpcode == PPC::TCRETURNdi8 ||
926 RetOpcode == PPC::TCRETURNai8;
929 int MaxTCRetDelta = FI->getTailCallSPDelta();
930 MachineOperand &StackAdjust = MBBI->getOperand(1);
931 assert(StackAdjust.isImm() && "Expecting immediate value.");
932 // Adjust stack pointer.
933 int StackAdj = StackAdjust.getImm();
934 int Delta = StackAdj - MaxTCRetDelta;
935 assert((Delta >= 0) && "Delta must be positive");
937 FrameSize += (StackAdj +Delta);
939 FrameSize += StackAdj;
942 // Frames of 32KB & larger require special handling because they cannot be
943 // indexed into with a simple LD/LWZ immediate offset operand.
944 bool isLargeFrame = !isInt<16>(FrameSize);
947 // In the prologue, the loaded (or persistent) stack pointer value is offset
948 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
950 // If this function contained a fastcc call and GuaranteedTailCallOpt is
951 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
952 // call which invalidates the stack pointer value in SP(0). So we use the
953 // value of R31 in this case.
954 if (FI->hasFastCall()) {
955 assert(HasFP && "Expecting a valid frame pointer.");
957 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
958 .addReg(FPReg).addImm(FrameSize);
960 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
961 .addImm(FrameSize >> 16);
962 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
963 .addReg(ScratchReg, RegState::Kill)
964 .addImm(FrameSize & 0xFFFF);
965 BuildMI(MBB, MBBI, dl, AddInst)
970 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
971 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
975 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
983 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
987 assert((isPPC64 || MustSaveCRs.empty()) &&
988 "Epilogue CR restoring supported only in 64-bit mode");
990 if (!MustSaveCRs.empty()) // will only occur for PPC64
991 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
996 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1001 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1005 if (!MustSaveCRs.empty()) // will only occur for PPC64
1006 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1007 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1008 .addReg(TempReg, getKillRegState(i == e-1));
1011 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1013 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1014 // call optimization
1015 if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1016 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1017 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1018 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1020 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1021 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1022 .addReg(SPReg).addImm(CallerAllocatedAmt);
1024 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1025 .addImm(CallerAllocatedAmt >> 16);
1026 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1027 .addReg(ScratchReg, RegState::Kill)
1028 .addImm(CallerAllocatedAmt & 0xFFFF);
1029 BuildMI(MBB, MBBI, dl, AddInst)
1032 .addReg(ScratchReg);
1034 } else if (RetOpcode == PPC::TCRETURNdi) {
1035 MBBI = MBB.getLastNonDebugInstr();
1036 MachineOperand &JumpTarget = MBBI->getOperand(0);
1037 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1038 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1039 } else if (RetOpcode == PPC::TCRETURNri) {
1040 MBBI = MBB.getLastNonDebugInstr();
1041 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1042 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1043 } else if (RetOpcode == PPC::TCRETURNai) {
1044 MBBI = MBB.getLastNonDebugInstr();
1045 MachineOperand &JumpTarget = MBBI->getOperand(0);
1046 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1047 } else if (RetOpcode == PPC::TCRETURNdi8) {
1048 MBBI = MBB.getLastNonDebugInstr();
1049 MachineOperand &JumpTarget = MBBI->getOperand(0);
1050 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1051 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1052 } else if (RetOpcode == PPC::TCRETURNri8) {
1053 MBBI = MBB.getLastNonDebugInstr();
1054 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1055 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1056 } else if (RetOpcode == PPC::TCRETURNai8) {
1057 MBBI = MBB.getLastNonDebugInstr();
1058 MachineOperand &JumpTarget = MBBI->getOperand(0);
1059 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1063 /// MustSaveLR - Return true if this function requires that we save the LR
1064 /// register onto the stack in the prolog and restore it in the epilog of the
1066 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
1067 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
1069 // We need a save/restore of LR if there is any def of LR (which is
1070 // defined by calls, including the PIC setup sequence), or if there is
1071 // some use of the LR stack slot (e.g. for builtin_return_address).
1072 // (LR comes in 32 and 64 bit versions.)
1073 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
1074 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
1078 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1079 RegScavenger *) const {
1080 const PPCRegisterInfo *RegInfo =
1081 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
1083 // Save and clear the LR state.
1084 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1085 unsigned LR = RegInfo->getRARegister();
1086 FI->setMustSaveLR(MustSaveLR(MF, LR));
1087 MachineRegisterInfo &MRI = MF.getRegInfo();
1088 MRI.setPhysRegUnused(LR);
1090 // Save R31 if necessary
1091 int FPSI = FI->getFramePointerSaveIndex();
1092 bool isPPC64 = Subtarget.isPPC64();
1093 bool isDarwinABI = Subtarget.isDarwinABI();
1094 MachineFrameInfo *MFI = MF.getFrameInfo();
1096 // If the frame pointer save index hasn't been defined yet.
1097 if (!FPSI && needsFP(MF)) {
1098 // Find out what the fix offset of the frame pointer save area.
1099 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1100 // Allocate the frame index for frame pointer save area.
1101 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1103 FI->setFramePointerSaveIndex(FPSI);
1106 int BPSI = FI->getBasePointerSaveIndex();
1107 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1108 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI);
1109 // Allocate the frame index for the base pointer save area.
1110 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1112 FI->setBasePointerSaveIndex(BPSI);
1115 // Reserve stack space to move the linkage area to in case of a tail call.
1117 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1118 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1119 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1122 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1123 // function uses CR 2, 3, or 4.
1124 if (!isPPC64 && !isDarwinABI &&
1125 (MRI.isPhysRegUsed(PPC::CR2) ||
1126 MRI.isPhysRegUsed(PPC::CR3) ||
1127 MRI.isPhysRegUsed(PPC::CR4))) {
1128 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1129 FI->setCRSpillFrameIndex(FrameIdx);
1133 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1134 RegScavenger *RS) const {
1135 // Early exit if not using the SVR4 ABI.
1136 if (!Subtarget.isSVR4ABI()) {
1137 addScavengingSpillSlot(MF, RS);
1141 // Get callee saved register information.
1142 MachineFrameInfo *FFI = MF.getFrameInfo();
1143 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1145 // Early exit if no callee saved registers are modified!
1146 if (CSI.empty() && !needsFP(MF)) {
1147 addScavengingSpillSlot(MF, RS);
1151 unsigned MinGPR = PPC::R31;
1152 unsigned MinG8R = PPC::X31;
1153 unsigned MinFPR = PPC::F31;
1154 unsigned MinVR = PPC::V31;
1156 bool HasGPSaveArea = false;
1157 bool HasG8SaveArea = false;
1158 bool HasFPSaveArea = false;
1159 bool HasVRSAVESaveArea = false;
1160 bool HasVRSaveArea = false;
1162 SmallVector<CalleeSavedInfo, 18> GPRegs;
1163 SmallVector<CalleeSavedInfo, 18> G8Regs;
1164 SmallVector<CalleeSavedInfo, 18> FPRegs;
1165 SmallVector<CalleeSavedInfo, 18> VRegs;
1167 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1168 unsigned Reg = CSI[i].getReg();
1169 if (PPC::GPRCRegClass.contains(Reg)) {
1170 HasGPSaveArea = true;
1172 GPRegs.push_back(CSI[i]);
1177 } else if (PPC::G8RCRegClass.contains(Reg)) {
1178 HasG8SaveArea = true;
1180 G8Regs.push_back(CSI[i]);
1185 } else if (PPC::F8RCRegClass.contains(Reg)) {
1186 HasFPSaveArea = true;
1188 FPRegs.push_back(CSI[i]);
1193 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1194 PPC::CRRCRegClass.contains(Reg)) {
1195 ; // do nothing, as we already know whether CRs are spilled
1196 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1197 HasVRSAVESaveArea = true;
1198 } else if (PPC::VRRCRegClass.contains(Reg)) {
1199 HasVRSaveArea = true;
1201 VRegs.push_back(CSI[i]);
1207 llvm_unreachable("Unknown RegisterClass!");
1211 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1212 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1214 int64_t LowerBound = 0;
1216 // Take into account stack space reserved for tail calls.
1218 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1219 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1220 LowerBound = TCSPDelta;
1223 // The Floating-point register save area is right below the back chain word
1224 // of the previous stack frame.
1225 if (HasFPSaveArea) {
1226 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1227 int FI = FPRegs[i].getFrameIdx();
1229 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1232 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1235 // Check whether the frame pointer register is allocated. If so, make sure it
1236 // is spilled to the correct offset.
1238 HasGPSaveArea = true;
1240 int FI = PFI->getFramePointerSaveIndex();
1241 assert(FI && "No Frame Pointer Save Slot!");
1243 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1246 const PPCRegisterInfo *RegInfo =
1247 static_cast<const PPCRegisterInfo*>(MF.getTarget().getRegisterInfo());
1248 if (RegInfo->hasBasePointer(MF)) {
1249 HasGPSaveArea = true;
1251 int FI = PFI->getBasePointerSaveIndex();
1252 assert(FI && "No Base Pointer Save Slot!");
1254 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1257 // General register save area starts right below the Floating-point
1258 // register save area.
1259 if (HasGPSaveArea || HasG8SaveArea) {
1260 // Move general register save area spill slots down, taking into account
1261 // the size of the Floating-point register save area.
1262 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1263 int FI = GPRegs[i].getFrameIdx();
1265 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1268 // Move general register save area spill slots down, taking into account
1269 // the size of the Floating-point register save area.
1270 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1271 int FI = G8Regs[i].getFrameIdx();
1273 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1277 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1278 TRI->getEncodingValue(MinG8R));
1280 if (Subtarget.isPPC64()) {
1281 LowerBound -= (31 - MinReg + 1) * 8;
1283 LowerBound -= (31 - MinReg + 1) * 4;
1287 // For 32-bit only, the CR save area is below the general register
1288 // save area. For 64-bit SVR4, the CR save area is addressed relative
1289 // to the stack pointer and hence does not need an adjustment here.
1290 // Only CR2 (the first nonvolatile spilled) has an associated frame
1291 // index so that we have a single uniform save area.
1292 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1293 // Adjust the frame index of the CR spill slot.
1294 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1295 unsigned Reg = CSI[i].getReg();
1297 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1298 // Leave Darwin logic as-is.
1299 || (!Subtarget.isSVR4ABI() &&
1300 (PPC::CRBITRCRegClass.contains(Reg) ||
1301 PPC::CRRCRegClass.contains(Reg)))) {
1302 int FI = CSI[i].getFrameIdx();
1304 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1308 LowerBound -= 4; // The CR save area is always 4 bytes long.
1311 if (HasVRSAVESaveArea) {
1312 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1313 // which have the VRSAVE register class?
1314 // Adjust the frame index of the VRSAVE spill slot.
1315 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1316 unsigned Reg = CSI[i].getReg();
1318 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1319 int FI = CSI[i].getFrameIdx();
1321 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1325 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1328 if (HasVRSaveArea) {
1329 // Insert alignment padding, we need 16-byte alignment.
1330 LowerBound = (LowerBound - 15) & ~(15);
1332 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1333 int FI = VRegs[i].getFrameIdx();
1335 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1339 addScavengingSpillSlot(MF, RS);
1343 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1344 RegScavenger *RS) const {
1345 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1346 // a large stack, which will require scavenging a register to materialize a
1349 // We need to have a scavenger spill slot for spills if the frame size is
1350 // large. In case there is no free register for large-offset addressing,
1351 // this slot is used for the necessary emergency spill. Also, we need the
1352 // slot for dynamic stack allocations.
1354 // The scavenger might be invoked if the frame offset does not fit into
1355 // the 16-bit immediate. We don't know the complete frame size here
1356 // because we've not yet computed callee-saved register spills or the
1357 // needed alignment padding.
1358 unsigned StackSize = determineFrameLayout(MF, false, true);
1359 MachineFrameInfo *MFI = MF.getFrameInfo();
1360 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1361 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1362 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1363 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1364 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1365 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1369 // Might we have over-aligned allocas?
1370 bool HasAlVars = MFI->hasVarSizedObjects() &&
1371 MFI->getMaxAlignment() > getStackAlignment();
1373 // These kinds of spills might need two registers.
1374 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1375 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1383 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1384 MachineBasicBlock::iterator MI,
1385 const std::vector<CalleeSavedInfo> &CSI,
1386 const TargetRegisterInfo *TRI) const {
1388 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1389 // Return false otherwise to maintain pre-existing behavior.
1390 if (!Subtarget.isSVR4ABI())
1393 MachineFunction *MF = MBB.getParent();
1394 const PPCInstrInfo &TII =
1395 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1397 bool CRSpilled = false;
1398 MachineInstrBuilder CRMIB;
1400 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1401 unsigned Reg = CSI[i].getReg();
1402 // Only Darwin actually uses the VRSAVE register, but it can still appear
1403 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1404 // Darwin, ignore it.
1405 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1408 // CR2 through CR4 are the nonvolatile CR fields.
1409 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1411 // Add the callee-saved register as live-in; it's killed at the spill.
1414 if (CRSpilled && IsCRField) {
1415 CRMIB.addReg(Reg, RegState::ImplicitKill);
1419 // Insert the spill to the stack frame.
1421 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1422 if (Subtarget.isPPC64()) {
1423 // The actual spill will happen at the start of the prologue.
1424 FuncInfo->addMustSaveCR(Reg);
1427 FuncInfo->setSpillsCR();
1429 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1430 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1431 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1432 .addReg(Reg, RegState::ImplicitKill);
1434 MBB.insert(MI, CRMIB);
1435 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1437 getKillRegState(true)),
1438 CSI[i].getFrameIdx()));
1441 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1442 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1443 CSI[i].getFrameIdx(), RC, TRI);
1450 restoreCRs(bool isPPC64, bool is31,
1451 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1452 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1453 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1455 MachineFunction *MF = MBB.getParent();
1456 const PPCInstrInfo &TII =
1457 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1459 unsigned RestoreOp, MoveReg;
1462 // This is handled during epilogue generation.
1465 // 32-bit: FP-relative
1466 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1468 CSI[CSIIndex].getFrameIdx()));
1469 RestoreOp = PPC::MTOCRF;
1474 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1475 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1478 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1479 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1482 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1483 .addReg(MoveReg, getKillRegState(true)));
1486 void PPCFrameLowering::
1487 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1488 MachineBasicBlock::iterator I) const {
1489 const PPCInstrInfo &TII =
1490 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
1491 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1492 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1493 // Add (actually subtract) back the amount the callee popped on return.
1494 if (int CalleeAmt = I->getOperand(1).getImm()) {
1495 bool is64Bit = Subtarget.isPPC64();
1497 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1498 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1499 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1500 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1501 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1502 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1503 MachineInstr *MI = I;
1504 DebugLoc dl = MI->getDebugLoc();
1506 if (isInt<16>(CalleeAmt)) {
1507 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1508 .addReg(StackReg, RegState::Kill)
1511 MachineBasicBlock::iterator MBBI = I;
1512 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1513 .addImm(CalleeAmt >> 16);
1514 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1515 .addReg(TmpReg, RegState::Kill)
1516 .addImm(CalleeAmt & 0xFFFF);
1517 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1518 .addReg(StackReg, RegState::Kill)
1523 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1528 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1529 MachineBasicBlock::iterator MI,
1530 const std::vector<CalleeSavedInfo> &CSI,
1531 const TargetRegisterInfo *TRI) const {
1533 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1534 // Return false otherwise to maintain pre-existing behavior.
1535 if (!Subtarget.isSVR4ABI())
1538 MachineFunction *MF = MBB.getParent();
1539 const PPCInstrInfo &TII =
1540 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1541 bool CR2Spilled = false;
1542 bool CR3Spilled = false;
1543 bool CR4Spilled = false;
1544 unsigned CSIIndex = 0;
1546 // Initialize insertion-point logic; we will be restoring in reverse
1548 MachineBasicBlock::iterator I = MI, BeforeI = I;
1549 bool AtStart = I == MBB.begin();
1554 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1555 unsigned Reg = CSI[i].getReg();
1557 // Only Darwin actually uses the VRSAVE register, but it can still appear
1558 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1559 // Darwin, ignore it.
1560 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1563 if (Reg == PPC::CR2) {
1565 // The spill slot is associated only with CR2, which is the
1566 // first nonvolatile spilled. Save it here.
1569 } else if (Reg == PPC::CR3) {
1572 } else if (Reg == PPC::CR4) {
1576 // When we first encounter a non-CR register after seeing at
1577 // least one CR register, restore all spilled CRs together.
1578 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1579 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1580 bool is31 = needsFP(*MF);
1581 restoreCRs(Subtarget.isPPC64(), is31,
1582 CR2Spilled, CR3Spilled, CR4Spilled,
1583 MBB, I, CSI, CSIIndex);
1584 CR2Spilled = CR3Spilled = CR4Spilled = false;
1587 // Default behavior for non-CR saves.
1588 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1589 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1591 assert(I != MBB.begin() &&
1592 "loadRegFromStackSlot didn't insert any code!");
1595 // Insert in reverse order.
1604 // If we haven't yet spilled the CRs, do so now.
1605 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1606 bool is31 = needsFP(*MF);
1607 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1608 MBB, I, CSI, CSIIndex);