1 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the PPC implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCFrameLowering.h"
15 #include "PPCInstrBuilder.h"
16 #include "PPCInstrInfo.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Target/TargetOptions.h"
30 /// VRRegNo - Map from a numbered VR register to its enum value.
32 static const uint16_t VRRegNo[] = {
33 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
34 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
35 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
36 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
39 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
40 if (STI.isDarwinABI())
41 return STI.isPPC64() ? 16 : 8;
43 return STI.isPPC64() ? 16 : 4;
46 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
47 return STI.isELFv2ABI() ? 24 : 40;
50 static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
51 // For the Darwin ABI:
52 // We cannot use the TOC save slot (offset +20) in the PowerPC linkage area
53 // for saving the frame pointer (if needed.) While the published ABI has
54 // not used this slot since at least MacOSX 10.2, there is older code
55 // around that does use it, and that needs to continue to work.
56 if (STI.isDarwinABI())
57 return STI.isPPC64() ? -8U : -4U;
59 // SVR4 ABI: First slot in the general register save area.
60 return STI.isPPC64() ? -8U : -4U;
63 static unsigned computeLinkageSize(const PPCSubtarget &STI) {
64 if (STI.isDarwinABI() || STI.isPPC64())
65 return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
71 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
72 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
73 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
74 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
75 TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
76 FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
77 LinkageSize(computeLinkageSize(Subtarget)) {}
79 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
80 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
81 unsigned &NumEntries) const {
82 if (Subtarget.isDarwinABI()) {
84 if (Subtarget.isPPC64()) {
85 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
86 return &darwin64Offsets;
88 static const SpillSlot darwinOffsets = {PPC::R31, -4};
89 return &darwinOffsets;
93 // Early exit if not using the SVR4 ABI.
94 if (!Subtarget.isSVR4ABI()) {
99 // Note that the offsets here overlap, but this is fixed up in
100 // processFunctionBeforeFrameFinalized.
102 static const SpillSlot Offsets[] = {
103 // Floating-point register save area offsets.
123 // General register save area offsets.
143 // CR save area offset. We map each of the nonvolatile CR fields
144 // to the slot for CR2, which is the first of the nonvolatile CR
145 // fields to be assigned, so that we only allocate one save slot.
146 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
149 // VRSAVE save area offset.
152 // Vector register save area
166 static const SpillSlot Offsets64[] = {
167 // Floating-point register save area offsets.
187 // General register save area offsets.
207 // VRSAVE save area offset.
210 // Vector register save area
224 if (Subtarget.isPPC64()) {
225 NumEntries = array_lengthof(Offsets64);
229 NumEntries = array_lengthof(Offsets);
235 /// RemoveVRSaveCode - We have found that this function does not need any code
236 /// to manipulate the VRSAVE register, even though it uses vector registers.
237 /// This can happen when the only registers used are known to be live in or out
238 /// of the function. Remove all of the VRSAVE related code from the function.
239 /// FIXME: The removal of the code results in a compile failure at -O0 when the
240 /// function contains a function call, as the GPR containing original VRSAVE
241 /// contents is spilled and reloaded around the call. Without the prolog code,
242 /// the spill instruction refers to an undefined register. This code needs
243 /// to account for all uses of that GPR.
244 static void RemoveVRSaveCode(MachineInstr *MI) {
245 MachineBasicBlock *Entry = MI->getParent();
246 MachineFunction *MF = Entry->getParent();
248 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
249 MachineBasicBlock::iterator MBBI = MI;
251 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
252 MBBI->eraseFromParent();
254 bool RemovedAllMTVRSAVEs = true;
255 // See if we can find and remove the MTVRSAVE instruction from all of the
257 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
258 // If last instruction is a return instruction, add an epilogue
259 if (!I->empty() && I->back().isReturn()) {
260 bool FoundIt = false;
261 for (MBBI = I->end(); MBBI != I->begin(); ) {
263 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
264 MBBI->eraseFromParent(); // remove it.
269 RemovedAllMTVRSAVEs &= FoundIt;
273 // If we found and removed all MTVRSAVE instructions, remove the read of
275 if (RemovedAllMTVRSAVEs) {
277 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
279 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
280 MBBI->eraseFromParent();
283 // Finally, nuke the UPDATE_VRSAVE.
284 MI->eraseFromParent();
287 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
288 // instruction selector. Based on the vector registers that have been used,
289 // transform this into the appropriate ORI instruction.
290 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
291 MachineFunction *MF = MI->getParent()->getParent();
292 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
293 DebugLoc dl = MI->getDebugLoc();
295 unsigned UsedRegMask = 0;
296 for (unsigned i = 0; i != 32; ++i)
297 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
298 UsedRegMask |= 1 << (31-i);
300 // Live in and live out values already must be in the mask, so don't bother
302 for (MachineRegisterInfo::livein_iterator
303 I = MF->getRegInfo().livein_begin(),
304 E = MF->getRegInfo().livein_end(); I != E; ++I) {
305 unsigned RegNo = TRI->getEncodingValue(I->first);
306 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
307 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
310 // Live out registers appear as use operands on return instructions.
311 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
312 UsedRegMask != 0 && BI != BE; ++BI) {
313 const MachineBasicBlock &MBB = *BI;
314 if (MBB.empty() || !MBB.back().isReturn())
316 const MachineInstr &Ret = MBB.back();
317 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
318 const MachineOperand &MO = Ret.getOperand(I);
319 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
321 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
322 UsedRegMask &= ~(1 << (31-RegNo));
326 // If no registers are used, turn this into a copy.
327 if (UsedRegMask == 0) {
328 // Remove all VRSAVE code.
329 RemoveVRSaveCode(MI);
333 unsigned SrcReg = MI->getOperand(1).getReg();
334 unsigned DstReg = MI->getOperand(0).getReg();
336 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
337 if (DstReg != SrcReg)
338 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
340 .addImm(UsedRegMask);
342 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
343 .addReg(SrcReg, RegState::Kill)
344 .addImm(UsedRegMask);
345 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
346 if (DstReg != SrcReg)
347 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
349 .addImm(UsedRegMask >> 16);
351 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
352 .addReg(SrcReg, RegState::Kill)
353 .addImm(UsedRegMask >> 16);
355 if (DstReg != SrcReg)
356 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
358 .addImm(UsedRegMask >> 16);
360 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
361 .addReg(SrcReg, RegState::Kill)
362 .addImm(UsedRegMask >> 16);
364 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
365 .addReg(DstReg, RegState::Kill)
366 .addImm(UsedRegMask & 0xFFFF);
369 // Remove the old UPDATE_VRSAVE instruction.
370 MI->eraseFromParent();
373 static bool spillsCR(const MachineFunction &MF) {
374 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
375 return FuncInfo->isCRSpilled();
378 static bool spillsVRSAVE(const MachineFunction &MF) {
379 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
380 return FuncInfo->isVRSAVESpilled();
383 static bool hasSpills(const MachineFunction &MF) {
384 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
385 return FuncInfo->hasSpills();
388 static bool hasNonRISpills(const MachineFunction &MF) {
389 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
390 return FuncInfo->hasNonRISpills();
393 /// MustSaveLR - Return true if this function requires that we save the LR
394 /// register onto the stack in the prolog and restore it in the epilog of the
396 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
397 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
399 // We need a save/restore of LR if there is any def of LR (which is
400 // defined by calls, including the PIC setup sequence), or if there is
401 // some use of the LR stack slot (e.g. for builtin_return_address).
402 // (LR comes in 32 and 64 bit versions.)
403 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
404 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
407 /// determineFrameLayout - Determine the size of the frame and maximum call
409 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
411 bool UseEstimate) const {
412 MachineFrameInfo *MFI = MF.getFrameInfo();
414 // Get the number of bytes to allocate from the FrameInfo
416 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
418 // Get stack alignments. The frame must be aligned to the greatest of these:
419 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
420 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
421 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
423 const PPCRegisterInfo *RegInfo =
424 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
426 // If we are a leaf function, and use up to 224 bytes of stack space,
427 // don't have a frame pointer, calls, or dynamic alloca then we do not need
428 // to adjust the stack pointer (we fit in the Red Zone).
429 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
430 // stackless code if all local vars are reg-allocated.
431 bool DisableRedZone = MF.getFunction()->getAttributes().
432 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
433 unsigned LR = RegInfo->getRARegister();
434 if (!DisableRedZone &&
435 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
436 !Subtarget.isSVR4ABI() || // allocated locals.
438 FrameSize <= 224 && // Fits in red zone.
439 !MFI->hasVarSizedObjects() && // No dynamic alloca.
440 !MFI->adjustsStack() && // No calls.
441 !MustSaveLR(MF, LR) &&
442 !RegInfo->hasBasePointer(MF)) { // No special alignment.
445 MFI->setStackSize(0);
449 // Get the maximum call frame size of all the calls.
450 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
452 // Maximum call frame needs to be at least big enough for linkage area.
453 unsigned minCallFrameSize = getLinkageSize();
454 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
456 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
457 // that allocations will be aligned.
458 if (MFI->hasVarSizedObjects())
459 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
461 // Update maximum call frame size.
463 MFI->setMaxCallFrameSize(maxCallFrameSize);
465 // Include call frame size in total.
466 FrameSize += maxCallFrameSize;
468 // Make sure the frame is aligned.
469 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
471 // Update frame info.
473 MFI->setStackSize(FrameSize);
478 // hasFP - Return true if the specified function actually has a dedicated frame
480 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
481 const MachineFrameInfo *MFI = MF.getFrameInfo();
482 // FIXME: This is pretty much broken by design: hasFP() might be called really
483 // early, before the stack layout was calculated and thus hasFP() might return
484 // true or false here depending on the time of call.
485 return (MFI->getStackSize()) && needsFP(MF);
488 // needsFP - Return true if the specified function should have a dedicated frame
489 // pointer register. This is true if the function has variable sized allocas or
490 // if frame pointer elimination is disabled.
491 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
492 const MachineFrameInfo *MFI = MF.getFrameInfo();
494 // Naked functions have no stack frame pushed, so we don't have a frame
496 if (MF.getFunction()->getAttributes().hasAttribute(
497 AttributeSet::FunctionIndex, Attribute::Naked))
500 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
501 MFI->hasVarSizedObjects() ||
502 MFI->hasStackMap() || MFI->hasPatchPoint() ||
503 (MF.getTarget().Options.GuaranteedTailCallOpt &&
504 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
507 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
508 bool is31 = needsFP(MF);
509 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
510 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
512 const PPCRegisterInfo *RegInfo =
513 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
514 bool HasBP = RegInfo->hasBasePointer(MF);
515 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
516 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
518 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
520 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
522 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
523 MachineOperand &MO = MBBI->getOperand(I);
527 switch (MO.getReg()) {
546 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
547 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
548 MachineBasicBlock::iterator MBBI = MBB.begin();
549 MachineFrameInfo *MFI = MF.getFrameInfo();
550 const PPCInstrInfo &TII =
551 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
552 const PPCRegisterInfo *RegInfo =
553 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
555 MachineModuleInfo &MMI = MF.getMMI();
556 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
558 bool needsCFI = MMI.hasDebugInfo() ||
559 MF.getFunction()->needsUnwindTableEntry();
560 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
562 // Get processor type.
563 bool isPPC64 = Subtarget.isPPC64();
565 bool isDarwinABI = Subtarget.isDarwinABI();
566 bool isSVR4ABI = Subtarget.isSVR4ABI();
567 bool isELFv2ABI = Subtarget.isELFv2ABI();
568 assert((isDarwinABI || isSVR4ABI) &&
569 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
571 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
574 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
575 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
576 HandleVRSaveUpdate(MBBI, TII);
581 // Move MBBI back to the beginning of the function.
584 // Work out frame sizes.
585 unsigned FrameSize = determineFrameLayout(MF);
586 int NegFrameSize = -FrameSize;
587 if (!isInt<32>(NegFrameSize))
588 llvm_unreachable("Unhandled stack size!");
590 if (MFI->isFrameAddressTaken())
591 replaceFPWithRealFP(MF);
593 // Check if the link register (LR) must be saved.
594 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
595 bool MustSaveLR = FI->mustSaveLR();
596 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
597 // Do we have a frame pointer and/or base pointer for this function?
598 bool HasFP = hasFP(MF);
599 bool HasBP = RegInfo->hasBasePointer(MF);
601 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
602 unsigned BPReg = RegInfo->getBaseRegister(MF);
603 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
604 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
605 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
606 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
607 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
608 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
610 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
612 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
614 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
616 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
618 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
620 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
622 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
624 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
627 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
628 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
629 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
630 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
631 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
632 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
634 int LROffset = getReturnSaveOffset();
639 MachineFrameInfo *FFI = MF.getFrameInfo();
640 int FPIndex = FI->getFramePointerSaveIndex();
641 assert(FPIndex && "No Frame Pointer Save Slot!");
642 FPOffset = FFI->getObjectOffset(FPIndex);
644 FPOffset = getFramePointerSaveOffset();
651 MachineFrameInfo *FFI = MF.getFrameInfo();
652 int BPIndex = FI->getBasePointerSaveIndex();
653 assert(BPIndex && "No Base Pointer Save Slot!");
654 BPOffset = FFI->getObjectOffset(BPIndex);
657 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
664 if (FI->usesPICBase()) {
665 MachineFrameInfo *FFI = MF.getFrameInfo();
666 int PBPIndex = FI->getPICBasePointerSaveIndex();
667 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
668 PBPOffset = FFI->getObjectOffset(PBPIndex);
671 // Get stack alignments.
672 unsigned MaxAlign = MFI->getMaxAlignment();
673 if (HasBP && MaxAlign > 1)
674 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
675 "Invalid alignment!");
677 // Frames of 32KB & larger require special handling because they cannot be
678 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
679 bool isLargeFrame = !isInt<16>(NegFrameSize);
682 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
684 assert((isPPC64 || MustSaveCRs.empty()) &&
685 "Prologue CR saving supported only in 64-bit mode");
687 if (!MustSaveCRs.empty()) { // will only occur for PPC64
688 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
689 // If only one or two CR fields are clobbered, it could be more
690 // efficient to use mfocrf to selectively save just those fields.
691 MachineInstrBuilder MIB =
692 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
693 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
694 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
698 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
699 BuildMI(MBB, MBBI, dl, StoreInst)
704 if (FI->usesPICBase())
705 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
706 BuildMI(MBB, MBBI, dl, StoreInst)
712 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
713 BuildMI(MBB, MBBI, dl, StoreInst)
719 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
720 BuildMI(MBB, MBBI, dl, StoreInst)
725 if (!MustSaveCRs.empty()) // will only occur for PPC64
726 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
727 .addReg(TempReg, getKillRegState(true))
731 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
732 if (!FrameSize) return;
734 // Adjust stack pointer: r1 += NegFrameSize.
735 // If there is a preferred stack alignment, align R1 now
738 // Save a copy of r1 as the base pointer.
739 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
744 if (HasBP && MaxAlign > 1) {
746 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
749 .addImm(64 - Log2_32(MaxAlign));
751 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
754 .addImm(32 - Log2_32(MaxAlign))
757 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
758 .addReg(ScratchReg, RegState::Kill)
759 .addImm(NegFrameSize);
761 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
762 .addImm(NegFrameSize >> 16);
763 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
764 .addReg(TempReg, RegState::Kill)
765 .addImm(NegFrameSize & 0xFFFF);
766 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
767 .addReg(ScratchReg, RegState::Kill)
768 .addReg(TempReg, RegState::Kill);
770 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
771 .addReg(SPReg, RegState::Kill)
775 } else if (!isLargeFrame) {
776 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
778 .addImm(NegFrameSize)
782 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
783 .addImm(NegFrameSize >> 16);
784 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
785 .addReg(ScratchReg, RegState::Kill)
786 .addImm(NegFrameSize & 0xFFFF);
787 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
788 .addReg(SPReg, RegState::Kill)
793 // Add Call Frame Information for the instructions we generated above.
798 // Define CFA in terms of BP. Do this in preference to using FP/SP,
799 // because if the stack needed aligning then CFA won't be at a fixed
800 // offset from FP/SP.
801 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
802 CFIIndex = MMI.addFrameInst(
803 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
805 // Adjust the definition of CFA to account for the change in SP.
806 assert(NegFrameSize);
807 CFIIndex = MMI.addFrameInst(
808 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
810 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
811 .addCFIIndex(CFIIndex);
814 // Describe where FP was saved, at a fixed offset from CFA.
815 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
816 CFIIndex = MMI.addFrameInst(
817 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
818 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
819 .addCFIIndex(CFIIndex);
822 if (FI->usesPICBase()) {
823 // Describe where FP was saved, at a fixed offset from CFA.
824 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
825 CFIIndex = MMI.addFrameInst(
826 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
827 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
828 .addCFIIndex(CFIIndex);
832 // Describe where BP was saved, at a fixed offset from CFA.
833 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
834 CFIIndex = MMI.addFrameInst(
835 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
836 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
837 .addCFIIndex(CFIIndex);
841 // Describe where LR was saved, at a fixed offset from CFA.
842 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
843 CFIIndex = MMI.addFrameInst(
844 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
845 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
846 .addCFIIndex(CFIIndex);
850 // If there is a frame pointer, copy R1 into R31
852 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
856 if (!HasBP && needsCFI) {
857 // Change the definition of CFA from SP+offset to FP+offset, because SP
858 // will change at every alloca.
859 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
860 unsigned CFIIndex = MMI.addFrameInst(
861 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
863 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
864 .addCFIIndex(CFIIndex);
869 // Describe where callee saved registers were saved, at fixed offsets from
871 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
872 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
873 unsigned Reg = CSI[I].getReg();
874 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
876 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
877 // subregisters of CR2. We just need to emit a move of CR2.
878 if (PPC::CRBITRCRegClass.contains(Reg))
881 // For SVR4, don't emit a move for the CR spill slot if we haven't
883 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
884 && MustSaveCRs.empty())
887 // For 64-bit SVR4 when we have spilled CRs, the spill location
888 // is SP+8, not a frame-relative slot.
889 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
890 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
891 // the whole CR word. In the ELFv2 ABI, every CR that was
892 // actually saved gets its own CFI record.
893 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
894 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
895 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
896 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
897 .addCFIIndex(CFIIndex);
901 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
902 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
903 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
904 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
905 .addCFIIndex(CFIIndex);
910 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
911 MachineBasicBlock &MBB) const {
912 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
913 assert(MBBI != MBB.end() && "Returning block has no terminator");
914 const PPCInstrInfo &TII =
915 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
916 const PPCRegisterInfo *RegInfo =
917 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
919 unsigned RetOpcode = MBBI->getOpcode();
922 assert((RetOpcode == PPC::BLR ||
923 RetOpcode == PPC::BLR8 ||
924 RetOpcode == PPC::TCRETURNri ||
925 RetOpcode == PPC::TCRETURNdi ||
926 RetOpcode == PPC::TCRETURNai ||
927 RetOpcode == PPC::TCRETURNri8 ||
928 RetOpcode == PPC::TCRETURNdi8 ||
929 RetOpcode == PPC::TCRETURNai8) &&
930 "Can only insert epilog into returning blocks");
932 // Get alignment info so we know how to restore the SP.
933 const MachineFrameInfo *MFI = MF.getFrameInfo();
935 // Get the number of bytes allocated from the FrameInfo.
936 int FrameSize = MFI->getStackSize();
938 // Get processor type.
939 bool isPPC64 = Subtarget.isPPC64();
941 bool isDarwinABI = Subtarget.isDarwinABI();
942 bool isSVR4ABI = Subtarget.isSVR4ABI();
943 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
945 // Check if the link register (LR) has been saved.
946 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
947 bool MustSaveLR = FI->mustSaveLR();
948 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
949 // Do we have a frame pointer and/or base pointer for this function?
950 bool HasFP = hasFP(MF);
951 bool HasBP = RegInfo->hasBasePointer(MF);
953 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
954 unsigned BPReg = RegInfo->getBaseRegister(MF);
955 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
956 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
957 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
958 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
960 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
962 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
964 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
966 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
968 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
971 int LROffset = getReturnSaveOffset();
976 MachineFrameInfo *FFI = MF.getFrameInfo();
977 int FPIndex = FI->getFramePointerSaveIndex();
978 assert(FPIndex && "No Frame Pointer Save Slot!");
979 FPOffset = FFI->getObjectOffset(FPIndex);
981 FPOffset = getFramePointerSaveOffset();
988 MachineFrameInfo *FFI = MF.getFrameInfo();
989 int BPIndex = FI->getBasePointerSaveIndex();
990 assert(BPIndex && "No Base Pointer Save Slot!");
991 BPOffset = FFI->getObjectOffset(BPIndex);
994 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
1001 if (FI->usesPICBase()) {
1002 MachineFrameInfo *FFI = MF.getFrameInfo();
1003 int PBPIndex = FI->getPICBasePointerSaveIndex();
1004 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1005 PBPOffset = FFI->getObjectOffset(PBPIndex);
1008 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
1009 RetOpcode == PPC::TCRETURNdi ||
1010 RetOpcode == PPC::TCRETURNai ||
1011 RetOpcode == PPC::TCRETURNri8 ||
1012 RetOpcode == PPC::TCRETURNdi8 ||
1013 RetOpcode == PPC::TCRETURNai8;
1016 int MaxTCRetDelta = FI->getTailCallSPDelta();
1017 MachineOperand &StackAdjust = MBBI->getOperand(1);
1018 assert(StackAdjust.isImm() && "Expecting immediate value.");
1019 // Adjust stack pointer.
1020 int StackAdj = StackAdjust.getImm();
1021 int Delta = StackAdj - MaxTCRetDelta;
1022 assert((Delta >= 0) && "Delta must be positive");
1023 if (MaxTCRetDelta>0)
1024 FrameSize += (StackAdj +Delta);
1026 FrameSize += StackAdj;
1029 // Frames of 32KB & larger require special handling because they cannot be
1030 // indexed into with a simple LD/LWZ immediate offset operand.
1031 bool isLargeFrame = !isInt<16>(FrameSize);
1034 // In the prologue, the loaded (or persistent) stack pointer value is offset
1035 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
1037 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1038 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1039 // call which invalidates the stack pointer value in SP(0). So we use the
1040 // value of R31 in this case.
1041 if (FI->hasFastCall()) {
1042 assert(HasFP && "Expecting a valid frame pointer.");
1043 if (!isLargeFrame) {
1044 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1045 .addReg(FPReg).addImm(FrameSize);
1047 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1048 .addImm(FrameSize >> 16);
1049 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1050 .addReg(ScratchReg, RegState::Kill)
1051 .addImm(FrameSize & 0xFFFF);
1052 BuildMI(MBB, MBBI, dl, AddInst)
1055 .addReg(ScratchReg);
1057 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1058 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1062 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1070 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1074 assert((isPPC64 || MustSaveCRs.empty()) &&
1075 "Epilogue CR restoring supported only in 64-bit mode");
1077 if (!MustSaveCRs.empty()) // will only occur for PPC64
1078 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1083 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1087 if (FI->usesPICBase())
1088 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1089 BuildMI(MBB, MBBI, dl, LoadInst)
1095 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1099 if (!MustSaveCRs.empty()) // will only occur for PPC64
1100 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1101 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1102 .addReg(TempReg, getKillRegState(i == e-1));
1105 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1107 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1108 // call optimization
1109 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1110 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1111 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1112 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1113 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1115 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1116 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1117 .addReg(SPReg).addImm(CallerAllocatedAmt);
1119 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1120 .addImm(CallerAllocatedAmt >> 16);
1121 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1122 .addReg(ScratchReg, RegState::Kill)
1123 .addImm(CallerAllocatedAmt & 0xFFFF);
1124 BuildMI(MBB, MBBI, dl, AddInst)
1127 .addReg(ScratchReg);
1129 } else if (RetOpcode == PPC::TCRETURNdi) {
1130 MBBI = MBB.getLastNonDebugInstr();
1131 MachineOperand &JumpTarget = MBBI->getOperand(0);
1132 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1133 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1134 } else if (RetOpcode == PPC::TCRETURNri) {
1135 MBBI = MBB.getLastNonDebugInstr();
1136 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1137 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1138 } else if (RetOpcode == PPC::TCRETURNai) {
1139 MBBI = MBB.getLastNonDebugInstr();
1140 MachineOperand &JumpTarget = MBBI->getOperand(0);
1141 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1142 } else if (RetOpcode == PPC::TCRETURNdi8) {
1143 MBBI = MBB.getLastNonDebugInstr();
1144 MachineOperand &JumpTarget = MBBI->getOperand(0);
1145 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1146 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1147 } else if (RetOpcode == PPC::TCRETURNri8) {
1148 MBBI = MBB.getLastNonDebugInstr();
1149 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1150 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1151 } else if (RetOpcode == PPC::TCRETURNai8) {
1152 MBBI = MBB.getLastNonDebugInstr();
1153 MachineOperand &JumpTarget = MBBI->getOperand(0);
1154 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1159 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1160 RegScavenger *) const {
1161 const PPCRegisterInfo *RegInfo =
1162 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1164 // Save and clear the LR state.
1165 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1166 unsigned LR = RegInfo->getRARegister();
1167 FI->setMustSaveLR(MustSaveLR(MF, LR));
1168 MachineRegisterInfo &MRI = MF.getRegInfo();
1169 MRI.setPhysRegUnused(LR);
1171 // Save R31 if necessary
1172 int FPSI = FI->getFramePointerSaveIndex();
1173 bool isPPC64 = Subtarget.isPPC64();
1174 bool isDarwinABI = Subtarget.isDarwinABI();
1175 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1176 MachineFrameInfo *MFI = MF.getFrameInfo();
1178 // If the frame pointer save index hasn't been defined yet.
1179 if (!FPSI && needsFP(MF)) {
1180 // Find out what the fix offset of the frame pointer save area.
1181 int FPOffset = getFramePointerSaveOffset();
1182 // Allocate the frame index for frame pointer save area.
1183 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1185 FI->setFramePointerSaveIndex(FPSI);
1188 int BPSI = FI->getBasePointerSaveIndex();
1189 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1190 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1191 // Allocate the frame index for the base pointer save area.
1192 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1194 FI->setBasePointerSaveIndex(BPSI);
1197 // Reserve stack space for the PIC Base register (R30).
1198 // Only used in SVR4 32-bit.
1199 if (FI->usesPICBase()) {
1200 int PBPSI = FI->getPICBasePointerSaveIndex();
1201 PBPSI = MFI->CreateFixedObject(4, -8, true);
1202 FI->setPICBasePointerSaveIndex(PBPSI);
1205 // Reserve stack space to move the linkage area to in case of a tail call.
1207 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1208 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1209 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1212 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1213 // function uses CR 2, 3, or 4.
1214 if (!isPPC64 && !isDarwinABI &&
1215 (MRI.isPhysRegUsed(PPC::CR2) ||
1216 MRI.isPhysRegUsed(PPC::CR3) ||
1217 MRI.isPhysRegUsed(PPC::CR4))) {
1218 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1219 FI->setCRSpillFrameIndex(FrameIdx);
1223 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1224 RegScavenger *RS) const {
1225 // Early exit if not using the SVR4 ABI.
1226 if (!Subtarget.isSVR4ABI()) {
1227 addScavengingSpillSlot(MF, RS);
1231 // Get callee saved register information.
1232 MachineFrameInfo *FFI = MF.getFrameInfo();
1233 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1235 // Early exit if no callee saved registers are modified!
1236 if (CSI.empty() && !needsFP(MF)) {
1237 addScavengingSpillSlot(MF, RS);
1241 unsigned MinGPR = PPC::R31;
1242 unsigned MinG8R = PPC::X31;
1243 unsigned MinFPR = PPC::F31;
1244 unsigned MinVR = PPC::V31;
1246 bool HasGPSaveArea = false;
1247 bool HasG8SaveArea = false;
1248 bool HasFPSaveArea = false;
1249 bool HasVRSAVESaveArea = false;
1250 bool HasVRSaveArea = false;
1252 SmallVector<CalleeSavedInfo, 18> GPRegs;
1253 SmallVector<CalleeSavedInfo, 18> G8Regs;
1254 SmallVector<CalleeSavedInfo, 18> FPRegs;
1255 SmallVector<CalleeSavedInfo, 18> VRegs;
1257 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1258 unsigned Reg = CSI[i].getReg();
1259 if (PPC::GPRCRegClass.contains(Reg)) {
1260 HasGPSaveArea = true;
1262 GPRegs.push_back(CSI[i]);
1267 } else if (PPC::G8RCRegClass.contains(Reg)) {
1268 HasG8SaveArea = true;
1270 G8Regs.push_back(CSI[i]);
1275 } else if (PPC::F8RCRegClass.contains(Reg)) {
1276 HasFPSaveArea = true;
1278 FPRegs.push_back(CSI[i]);
1283 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1284 PPC::CRRCRegClass.contains(Reg)) {
1285 ; // do nothing, as we already know whether CRs are spilled
1286 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1287 HasVRSAVESaveArea = true;
1288 } else if (PPC::VRRCRegClass.contains(Reg)) {
1289 HasVRSaveArea = true;
1291 VRegs.push_back(CSI[i]);
1297 llvm_unreachable("Unknown RegisterClass!");
1301 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1302 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1304 int64_t LowerBound = 0;
1306 // Take into account stack space reserved for tail calls.
1308 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1309 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1310 LowerBound = TCSPDelta;
1313 // The Floating-point register save area is right below the back chain word
1314 // of the previous stack frame.
1315 if (HasFPSaveArea) {
1316 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1317 int FI = FPRegs[i].getFrameIdx();
1319 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1322 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1325 // Check whether the frame pointer register is allocated. If so, make sure it
1326 // is spilled to the correct offset.
1328 HasGPSaveArea = true;
1330 int FI = PFI->getFramePointerSaveIndex();
1331 assert(FI && "No Frame Pointer Save Slot!");
1333 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1336 if (PFI->usesPICBase()) {
1337 HasGPSaveArea = true;
1339 int FI = PFI->getPICBasePointerSaveIndex();
1340 assert(FI && "No PIC Base Pointer Save Slot!");
1342 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1345 const PPCRegisterInfo *RegInfo =
1346 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1347 if (RegInfo->hasBasePointer(MF)) {
1348 HasGPSaveArea = true;
1350 int FI = PFI->getBasePointerSaveIndex();
1351 assert(FI && "No Base Pointer Save Slot!");
1353 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1356 // General register save area starts right below the Floating-point
1357 // register save area.
1358 if (HasGPSaveArea || HasG8SaveArea) {
1359 // Move general register save area spill slots down, taking into account
1360 // the size of the Floating-point register save area.
1361 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1362 int FI = GPRegs[i].getFrameIdx();
1364 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1367 // Move general register save area spill slots down, taking into account
1368 // the size of the Floating-point register save area.
1369 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1370 int FI = G8Regs[i].getFrameIdx();
1372 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1376 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1377 TRI->getEncodingValue(MinG8R));
1379 if (Subtarget.isPPC64()) {
1380 LowerBound -= (31 - MinReg + 1) * 8;
1382 LowerBound -= (31 - MinReg + 1) * 4;
1386 // For 32-bit only, the CR save area is below the general register
1387 // save area. For 64-bit SVR4, the CR save area is addressed relative
1388 // to the stack pointer and hence does not need an adjustment here.
1389 // Only CR2 (the first nonvolatile spilled) has an associated frame
1390 // index so that we have a single uniform save area.
1391 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1392 // Adjust the frame index of the CR spill slot.
1393 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1394 unsigned Reg = CSI[i].getReg();
1396 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1397 // Leave Darwin logic as-is.
1398 || (!Subtarget.isSVR4ABI() &&
1399 (PPC::CRBITRCRegClass.contains(Reg) ||
1400 PPC::CRRCRegClass.contains(Reg)))) {
1401 int FI = CSI[i].getFrameIdx();
1403 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1407 LowerBound -= 4; // The CR save area is always 4 bytes long.
1410 if (HasVRSAVESaveArea) {
1411 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1412 // which have the VRSAVE register class?
1413 // Adjust the frame index of the VRSAVE spill slot.
1414 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1415 unsigned Reg = CSI[i].getReg();
1417 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1418 int FI = CSI[i].getFrameIdx();
1420 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1424 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1427 if (HasVRSaveArea) {
1428 // Insert alignment padding, we need 16-byte alignment.
1429 LowerBound = (LowerBound - 15) & ~(15);
1431 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1432 int FI = VRegs[i].getFrameIdx();
1434 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1438 addScavengingSpillSlot(MF, RS);
1442 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1443 RegScavenger *RS) const {
1444 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1445 // a large stack, which will require scavenging a register to materialize a
1448 // We need to have a scavenger spill slot for spills if the frame size is
1449 // large. In case there is no free register for large-offset addressing,
1450 // this slot is used for the necessary emergency spill. Also, we need the
1451 // slot for dynamic stack allocations.
1453 // The scavenger might be invoked if the frame offset does not fit into
1454 // the 16-bit immediate. We don't know the complete frame size here
1455 // because we've not yet computed callee-saved register spills or the
1456 // needed alignment padding.
1457 unsigned StackSize = determineFrameLayout(MF, false, true);
1458 MachineFrameInfo *MFI = MF.getFrameInfo();
1459 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1460 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1461 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1462 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1463 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1464 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1468 // Might we have over-aligned allocas?
1469 bool HasAlVars = MFI->hasVarSizedObjects() &&
1470 MFI->getMaxAlignment() > getStackAlignment();
1472 // These kinds of spills might need two registers.
1473 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1474 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1482 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1483 MachineBasicBlock::iterator MI,
1484 const std::vector<CalleeSavedInfo> &CSI,
1485 const TargetRegisterInfo *TRI) const {
1487 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1488 // Return false otherwise to maintain pre-existing behavior.
1489 if (!Subtarget.isSVR4ABI())
1492 MachineFunction *MF = MBB.getParent();
1493 const PPCInstrInfo &TII =
1494 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1496 bool CRSpilled = false;
1497 MachineInstrBuilder CRMIB;
1499 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1500 unsigned Reg = CSI[i].getReg();
1501 // Only Darwin actually uses the VRSAVE register, but it can still appear
1502 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1503 // Darwin, ignore it.
1504 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1507 // CR2 through CR4 are the nonvolatile CR fields.
1508 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1510 // Add the callee-saved register as live-in; it's killed at the spill.
1513 if (CRSpilled && IsCRField) {
1514 CRMIB.addReg(Reg, RegState::ImplicitKill);
1518 // Insert the spill to the stack frame.
1520 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1521 if (Subtarget.isPPC64()) {
1522 // The actual spill will happen at the start of the prologue.
1523 FuncInfo->addMustSaveCR(Reg);
1526 FuncInfo->setSpillsCR();
1528 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1529 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1530 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1531 .addReg(Reg, RegState::ImplicitKill);
1533 MBB.insert(MI, CRMIB);
1534 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1536 getKillRegState(true)),
1537 CSI[i].getFrameIdx()));
1540 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1541 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1542 CSI[i].getFrameIdx(), RC, TRI);
1549 restoreCRs(bool isPPC64, bool is31,
1550 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1551 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1552 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1554 MachineFunction *MF = MBB.getParent();
1555 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1557 unsigned RestoreOp, MoveReg;
1560 // This is handled during epilogue generation.
1563 // 32-bit: FP-relative
1564 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1566 CSI[CSIIndex].getFrameIdx()));
1567 RestoreOp = PPC::MTOCRF;
1572 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1573 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1576 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1577 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1580 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1581 .addReg(MoveReg, getKillRegState(true)));
1584 void PPCFrameLowering::
1585 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1586 MachineBasicBlock::iterator I) const {
1587 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1588 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1589 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1590 // Add (actually subtract) back the amount the callee popped on return.
1591 if (int CalleeAmt = I->getOperand(1).getImm()) {
1592 bool is64Bit = Subtarget.isPPC64();
1594 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1595 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1596 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1597 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1598 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1599 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1600 MachineInstr *MI = I;
1601 DebugLoc dl = MI->getDebugLoc();
1603 if (isInt<16>(CalleeAmt)) {
1604 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1605 .addReg(StackReg, RegState::Kill)
1608 MachineBasicBlock::iterator MBBI = I;
1609 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1610 .addImm(CalleeAmt >> 16);
1611 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1612 .addReg(TmpReg, RegState::Kill)
1613 .addImm(CalleeAmt & 0xFFFF);
1614 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1615 .addReg(StackReg, RegState::Kill)
1620 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1625 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1626 MachineBasicBlock::iterator MI,
1627 const std::vector<CalleeSavedInfo> &CSI,
1628 const TargetRegisterInfo *TRI) const {
1630 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1631 // Return false otherwise to maintain pre-existing behavior.
1632 if (!Subtarget.isSVR4ABI())
1635 MachineFunction *MF = MBB.getParent();
1636 const PPCInstrInfo &TII =
1637 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1638 bool CR2Spilled = false;
1639 bool CR3Spilled = false;
1640 bool CR4Spilled = false;
1641 unsigned CSIIndex = 0;
1643 // Initialize insertion-point logic; we will be restoring in reverse
1645 MachineBasicBlock::iterator I = MI, BeforeI = I;
1646 bool AtStart = I == MBB.begin();
1651 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1652 unsigned Reg = CSI[i].getReg();
1654 // Only Darwin actually uses the VRSAVE register, but it can still appear
1655 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1656 // Darwin, ignore it.
1657 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1660 if (Reg == PPC::CR2) {
1662 // The spill slot is associated only with CR2, which is the
1663 // first nonvolatile spilled. Save it here.
1666 } else if (Reg == PPC::CR3) {
1669 } else if (Reg == PPC::CR4) {
1673 // When we first encounter a non-CR register after seeing at
1674 // least one CR register, restore all spilled CRs together.
1675 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1676 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1677 bool is31 = needsFP(*MF);
1678 restoreCRs(Subtarget.isPPC64(), is31,
1679 CR2Spilled, CR3Spilled, CR4Spilled,
1680 MBB, I, CSI, CSIIndex);
1681 CR2Spilled = CR3Spilled = CR4Spilled = false;
1684 // Default behavior for non-CR saves.
1685 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1686 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1688 assert(I != MBB.begin() &&
1689 "loadRegFromStackSlot didn't insert any code!");
1692 // Insert in reverse order.
1701 // If we haven't yet spilled the CRs, do so now.
1702 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1703 bool is31 = needsFP(*MF);
1704 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1705 MBB, I, CSI, CSIIndex);