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 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
45 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
46 unsigned &NumEntries) const {
47 if (Subtarget.isDarwinABI()) {
49 if (Subtarget.isPPC64()) {
50 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
51 return &darwin64Offsets;
53 static const SpillSlot darwinOffsets = {PPC::R31, -4};
54 return &darwinOffsets;
58 // Early exit if not using the SVR4 ABI.
59 if (!Subtarget.isSVR4ABI()) {
64 // Note that the offsets here overlap, but this is fixed up in
65 // processFunctionBeforeFrameFinalized.
67 static const SpillSlot Offsets[] = {
68 // Floating-point register save area offsets.
88 // General register save area offsets.
108 // CR save area offset. We map each of the nonvolatile CR fields
109 // to the slot for CR2, which is the first of the nonvolatile CR
110 // fields to be assigned, so that we only allocate one save slot.
111 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
114 // VRSAVE save area offset.
117 // Vector register save area
131 static const SpillSlot Offsets64[] = {
132 // Floating-point register save area offsets.
152 // General register save area offsets.
172 // VRSAVE save area offset.
175 // Vector register save area
189 if (Subtarget.isPPC64()) {
190 NumEntries = array_lengthof(Offsets64);
194 NumEntries = array_lengthof(Offsets);
200 /// RemoveVRSaveCode - We have found that this function does not need any code
201 /// to manipulate the VRSAVE register, even though it uses vector registers.
202 /// This can happen when the only registers used are known to be live in or out
203 /// of the function. Remove all of the VRSAVE related code from the function.
204 /// FIXME: The removal of the code results in a compile failure at -O0 when the
205 /// function contains a function call, as the GPR containing original VRSAVE
206 /// contents is spilled and reloaded around the call. Without the prolog code,
207 /// the spill instruction refers to an undefined register. This code needs
208 /// to account for all uses of that GPR.
209 static void RemoveVRSaveCode(MachineInstr *MI) {
210 MachineBasicBlock *Entry = MI->getParent();
211 MachineFunction *MF = Entry->getParent();
213 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
214 MachineBasicBlock::iterator MBBI = MI;
216 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
217 MBBI->eraseFromParent();
219 bool RemovedAllMTVRSAVEs = true;
220 // See if we can find and remove the MTVRSAVE instruction from all of the
222 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
223 // If last instruction is a return instruction, add an epilogue
224 if (!I->empty() && I->back().isReturn()) {
225 bool FoundIt = false;
226 for (MBBI = I->end(); MBBI != I->begin(); ) {
228 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
229 MBBI->eraseFromParent(); // remove it.
234 RemovedAllMTVRSAVEs &= FoundIt;
238 // If we found and removed all MTVRSAVE instructions, remove the read of
240 if (RemovedAllMTVRSAVEs) {
242 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
244 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
245 MBBI->eraseFromParent();
248 // Finally, nuke the UPDATE_VRSAVE.
249 MI->eraseFromParent();
252 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
253 // instruction selector. Based on the vector registers that have been used,
254 // transform this into the appropriate ORI instruction.
255 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
256 MachineFunction *MF = MI->getParent()->getParent();
257 const TargetRegisterInfo *TRI =
258 MF->getTarget().getSubtargetImpl()->getRegisterInfo();
259 DebugLoc dl = MI->getDebugLoc();
261 unsigned UsedRegMask = 0;
262 for (unsigned i = 0; i != 32; ++i)
263 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
264 UsedRegMask |= 1 << (31-i);
266 // Live in and live out values already must be in the mask, so don't bother
268 for (MachineRegisterInfo::livein_iterator
269 I = MF->getRegInfo().livein_begin(),
270 E = MF->getRegInfo().livein_end(); I != E; ++I) {
271 unsigned RegNo = TRI->getEncodingValue(I->first);
272 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
273 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
276 // Live out registers appear as use operands on return instructions.
277 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
278 UsedRegMask != 0 && BI != BE; ++BI) {
279 const MachineBasicBlock &MBB = *BI;
280 if (MBB.empty() || !MBB.back().isReturn())
282 const MachineInstr &Ret = MBB.back();
283 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
284 const MachineOperand &MO = Ret.getOperand(I);
285 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
287 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
288 UsedRegMask &= ~(1 << (31-RegNo));
292 // If no registers are used, turn this into a copy.
293 if (UsedRegMask == 0) {
294 // Remove all VRSAVE code.
295 RemoveVRSaveCode(MI);
299 unsigned SrcReg = MI->getOperand(1).getReg();
300 unsigned DstReg = MI->getOperand(0).getReg();
302 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
303 if (DstReg != SrcReg)
304 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
306 .addImm(UsedRegMask);
308 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
309 .addReg(SrcReg, RegState::Kill)
310 .addImm(UsedRegMask);
311 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
312 if (DstReg != SrcReg)
313 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
315 .addImm(UsedRegMask >> 16);
317 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
318 .addReg(SrcReg, RegState::Kill)
319 .addImm(UsedRegMask >> 16);
321 if (DstReg != SrcReg)
322 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
324 .addImm(UsedRegMask >> 16);
326 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
327 .addReg(SrcReg, RegState::Kill)
328 .addImm(UsedRegMask >> 16);
330 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
331 .addReg(DstReg, RegState::Kill)
332 .addImm(UsedRegMask & 0xFFFF);
335 // Remove the old UPDATE_VRSAVE instruction.
336 MI->eraseFromParent();
339 static bool spillsCR(const MachineFunction &MF) {
340 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
341 return FuncInfo->isCRSpilled();
344 static bool spillsVRSAVE(const MachineFunction &MF) {
345 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
346 return FuncInfo->isVRSAVESpilled();
349 static bool hasSpills(const MachineFunction &MF) {
350 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
351 return FuncInfo->hasSpills();
354 static bool hasNonRISpills(const MachineFunction &MF) {
355 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
356 return FuncInfo->hasNonRISpills();
359 /// determineFrameLayout - Determine the size of the frame and maximum call
361 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
363 bool UseEstimate) const {
364 MachineFrameInfo *MFI = MF.getFrameInfo();
366 // Get the number of bytes to allocate from the FrameInfo
368 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
370 // Get stack alignments. The frame must be aligned to the greatest of these:
371 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
372 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
373 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
375 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
376 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
378 // If we are a leaf function, and use up to 224 bytes of stack space,
379 // don't have a frame pointer, calls, or dynamic alloca then we do not need
380 // to adjust the stack pointer (we fit in the Red Zone).
381 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
382 // stackless code if all local vars are reg-allocated.
383 bool DisableRedZone = MF.getFunction()->getAttributes().
384 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
385 if (!DisableRedZone &&
386 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
387 !Subtarget.isSVR4ABI() || // allocated locals.
389 FrameSize <= 224 && // Fits in red zone.
390 !MFI->hasVarSizedObjects() && // No dynamic alloca.
391 !MFI->adjustsStack() && // No calls.
392 !RegInfo->hasBasePointer(MF)) { // No special alignment.
395 MFI->setStackSize(0);
399 // Get the maximum call frame size of all the calls.
400 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
402 // Maximum call frame needs to be at least big enough for linkage area.
403 unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
404 Subtarget.isDarwinABI(),
405 Subtarget.isELFv2ABI());
406 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
408 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
409 // that allocations will be aligned.
410 if (MFI->hasVarSizedObjects())
411 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
413 // Update maximum call frame size.
415 MFI->setMaxCallFrameSize(maxCallFrameSize);
417 // Include call frame size in total.
418 FrameSize += maxCallFrameSize;
420 // Make sure the frame is aligned.
421 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
423 // Update frame info.
425 MFI->setStackSize(FrameSize);
430 // hasFP - Return true if the specified function actually has a dedicated frame
432 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
433 const MachineFrameInfo *MFI = MF.getFrameInfo();
434 // FIXME: This is pretty much broken by design: hasFP() might be called really
435 // early, before the stack layout was calculated and thus hasFP() might return
436 // true or false here depending on the time of call.
437 return (MFI->getStackSize()) && needsFP(MF);
440 // needsFP - Return true if the specified function should have a dedicated frame
441 // pointer register. This is true if the function has variable sized allocas or
442 // if frame pointer elimination is disabled.
443 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
444 const MachineFrameInfo *MFI = MF.getFrameInfo();
446 // Naked functions have no stack frame pushed, so we don't have a frame
448 if (MF.getFunction()->getAttributes().hasAttribute(
449 AttributeSet::FunctionIndex, Attribute::Naked))
452 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
453 MFI->hasVarSizedObjects() ||
454 (MF.getTarget().Options.GuaranteedTailCallOpt &&
455 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
458 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
459 bool is31 = needsFP(MF);
460 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
461 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
463 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
464 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
465 bool HasBP = RegInfo->hasBasePointer(MF);
466 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
467 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
469 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
471 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
473 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
474 MachineOperand &MO = MBBI->getOperand(I);
478 switch (MO.getReg()) {
497 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
498 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
499 MachineBasicBlock::iterator MBBI = MBB.begin();
500 MachineFrameInfo *MFI = MF.getFrameInfo();
501 const PPCInstrInfo &TII =
502 *static_cast<const PPCInstrInfo *>(
503 MF.getTarget().getSubtargetImpl()->getInstrInfo());
504 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
505 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
507 MachineModuleInfo &MMI = MF.getMMI();
508 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
510 bool needsFrameMoves = MMI.hasDebugInfo() ||
511 MF.getFunction()->needsUnwindTableEntry();
512 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
514 // Get processor type.
515 bool isPPC64 = Subtarget.isPPC64();
517 bool isDarwinABI = Subtarget.isDarwinABI();
518 bool isSVR4ABI = Subtarget.isSVR4ABI();
519 bool isELFv2ABI = Subtarget.isELFv2ABI();
520 assert((isDarwinABI || isSVR4ABI) &&
521 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
523 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
526 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
527 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
528 HandleVRSaveUpdate(MBBI, TII);
533 // Move MBBI back to the beginning of the function.
536 // Work out frame sizes.
537 unsigned FrameSize = determineFrameLayout(MF);
538 int NegFrameSize = -FrameSize;
539 if (!isInt<32>(NegFrameSize))
540 llvm_unreachable("Unhandled stack size!");
542 if (MFI->isFrameAddressTaken())
543 replaceFPWithRealFP(MF);
545 // Check if the link register (LR) must be saved.
546 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
547 bool MustSaveLR = FI->mustSaveLR();
548 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
549 // Do we have a frame pointer and/or base pointer for this function?
550 bool HasFP = hasFP(MF);
551 bool HasBP = RegInfo->hasBasePointer(MF);
553 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
554 unsigned BPReg = RegInfo->getBaseRegister(MF);
555 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
556 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
557 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
558 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
559 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
560 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
562 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
564 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
566 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
568 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
570 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
572 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
574 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
576 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
579 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
580 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
581 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
582 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
583 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
584 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
586 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
591 MachineFrameInfo *FFI = MF.getFrameInfo();
592 int FPIndex = FI->getFramePointerSaveIndex();
593 assert(FPIndex && "No Frame Pointer Save Slot!");
594 FPOffset = FFI->getObjectOffset(FPIndex);
597 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
604 MachineFrameInfo *FFI = MF.getFrameInfo();
605 int BPIndex = FI->getBasePointerSaveIndex();
606 assert(BPIndex && "No Base Pointer Save Slot!");
607 BPOffset = FFI->getObjectOffset(BPIndex);
610 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
616 // Get stack alignments.
617 unsigned MaxAlign = MFI->getMaxAlignment();
618 if (HasBP && MaxAlign > 1)
619 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
620 "Invalid alignment!");
622 // Frames of 32KB & larger require special handling because they cannot be
623 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
624 bool isLargeFrame = !isInt<16>(NegFrameSize);
627 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
629 assert((isPPC64 || MustSaveCRs.empty()) &&
630 "Prologue CR saving supported only in 64-bit mode");
632 if (!MustSaveCRs.empty()) { // will only occur for PPC64
633 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
634 // If only one or two CR fields are clobbered, it could be more
635 // efficient to use mfocrf to selectively save just those fields.
636 MachineInstrBuilder MIB =
637 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
638 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
639 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
643 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
644 BuildMI(MBB, MBBI, dl, StoreInst)
650 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
651 BuildMI(MBB, MBBI, dl, StoreInst)
657 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
658 BuildMI(MBB, MBBI, dl, StoreInst)
663 if (!MustSaveCRs.empty()) // will only occur for PPC64
664 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
665 .addReg(TempReg, getKillRegState(true))
669 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
670 if (!FrameSize) return;
672 // Adjust stack pointer: r1 += NegFrameSize.
673 // If there is a preferred stack alignment, align R1 now
676 // Save a copy of r1 as the base pointer.
677 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
682 if (HasBP && MaxAlign > 1) {
684 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
687 .addImm(64 - Log2_32(MaxAlign));
689 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
692 .addImm(32 - Log2_32(MaxAlign))
695 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
696 .addReg(ScratchReg, RegState::Kill)
697 .addImm(NegFrameSize);
699 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
700 .addImm(NegFrameSize >> 16);
701 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
702 .addReg(TempReg, RegState::Kill)
703 .addImm(NegFrameSize & 0xFFFF);
704 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
705 .addReg(ScratchReg, RegState::Kill)
706 .addReg(TempReg, RegState::Kill);
708 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
709 .addReg(SPReg, RegState::Kill)
713 } else if (!isLargeFrame) {
714 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
716 .addImm(NegFrameSize)
720 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
721 .addImm(NegFrameSize >> 16);
722 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
723 .addReg(ScratchReg, RegState::Kill)
724 .addImm(NegFrameSize & 0xFFFF);
725 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
726 .addReg(SPReg, RegState::Kill)
731 // Add the "machine moves" for the instructions we generated above, but in
733 if (needsFrameMoves) {
734 // Show update of SP.
735 assert(NegFrameSize);
736 unsigned CFIIndex = MMI.addFrameInst(
737 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
738 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
739 .addCFIIndex(CFIIndex);
742 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
743 CFIIndex = MMI.addFrameInst(
744 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
745 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
746 .addCFIIndex(CFIIndex);
750 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
751 CFIIndex = MMI.addFrameInst(
752 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
753 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
754 .addCFIIndex(CFIIndex);
758 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
759 CFIIndex = MMI.addFrameInst(
760 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
761 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
762 .addCFIIndex(CFIIndex);
766 // If there is a frame pointer, copy R1 into R31
768 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
772 if (needsFrameMoves) {
773 // Mark effective beginning of when frame pointer is ready.
774 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
775 unsigned CFIIndex = MMI.addFrameInst(
776 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
778 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
779 .addCFIIndex(CFIIndex);
783 if (needsFrameMoves) {
784 // Add callee saved registers to move list.
785 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
786 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
787 unsigned Reg = CSI[I].getReg();
788 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
790 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
791 // subregisters of CR2. We just need to emit a move of CR2.
792 if (PPC::CRBITRCRegClass.contains(Reg))
795 // For SVR4, don't emit a move for the CR spill slot if we haven't
797 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
798 && MustSaveCRs.empty())
801 // For 64-bit SVR4 when we have spilled CRs, the spill location
802 // is SP+8, not a frame-relative slot.
803 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
804 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
805 // the whole CR word. In the ELFv2 ABI, every CR that was
806 // actually saved gets its own CFI record.
807 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
808 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
809 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
810 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
811 .addCFIIndex(CFIIndex);
815 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
816 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
817 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
818 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
819 .addCFIIndex(CFIIndex);
824 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
825 MachineBasicBlock &MBB) const {
826 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
827 assert(MBBI != MBB.end() && "Returning block has no terminator");
828 const PPCInstrInfo &TII =
829 *static_cast<const PPCInstrInfo *>(
830 MF.getTarget().getSubtargetImpl()->getInstrInfo());
831 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
832 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
834 unsigned RetOpcode = MBBI->getOpcode();
837 assert((RetOpcode == PPC::BLR ||
838 RetOpcode == PPC::TCRETURNri ||
839 RetOpcode == PPC::TCRETURNdi ||
840 RetOpcode == PPC::TCRETURNai ||
841 RetOpcode == PPC::TCRETURNri8 ||
842 RetOpcode == PPC::TCRETURNdi8 ||
843 RetOpcode == PPC::TCRETURNai8) &&
844 "Can only insert epilog into returning blocks");
846 // Get alignment info so we know how to restore the SP.
847 const MachineFrameInfo *MFI = MF.getFrameInfo();
849 // Get the number of bytes allocated from the FrameInfo.
850 int FrameSize = MFI->getStackSize();
852 // Get processor type.
853 bool isPPC64 = Subtarget.isPPC64();
855 bool isDarwinABI = Subtarget.isDarwinABI();
856 bool isSVR4ABI = Subtarget.isSVR4ABI();
857 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
859 // Check if the link register (LR) has been saved.
860 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
861 bool MustSaveLR = FI->mustSaveLR();
862 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
863 // Do we have a frame pointer and/or base pointer for this function?
864 bool HasFP = hasFP(MF);
865 bool HasBP = RegInfo->hasBasePointer(MF);
867 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
868 unsigned BPReg = RegInfo->getBaseRegister(MF);
869 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
870 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
871 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
872 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
874 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
876 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
878 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
880 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
882 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
885 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
890 MachineFrameInfo *FFI = MF.getFrameInfo();
891 int FPIndex = FI->getFramePointerSaveIndex();
892 assert(FPIndex && "No Frame Pointer Save Slot!");
893 FPOffset = FFI->getObjectOffset(FPIndex);
896 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
903 MachineFrameInfo *FFI = MF.getFrameInfo();
904 int BPIndex = FI->getBasePointerSaveIndex();
905 assert(BPIndex && "No Base Pointer Save Slot!");
906 BPOffset = FFI->getObjectOffset(BPIndex);
909 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
915 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
916 RetOpcode == PPC::TCRETURNdi ||
917 RetOpcode == PPC::TCRETURNai ||
918 RetOpcode == PPC::TCRETURNri8 ||
919 RetOpcode == PPC::TCRETURNdi8 ||
920 RetOpcode == PPC::TCRETURNai8;
923 int MaxTCRetDelta = FI->getTailCallSPDelta();
924 MachineOperand &StackAdjust = MBBI->getOperand(1);
925 assert(StackAdjust.isImm() && "Expecting immediate value.");
926 // Adjust stack pointer.
927 int StackAdj = StackAdjust.getImm();
928 int Delta = StackAdj - MaxTCRetDelta;
929 assert((Delta >= 0) && "Delta must be positive");
931 FrameSize += (StackAdj +Delta);
933 FrameSize += StackAdj;
936 // Frames of 32KB & larger require special handling because they cannot be
937 // indexed into with a simple LD/LWZ immediate offset operand.
938 bool isLargeFrame = !isInt<16>(FrameSize);
941 // In the prologue, the loaded (or persistent) stack pointer value is offset
942 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
944 // If this function contained a fastcc call and GuaranteedTailCallOpt is
945 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
946 // call which invalidates the stack pointer value in SP(0). So we use the
947 // value of R31 in this case.
948 if (FI->hasFastCall()) {
949 assert(HasFP && "Expecting a valid frame pointer.");
951 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
952 .addReg(FPReg).addImm(FrameSize);
954 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
955 .addImm(FrameSize >> 16);
956 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
957 .addReg(ScratchReg, RegState::Kill)
958 .addImm(FrameSize & 0xFFFF);
959 BuildMI(MBB, MBBI, dl, AddInst)
964 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
965 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
969 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
977 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
981 assert((isPPC64 || MustSaveCRs.empty()) &&
982 "Epilogue CR restoring supported only in 64-bit mode");
984 if (!MustSaveCRs.empty()) // will only occur for PPC64
985 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
990 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
995 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
999 if (!MustSaveCRs.empty()) // will only occur for PPC64
1000 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1001 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1002 .addReg(TempReg, getKillRegState(i == e-1));
1005 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1007 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1008 // call optimization
1009 if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1010 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1011 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1012 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1014 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1015 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1016 .addReg(SPReg).addImm(CallerAllocatedAmt);
1018 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1019 .addImm(CallerAllocatedAmt >> 16);
1020 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1021 .addReg(ScratchReg, RegState::Kill)
1022 .addImm(CallerAllocatedAmt & 0xFFFF);
1023 BuildMI(MBB, MBBI, dl, AddInst)
1026 .addReg(ScratchReg);
1028 } else if (RetOpcode == PPC::TCRETURNdi) {
1029 MBBI = MBB.getLastNonDebugInstr();
1030 MachineOperand &JumpTarget = MBBI->getOperand(0);
1031 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1032 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1033 } else if (RetOpcode == PPC::TCRETURNri) {
1034 MBBI = MBB.getLastNonDebugInstr();
1035 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1036 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1037 } else if (RetOpcode == PPC::TCRETURNai) {
1038 MBBI = MBB.getLastNonDebugInstr();
1039 MachineOperand &JumpTarget = MBBI->getOperand(0);
1040 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1041 } else if (RetOpcode == PPC::TCRETURNdi8) {
1042 MBBI = MBB.getLastNonDebugInstr();
1043 MachineOperand &JumpTarget = MBBI->getOperand(0);
1044 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1045 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1046 } else if (RetOpcode == PPC::TCRETURNri8) {
1047 MBBI = MBB.getLastNonDebugInstr();
1048 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1049 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1050 } else if (RetOpcode == PPC::TCRETURNai8) {
1051 MBBI = MBB.getLastNonDebugInstr();
1052 MachineOperand &JumpTarget = MBBI->getOperand(0);
1053 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1057 /// MustSaveLR - Return true if this function requires that we save the LR
1058 /// register onto the stack in the prolog and restore it in the epilog of the
1060 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
1061 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
1063 // We need a save/restore of LR if there is any def of LR (which is
1064 // defined by calls, including the PIC setup sequence), or if there is
1065 // some use of the LR stack slot (e.g. for builtin_return_address).
1066 // (LR comes in 32 and 64 bit versions.)
1067 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
1068 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
1072 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1073 RegScavenger *) const {
1074 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
1075 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1077 // Save and clear the LR state.
1078 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1079 unsigned LR = RegInfo->getRARegister();
1080 FI->setMustSaveLR(MustSaveLR(MF, LR));
1081 MachineRegisterInfo &MRI = MF.getRegInfo();
1082 MRI.setPhysRegUnused(LR);
1084 // Save R31 if necessary
1085 int FPSI = FI->getFramePointerSaveIndex();
1086 bool isPPC64 = Subtarget.isPPC64();
1087 bool isDarwinABI = Subtarget.isDarwinABI();
1088 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1089 MachineFrameInfo *MFI = MF.getFrameInfo();
1091 // If the frame pointer save index hasn't been defined yet.
1092 if (!FPSI && needsFP(MF)) {
1093 // Find out what the fix offset of the frame pointer save area.
1094 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1095 // Allocate the frame index for frame pointer save area.
1096 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1098 FI->setFramePointerSaveIndex(FPSI);
1101 int BPSI = FI->getBasePointerSaveIndex();
1102 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1103 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1104 // Allocate the frame index for the base pointer save area.
1105 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1107 FI->setBasePointerSaveIndex(BPSI);
1110 // Reserve stack space to move the linkage area to in case of a tail call.
1112 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1113 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1114 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1117 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1118 // function uses CR 2, 3, or 4.
1119 if (!isPPC64 && !isDarwinABI &&
1120 (MRI.isPhysRegUsed(PPC::CR2) ||
1121 MRI.isPhysRegUsed(PPC::CR3) ||
1122 MRI.isPhysRegUsed(PPC::CR4))) {
1123 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1124 FI->setCRSpillFrameIndex(FrameIdx);
1128 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1129 RegScavenger *RS) const {
1130 // Early exit if not using the SVR4 ABI.
1131 if (!Subtarget.isSVR4ABI()) {
1132 addScavengingSpillSlot(MF, RS);
1136 // Get callee saved register information.
1137 MachineFrameInfo *FFI = MF.getFrameInfo();
1138 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1140 // Early exit if no callee saved registers are modified!
1141 if (CSI.empty() && !needsFP(MF)) {
1142 addScavengingSpillSlot(MF, RS);
1146 unsigned MinGPR = PPC::R31;
1147 unsigned MinG8R = PPC::X31;
1148 unsigned MinFPR = PPC::F31;
1149 unsigned MinVR = PPC::V31;
1151 bool HasGPSaveArea = false;
1152 bool HasG8SaveArea = false;
1153 bool HasFPSaveArea = false;
1154 bool HasVRSAVESaveArea = false;
1155 bool HasVRSaveArea = false;
1157 SmallVector<CalleeSavedInfo, 18> GPRegs;
1158 SmallVector<CalleeSavedInfo, 18> G8Regs;
1159 SmallVector<CalleeSavedInfo, 18> FPRegs;
1160 SmallVector<CalleeSavedInfo, 18> VRegs;
1162 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1163 unsigned Reg = CSI[i].getReg();
1164 if (PPC::GPRCRegClass.contains(Reg)) {
1165 HasGPSaveArea = true;
1167 GPRegs.push_back(CSI[i]);
1172 } else if (PPC::G8RCRegClass.contains(Reg)) {
1173 HasG8SaveArea = true;
1175 G8Regs.push_back(CSI[i]);
1180 } else if (PPC::F8RCRegClass.contains(Reg)) {
1181 HasFPSaveArea = true;
1183 FPRegs.push_back(CSI[i]);
1188 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1189 PPC::CRRCRegClass.contains(Reg)) {
1190 ; // do nothing, as we already know whether CRs are spilled
1191 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1192 HasVRSAVESaveArea = true;
1193 } else if (PPC::VRRCRegClass.contains(Reg)) {
1194 HasVRSaveArea = true;
1196 VRegs.push_back(CSI[i]);
1202 llvm_unreachable("Unknown RegisterClass!");
1206 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1207 const TargetRegisterInfo *TRI =
1208 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
1210 int64_t LowerBound = 0;
1212 // Take into account stack space reserved for tail calls.
1214 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1215 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1216 LowerBound = TCSPDelta;
1219 // The Floating-point register save area is right below the back chain word
1220 // of the previous stack frame.
1221 if (HasFPSaveArea) {
1222 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1223 int FI = FPRegs[i].getFrameIdx();
1225 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1228 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1231 // Check whether the frame pointer register is allocated. If so, make sure it
1232 // is spilled to the correct offset.
1234 HasGPSaveArea = true;
1236 int FI = PFI->getFramePointerSaveIndex();
1237 assert(FI && "No Frame Pointer Save Slot!");
1239 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1242 const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
1243 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1244 if (RegInfo->hasBasePointer(MF)) {
1245 HasGPSaveArea = true;
1247 int FI = PFI->getBasePointerSaveIndex();
1248 assert(FI && "No Base Pointer Save Slot!");
1250 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1253 // General register save area starts right below the Floating-point
1254 // register save area.
1255 if (HasGPSaveArea || HasG8SaveArea) {
1256 // Move general register save area spill slots down, taking into account
1257 // the size of the Floating-point register save area.
1258 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1259 int FI = GPRegs[i].getFrameIdx();
1261 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1264 // Move general register save area spill slots down, taking into account
1265 // the size of the Floating-point register save area.
1266 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1267 int FI = G8Regs[i].getFrameIdx();
1269 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1273 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1274 TRI->getEncodingValue(MinG8R));
1276 if (Subtarget.isPPC64()) {
1277 LowerBound -= (31 - MinReg + 1) * 8;
1279 LowerBound -= (31 - MinReg + 1) * 4;
1283 // For 32-bit only, the CR save area is below the general register
1284 // save area. For 64-bit SVR4, the CR save area is addressed relative
1285 // to the stack pointer and hence does not need an adjustment here.
1286 // Only CR2 (the first nonvolatile spilled) has an associated frame
1287 // index so that we have a single uniform save area.
1288 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1289 // Adjust the frame index of the CR spill slot.
1290 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1291 unsigned Reg = CSI[i].getReg();
1293 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1294 // Leave Darwin logic as-is.
1295 || (!Subtarget.isSVR4ABI() &&
1296 (PPC::CRBITRCRegClass.contains(Reg) ||
1297 PPC::CRRCRegClass.contains(Reg)))) {
1298 int FI = CSI[i].getFrameIdx();
1300 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1304 LowerBound -= 4; // The CR save area is always 4 bytes long.
1307 if (HasVRSAVESaveArea) {
1308 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1309 // which have the VRSAVE register class?
1310 // Adjust the frame index of the VRSAVE spill slot.
1311 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1312 unsigned Reg = CSI[i].getReg();
1314 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1315 int FI = CSI[i].getFrameIdx();
1317 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1321 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1324 if (HasVRSaveArea) {
1325 // Insert alignment padding, we need 16-byte alignment.
1326 LowerBound = (LowerBound - 15) & ~(15);
1328 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1329 int FI = VRegs[i].getFrameIdx();
1331 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1335 addScavengingSpillSlot(MF, RS);
1339 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1340 RegScavenger *RS) const {
1341 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1342 // a large stack, which will require scavenging a register to materialize a
1345 // We need to have a scavenger spill slot for spills if the frame size is
1346 // large. In case there is no free register for large-offset addressing,
1347 // this slot is used for the necessary emergency spill. Also, we need the
1348 // slot for dynamic stack allocations.
1350 // The scavenger might be invoked if the frame offset does not fit into
1351 // the 16-bit immediate. We don't know the complete frame size here
1352 // because we've not yet computed callee-saved register spills or the
1353 // needed alignment padding.
1354 unsigned StackSize = determineFrameLayout(MF, false, true);
1355 MachineFrameInfo *MFI = MF.getFrameInfo();
1356 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1357 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1358 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1359 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1360 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1361 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1365 // Might we have over-aligned allocas?
1366 bool HasAlVars = MFI->hasVarSizedObjects() &&
1367 MFI->getMaxAlignment() > getStackAlignment();
1369 // These kinds of spills might need two registers.
1370 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1371 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1379 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1380 MachineBasicBlock::iterator MI,
1381 const std::vector<CalleeSavedInfo> &CSI,
1382 const TargetRegisterInfo *TRI) const {
1384 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1385 // Return false otherwise to maintain pre-existing behavior.
1386 if (!Subtarget.isSVR4ABI())
1389 MachineFunction *MF = MBB.getParent();
1390 const PPCInstrInfo &TII =
1391 *static_cast<const PPCInstrInfo *>(
1392 MF->getTarget().getSubtargetImpl()->getInstrInfo());
1394 bool CRSpilled = false;
1395 MachineInstrBuilder CRMIB;
1397 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1398 unsigned Reg = CSI[i].getReg();
1399 // Only Darwin actually uses the VRSAVE register, but it can still appear
1400 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1401 // Darwin, ignore it.
1402 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1405 // CR2 through CR4 are the nonvolatile CR fields.
1406 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1408 // Add the callee-saved register as live-in; it's killed at the spill.
1411 if (CRSpilled && IsCRField) {
1412 CRMIB.addReg(Reg, RegState::ImplicitKill);
1416 // Insert the spill to the stack frame.
1418 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1419 if (Subtarget.isPPC64()) {
1420 // The actual spill will happen at the start of the prologue.
1421 FuncInfo->addMustSaveCR(Reg);
1424 FuncInfo->setSpillsCR();
1426 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1427 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1428 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1429 .addReg(Reg, RegState::ImplicitKill);
1431 MBB.insert(MI, CRMIB);
1432 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1434 getKillRegState(true)),
1435 CSI[i].getFrameIdx()));
1438 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1439 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1440 CSI[i].getFrameIdx(), RC, TRI);
1447 restoreCRs(bool isPPC64, bool is31,
1448 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1449 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1450 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1452 MachineFunction *MF = MBB.getParent();
1453 const PPCInstrInfo &TII =
1454 *static_cast<const PPCInstrInfo *>(
1455 MF->getTarget().getSubtargetImpl()->getInstrInfo());
1457 unsigned RestoreOp, MoveReg;
1460 // This is handled during epilogue generation.
1463 // 32-bit: FP-relative
1464 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1466 CSI[CSIIndex].getFrameIdx()));
1467 RestoreOp = PPC::MTOCRF;
1472 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1473 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1476 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1477 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1480 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1481 .addReg(MoveReg, getKillRegState(true)));
1484 void PPCFrameLowering::
1485 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1486 MachineBasicBlock::iterator I) const {
1487 const PPCInstrInfo &TII =
1488 *static_cast<const PPCInstrInfo *>(
1489 MF.getTarget().getSubtargetImpl()->getInstrInfo());
1490 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1491 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1492 // Add (actually subtract) back the amount the callee popped on return.
1493 if (int CalleeAmt = I->getOperand(1).getImm()) {
1494 bool is64Bit = Subtarget.isPPC64();
1496 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1497 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1498 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1499 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1500 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1501 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1502 MachineInstr *MI = I;
1503 DebugLoc dl = MI->getDebugLoc();
1505 if (isInt<16>(CalleeAmt)) {
1506 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1507 .addReg(StackReg, RegState::Kill)
1510 MachineBasicBlock::iterator MBBI = I;
1511 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1512 .addImm(CalleeAmt >> 16);
1513 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1514 .addReg(TmpReg, RegState::Kill)
1515 .addImm(CalleeAmt & 0xFFFF);
1516 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1517 .addReg(StackReg, RegState::Kill)
1522 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1527 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1528 MachineBasicBlock::iterator MI,
1529 const std::vector<CalleeSavedInfo> &CSI,
1530 const TargetRegisterInfo *TRI) const {
1532 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1533 // Return false otherwise to maintain pre-existing behavior.
1534 if (!Subtarget.isSVR4ABI())
1537 MachineFunction *MF = MBB.getParent();
1538 const PPCInstrInfo &TII =
1539 *static_cast<const PPCInstrInfo *>(
1540 MF->getTarget().getSubtargetImpl()->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);