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 "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/Target/TargetOptions.h"
29 // FIXME This disables some code that aligns the stack to a boundary bigger than
30 // the default (16 bytes on Darwin) when there is a stack local of greater
31 // alignment. This does not currently work, because the delta between old and
32 // new stack pointers is added to offsets that reference incoming parameters
33 // after the prolog is generated, and the code that does that doesn't handle a
34 // variable delta. You don't want to do that anyway; a better approach is to
35 // reserve another register that retains to the incoming stack pointer, and
36 // reference parameters relative to that.
40 /// VRRegNo - Map from a numbered VR register to its enum value.
42 static const uint16_t VRRegNo[] = {
43 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
44 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
45 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
46 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
49 /// RemoveVRSaveCode - We have found that this function does not need any code
50 /// to manipulate the VRSAVE register, even though it uses vector registers.
51 /// This can happen when the only registers used are known to be live in or out
52 /// of the function. Remove all of the VRSAVE related code from the function.
53 /// FIXME: The removal of the code results in a compile failure at -O0 when the
54 /// function contains a function call, as the GPR containing original VRSAVE
55 /// contents is spilled and reloaded around the call. Without the prolog code,
56 /// the spill instruction refers to an undefined register. This code needs
57 /// to account for all uses of that GPR.
58 static void RemoveVRSaveCode(MachineInstr *MI) {
59 MachineBasicBlock *Entry = MI->getParent();
60 MachineFunction *MF = Entry->getParent();
62 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
63 MachineBasicBlock::iterator MBBI = MI;
65 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
66 MBBI->eraseFromParent();
68 bool RemovedAllMTVRSAVEs = true;
69 // See if we can find and remove the MTVRSAVE instruction from all of the
71 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
72 // If last instruction is a return instruction, add an epilogue
73 if (!I->empty() && I->back().isReturn()) {
75 for (MBBI = I->end(); MBBI != I->begin(); ) {
77 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
78 MBBI->eraseFromParent(); // remove it.
83 RemovedAllMTVRSAVEs &= FoundIt;
87 // If we found and removed all MTVRSAVE instructions, remove the read of
89 if (RemovedAllMTVRSAVEs) {
91 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
93 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
94 MBBI->eraseFromParent();
97 // Finally, nuke the UPDATE_VRSAVE.
98 MI->eraseFromParent();
101 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
102 // instruction selector. Based on the vector registers that have been used,
103 // transform this into the appropriate ORI instruction.
104 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
105 MachineFunction *MF = MI->getParent()->getParent();
106 DebugLoc dl = MI->getDebugLoc();
108 unsigned UsedRegMask = 0;
109 for (unsigned i = 0; i != 32; ++i)
110 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
111 UsedRegMask |= 1 << (31-i);
113 // Live in and live out values already must be in the mask, so don't bother
115 for (MachineRegisterInfo::livein_iterator
116 I = MF->getRegInfo().livein_begin(),
117 E = MF->getRegInfo().livein_end(); I != E; ++I) {
118 unsigned RegNo = getPPCRegisterNumbering(I->first);
119 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
120 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
122 for (MachineRegisterInfo::liveout_iterator
123 I = MF->getRegInfo().liveout_begin(),
124 E = MF->getRegInfo().liveout_end(); I != E; ++I) {
125 unsigned RegNo = getPPCRegisterNumbering(*I);
126 if (VRRegNo[RegNo] == *I) // If this really is a vector reg.
127 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
130 // If no registers are used, turn this into a copy.
131 if (UsedRegMask == 0) {
132 // Remove all VRSAVE code.
133 RemoveVRSaveCode(MI);
137 unsigned SrcReg = MI->getOperand(1).getReg();
138 unsigned DstReg = MI->getOperand(0).getReg();
140 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
141 if (DstReg != SrcReg)
142 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
144 .addImm(UsedRegMask);
146 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
147 .addReg(SrcReg, RegState::Kill)
148 .addImm(UsedRegMask);
149 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
150 if (DstReg != SrcReg)
151 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
153 .addImm(UsedRegMask >> 16);
155 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
156 .addReg(SrcReg, RegState::Kill)
157 .addImm(UsedRegMask >> 16);
159 if (DstReg != SrcReg)
160 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
162 .addImm(UsedRegMask >> 16);
164 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
165 .addReg(SrcReg, RegState::Kill)
166 .addImm(UsedRegMask >> 16);
168 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
169 .addReg(DstReg, RegState::Kill)
170 .addImm(UsedRegMask & 0xFFFF);
173 // Remove the old UPDATE_VRSAVE instruction.
174 MI->eraseFromParent();
177 static bool spillsCR(const MachineFunction &MF) {
178 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
179 return FuncInfo->isCRSpilled();
182 /// determineFrameLayout - Determine the size of the frame and maximum call
184 void PPCFrameLowering::determineFrameLayout(MachineFunction &MF) const {
185 MachineFrameInfo *MFI = MF.getFrameInfo();
187 // Get the number of bytes to allocate from the FrameInfo
188 unsigned FrameSize = MFI->getStackSize();
190 // Get the alignments provided by the target, and the maximum alignment
191 // (if any) of the fixed frame objects.
192 unsigned MaxAlign = MFI->getMaxAlignment();
193 unsigned TargetAlign = getStackAlignment();
194 unsigned AlignMask = TargetAlign - 1; //
196 // If we are a leaf function, and use up to 224 bytes of stack space,
197 // don't have a frame pointer, calls, or dynamic alloca then we do not need
198 // to adjust the stack pointer (we fit in the Red Zone). For 64-bit
199 // SVR4, we also require a stack frame if we need to spill the CR,
200 // since this spill area is addressed relative to the stack pointer.
201 bool DisableRedZone = MF.getFunction()->getAttributes().
202 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
203 // FIXME SVR4 The 32-bit SVR4 ABI has no red zone. However, it can
204 // still generate stackless code if all local vars are reg-allocated.
205 // Try: (FrameSize <= 224
206 // || (FrameSize == 0 && Subtarget.isPPC32 && Subtarget.isSVR4ABI()))
207 if (!DisableRedZone &&
208 FrameSize <= 224 && // Fits in red zone.
209 !MFI->hasVarSizedObjects() && // No dynamic alloca.
210 !MFI->adjustsStack() && // No calls.
211 !(Subtarget.isPPC64() && // No 64-bit SVR4 CRsave.
212 Subtarget.isSVR4ABI()
214 (!ALIGN_STACK || MaxAlign <= TargetAlign)) { // No special alignment.
216 MFI->setStackSize(0);
220 // Get the maximum call frame size of all the calls.
221 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
223 // Maximum call frame needs to be at least big enough for linkage and 8 args.
224 unsigned minCallFrameSize = getMinCallFrameSize(Subtarget.isPPC64(),
225 Subtarget.isDarwinABI());
226 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
228 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
229 // that allocations will be aligned.
230 if (MFI->hasVarSizedObjects())
231 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
233 // Update maximum call frame size.
234 MFI->setMaxCallFrameSize(maxCallFrameSize);
236 // Include call frame size in total.
237 FrameSize += maxCallFrameSize;
239 // Make sure the frame is aligned.
240 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
242 // Update frame info.
243 MFI->setStackSize(FrameSize);
246 // hasFP - Return true if the specified function actually has a dedicated frame
248 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
249 const MachineFrameInfo *MFI = MF.getFrameInfo();
250 // FIXME: This is pretty much broken by design: hasFP() might be called really
251 // early, before the stack layout was calculated and thus hasFP() might return
252 // true or false here depending on the time of call.
253 return (MFI->getStackSize()) && needsFP(MF);
256 // needsFP - Return true if the specified function should have a dedicated frame
257 // pointer register. This is true if the function has variable sized allocas or
258 // if frame pointer elimination is disabled.
259 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
260 const MachineFrameInfo *MFI = MF.getFrameInfo();
262 // Naked functions have no stack frame pushed, so we don't have a frame
264 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
268 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
269 MFI->hasVarSizedObjects() ||
270 (MF.getTarget().Options.GuaranteedTailCallOpt &&
271 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
275 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
276 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
277 MachineBasicBlock::iterator MBBI = MBB.begin();
278 MachineFrameInfo *MFI = MF.getFrameInfo();
279 const PPCInstrInfo &TII =
280 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
282 MachineModuleInfo &MMI = MF.getMMI();
284 bool needsFrameMoves = MMI.hasDebugInfo() ||
285 MF.getFunction()->needsUnwindTableEntry();
287 // Prepare for frame info.
288 MCSymbol *FrameLabel = 0;
290 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
292 if (!Subtarget.isSVR4ABI())
293 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
294 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
295 HandleVRSaveUpdate(MBBI, TII);
300 // Move MBBI back to the beginning of the function.
303 // Work out frame sizes.
304 // FIXME: determineFrameLayout() may change the frame size. This should be
305 // moved upper, to some hook.
306 determineFrameLayout(MF);
307 unsigned FrameSize = MFI->getStackSize();
309 int NegFrameSize = -FrameSize;
311 // Get processor type.
312 bool isPPC64 = Subtarget.isPPC64();
313 // Get operating system
314 bool isDarwinABI = Subtarget.isDarwinABI();
315 // Check if the link register (LR) must be saved.
316 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
317 bool MustSaveLR = FI->mustSaveLR();
318 // Do we have a frame pointer for this function?
319 bool HasFP = hasFP(MF);
321 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
325 if (Subtarget.isSVR4ABI()) {
326 MachineFrameInfo *FFI = MF.getFrameInfo();
327 int FPIndex = FI->getFramePointerSaveIndex();
328 assert(FPIndex && "No Frame Pointer Save Slot!");
329 FPOffset = FFI->getObjectOffset(FPIndex);
331 FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
337 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR8), PPC::X0);
340 BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
346 BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
348 .addImm(LROffset / 4)
352 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR), PPC::R0);
355 // FIXME: On PPC32 SVR4, FPOffset is negative and access to negative
356 // offsets of R1 is not allowed.
357 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
363 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
369 // Skip if a leaf routine.
370 if (!FrameSize) return;
372 // Get stack alignments.
373 unsigned TargetAlign = getStackAlignment();
374 unsigned MaxAlign = MFI->getMaxAlignment();
376 // Adjust stack pointer: r1 += NegFrameSize.
377 // If there is a preferred stack alignment, align R1 now
380 if (ALIGN_STACK && MaxAlign > TargetAlign) {
381 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
382 "Invalid alignment!");
383 assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
385 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), PPC::R0)
388 .addImm(32 - Log2_32(MaxAlign))
390 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC) ,PPC::R0)
391 .addReg(PPC::R0, RegState::Kill)
392 .addImm(NegFrameSize);
393 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX), PPC::R1)
394 .addReg(PPC::R1, RegState::Kill)
397 } else if (isInt<16>(NegFrameSize)) {
398 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1)
400 .addImm(NegFrameSize)
403 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
404 .addImm(NegFrameSize >> 16);
405 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
406 .addReg(PPC::R0, RegState::Kill)
407 .addImm(NegFrameSize & 0xFFFF);
408 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX), PPC::R1)
409 .addReg(PPC::R1, RegState::Kill)
414 if (ALIGN_STACK && MaxAlign > TargetAlign) {
415 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
416 "Invalid alignment!");
417 assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
419 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), PPC::X0)
422 .addImm(64 - Log2_32(MaxAlign));
423 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC8), PPC::X0)
425 .addImm(NegFrameSize);
426 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX), PPC::X1)
427 .addReg(PPC::X1, RegState::Kill)
430 } else if (isInt<16>(NegFrameSize)) {
431 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1)
433 .addImm(NegFrameSize / 4)
436 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
437 .addImm(NegFrameSize >> 16);
438 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
439 .addReg(PPC::X0, RegState::Kill)
440 .addImm(NegFrameSize & 0xFFFF);
441 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX), PPC::X1)
442 .addReg(PPC::X1, RegState::Kill)
448 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
450 // Add the "machine moves" for the instructions we generated above, but in
452 if (needsFrameMoves) {
453 // Mark effective beginning of when frame pointer becomes valid.
454 FrameLabel = MMI.getContext().CreateTempSymbol();
455 BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(FrameLabel);
457 // Show update of SP.
459 MachineLocation SPDst(MachineLocation::VirtualFP);
460 MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
461 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
463 MachineLocation SP(isPPC64 ? PPC::X31 : PPC::R31);
464 Moves.push_back(MachineMove(FrameLabel, SP, SP));
468 MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
469 MachineLocation FPSrc(isPPC64 ? PPC::X31 : PPC::R31);
470 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
474 MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
475 MachineLocation LRSrc(isPPC64 ? PPC::LR8 : PPC::LR);
476 Moves.push_back(MachineMove(FrameLabel, LRDst, LRSrc));
480 MCSymbol *ReadyLabel = 0;
482 // If there is a frame pointer, copy R1 into R31
485 BuildMI(MBB, MBBI, dl, TII.get(PPC::OR), PPC::R31)
489 BuildMI(MBB, MBBI, dl, TII.get(PPC::OR8), PPC::X31)
494 if (needsFrameMoves) {
495 ReadyLabel = MMI.getContext().CreateTempSymbol();
497 // Mark effective beginning of when frame pointer is ready.
498 BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(ReadyLabel);
500 MachineLocation FPDst(HasFP ? (isPPC64 ? PPC::X31 : PPC::R31) :
501 (isPPC64 ? PPC::X1 : PPC::R1));
502 MachineLocation FPSrc(MachineLocation::VirtualFP);
503 Moves.push_back(MachineMove(ReadyLabel, FPDst, FPSrc));
507 if (needsFrameMoves) {
508 MCSymbol *Label = HasFP ? ReadyLabel : FrameLabel;
510 // Add callee saved registers to move list.
511 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
512 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
513 unsigned Reg = CSI[I].getReg();
514 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
516 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
517 // subregisters of CR2. We just need to emit a move of CR2.
518 if (PPC::CRBITRCRegClass.contains(Reg))
521 // For SVR4, don't emit a move for the CR spill slot if we haven't
523 if (Subtarget.isSVR4ABI()
524 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
528 // For 64-bit SVR4 when we have spilled CRs, the spill location
529 // is SP+8, not a frame-relative slot.
530 if (Subtarget.isSVR4ABI()
531 && Subtarget.isPPC64()
532 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
533 MachineLocation CSDst(PPC::X1, 8);
534 MachineLocation CSSrc(PPC::CR2);
535 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
539 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
540 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
541 MachineLocation CSSrc(Reg);
542 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
547 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
548 MachineBasicBlock &MBB) const {
549 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
550 assert(MBBI != MBB.end() && "Returning block has no terminator");
551 const PPCInstrInfo &TII =
552 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
554 unsigned RetOpcode = MBBI->getOpcode();
557 assert((RetOpcode == PPC::BLR ||
558 RetOpcode == PPC::TCRETURNri ||
559 RetOpcode == PPC::TCRETURNdi ||
560 RetOpcode == PPC::TCRETURNai ||
561 RetOpcode == PPC::TCRETURNri8 ||
562 RetOpcode == PPC::TCRETURNdi8 ||
563 RetOpcode == PPC::TCRETURNai8) &&
564 "Can only insert epilog into returning blocks");
566 // Get alignment info so we know how to restore r1
567 const MachineFrameInfo *MFI = MF.getFrameInfo();
568 unsigned TargetAlign = getStackAlignment();
569 unsigned MaxAlign = MFI->getMaxAlignment();
571 // Get the number of bytes allocated from the FrameInfo.
572 int FrameSize = MFI->getStackSize();
574 // Get processor type.
575 bool isPPC64 = Subtarget.isPPC64();
576 // Get operating system
577 bool isDarwinABI = Subtarget.isDarwinABI();
578 // Check if the link register (LR) has been saved.
579 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
580 bool MustSaveLR = FI->mustSaveLR();
581 // Do we have a frame pointer for this function?
582 bool HasFP = hasFP(MF);
584 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
588 if (Subtarget.isSVR4ABI()) {
589 MachineFrameInfo *FFI = MF.getFrameInfo();
590 int FPIndex = FI->getFramePointerSaveIndex();
591 assert(FPIndex && "No Frame Pointer Save Slot!");
592 FPOffset = FFI->getObjectOffset(FPIndex);
594 FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
598 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
599 RetOpcode == PPC::TCRETURNdi ||
600 RetOpcode == PPC::TCRETURNai ||
601 RetOpcode == PPC::TCRETURNri8 ||
602 RetOpcode == PPC::TCRETURNdi8 ||
603 RetOpcode == PPC::TCRETURNai8;
606 int MaxTCRetDelta = FI->getTailCallSPDelta();
607 MachineOperand &StackAdjust = MBBI->getOperand(1);
608 assert(StackAdjust.isImm() && "Expecting immediate value.");
609 // Adjust stack pointer.
610 int StackAdj = StackAdjust.getImm();
611 int Delta = StackAdj - MaxTCRetDelta;
612 assert((Delta >= 0) && "Delta must be positive");
614 FrameSize += (StackAdj +Delta);
616 FrameSize += StackAdj;
620 // The loaded (or persistent) stack pointer value is offset by the 'stwu'
621 // on entry to the function. Add this offset back now.
623 // If this function contained a fastcc call and GuaranteedTailCallOpt is
624 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
625 // call which invalidates the stack pointer value in SP(0). So we use the
626 // value of R31 in this case.
627 if (FI->hasFastCall() && isInt<16>(FrameSize)) {
628 assert(hasFP(MF) && "Expecting a valid the frame pointer.");
629 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
630 .addReg(PPC::R31).addImm(FrameSize);
631 } else if(FI->hasFastCall()) {
632 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
633 .addImm(FrameSize >> 16);
634 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
635 .addReg(PPC::R0, RegState::Kill)
636 .addImm(FrameSize & 0xFFFF);
637 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD4))
641 } else if (isInt<16>(FrameSize) &&
642 (!ALIGN_STACK || TargetAlign >= MaxAlign) &&
643 !MFI->hasVarSizedObjects()) {
644 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
645 .addReg(PPC::R1).addImm(FrameSize);
647 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ),PPC::R1)
648 .addImm(0).addReg(PPC::R1);
651 if (FI->hasFastCall() && isInt<16>(FrameSize)) {
652 assert(hasFP(MF) && "Expecting a valid the frame pointer.");
653 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
654 .addReg(PPC::X31).addImm(FrameSize);
655 } else if(FI->hasFastCall()) {
656 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
657 .addImm(FrameSize >> 16);
658 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
659 .addReg(PPC::X0, RegState::Kill)
660 .addImm(FrameSize & 0xFFFF);
661 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD8))
665 } else if (isInt<16>(FrameSize) && TargetAlign >= MaxAlign &&
666 !MFI->hasVarSizedObjects()) {
667 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
668 .addReg(PPC::X1).addImm(FrameSize);
670 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X1)
671 .addImm(0).addReg(PPC::X1);
678 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X0)
679 .addImm(LROffset/4).addReg(PPC::X1);
682 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X31)
683 .addImm(FPOffset/4).addReg(PPC::X1);
686 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR8)).addReg(PPC::X0);
689 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R0)
690 .addImm(LROffset).addReg(PPC::R1);
693 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R31)
694 .addImm(FPOffset).addReg(PPC::R1);
697 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR)).addReg(PPC::R0);
700 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
702 if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
703 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
704 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
705 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
706 unsigned StackReg = isPPC64 ? PPC::X1 : PPC::R1;
707 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
708 unsigned TmpReg = isPPC64 ? PPC::X0 : PPC::R0;
709 unsigned ADDIInstr = isPPC64 ? PPC::ADDI8 : PPC::ADDI;
710 unsigned ADDInstr = isPPC64 ? PPC::ADD8 : PPC::ADD4;
711 unsigned LISInstr = isPPC64 ? PPC::LIS8 : PPC::LIS;
712 unsigned ORIInstr = isPPC64 ? PPC::ORI8 : PPC::ORI;
714 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
715 BuildMI(MBB, MBBI, dl, TII.get(ADDIInstr), StackReg)
716 .addReg(StackReg).addImm(CallerAllocatedAmt);
718 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
719 .addImm(CallerAllocatedAmt >> 16);
720 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
721 .addReg(TmpReg, RegState::Kill)
722 .addImm(CallerAllocatedAmt & 0xFFFF);
723 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
728 } else if (RetOpcode == PPC::TCRETURNdi) {
729 MBBI = MBB.getLastNonDebugInstr();
730 MachineOperand &JumpTarget = MBBI->getOperand(0);
731 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
732 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
733 } else if (RetOpcode == PPC::TCRETURNri) {
734 MBBI = MBB.getLastNonDebugInstr();
735 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
736 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
737 } else if (RetOpcode == PPC::TCRETURNai) {
738 MBBI = MBB.getLastNonDebugInstr();
739 MachineOperand &JumpTarget = MBBI->getOperand(0);
740 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
741 } else if (RetOpcode == PPC::TCRETURNdi8) {
742 MBBI = MBB.getLastNonDebugInstr();
743 MachineOperand &JumpTarget = MBBI->getOperand(0);
744 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
745 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
746 } else if (RetOpcode == PPC::TCRETURNri8) {
747 MBBI = MBB.getLastNonDebugInstr();
748 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
749 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
750 } else if (RetOpcode == PPC::TCRETURNai8) {
751 MBBI = MBB.getLastNonDebugInstr();
752 MachineOperand &JumpTarget = MBBI->getOperand(0);
753 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
757 /// MustSaveLR - Return true if this function requires that we save the LR
758 /// register onto the stack in the prolog and restore it in the epilog of the
760 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
761 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
763 // We need a save/restore of LR if there is any def of LR (which is
764 // defined by calls, including the PIC setup sequence), or if there is
765 // some use of the LR stack slot (e.g. for builtin_return_address).
766 // (LR comes in 32 and 64 bit versions.)
767 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
768 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
772 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
773 RegScavenger *RS) const {
774 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
776 // Save and clear the LR state.
777 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
778 unsigned LR = RegInfo->getRARegister();
779 FI->setMustSaveLR(MustSaveLR(MF, LR));
780 MF.getRegInfo().setPhysRegUnused(LR);
782 // Save R31 if necessary
783 int FPSI = FI->getFramePointerSaveIndex();
784 bool isPPC64 = Subtarget.isPPC64();
785 bool isDarwinABI = Subtarget.isDarwinABI();
786 MachineFrameInfo *MFI = MF.getFrameInfo();
788 // If the frame pointer save index hasn't been defined yet.
789 if (!FPSI && needsFP(MF)) {
790 // Find out what the fix offset of the frame pointer save area.
791 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
792 // Allocate the frame index for frame pointer save area.
793 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
795 FI->setFramePointerSaveIndex(FPSI);
798 // Reserve stack space to move the linkage area to in case of a tail call.
800 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
801 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
802 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
805 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
806 // a large stack, which will require scavenging a register to materialize a
808 // FIXME: this doesn't actually check stack size, so is a bit pessimistic
809 // FIXME: doesn't detect whether or not we need to spill vXX, which requires
812 if (RegInfo->requiresRegisterScavenging(MF))
813 if (needsFP(MF) || spillsCR(MF)) {
814 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
815 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
816 const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
817 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
823 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF)
825 // Early exit if not using the SVR4 ABI.
826 if (!Subtarget.isSVR4ABI())
829 // Get callee saved register information.
830 MachineFrameInfo *FFI = MF.getFrameInfo();
831 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
833 // Early exit if no callee saved registers are modified!
834 if (CSI.empty() && !needsFP(MF)) {
838 unsigned MinGPR = PPC::R31;
839 unsigned MinG8R = PPC::X31;
840 unsigned MinFPR = PPC::F31;
841 unsigned MinVR = PPC::V31;
843 bool HasGPSaveArea = false;
844 bool HasG8SaveArea = false;
845 bool HasFPSaveArea = false;
846 bool HasVRSAVESaveArea = false;
847 bool HasVRSaveArea = false;
849 SmallVector<CalleeSavedInfo, 18> GPRegs;
850 SmallVector<CalleeSavedInfo, 18> G8Regs;
851 SmallVector<CalleeSavedInfo, 18> FPRegs;
852 SmallVector<CalleeSavedInfo, 18> VRegs;
854 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
855 unsigned Reg = CSI[i].getReg();
856 if (PPC::GPRCRegClass.contains(Reg)) {
857 HasGPSaveArea = true;
859 GPRegs.push_back(CSI[i]);
864 } else if (PPC::G8RCRegClass.contains(Reg)) {
865 HasG8SaveArea = true;
867 G8Regs.push_back(CSI[i]);
872 } else if (PPC::F8RCRegClass.contains(Reg)) {
873 HasFPSaveArea = true;
875 FPRegs.push_back(CSI[i]);
880 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
881 PPC::CRRCRegClass.contains(Reg)) {
882 ; // do nothing, as we already know whether CRs are spilled
883 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
884 HasVRSAVESaveArea = true;
885 } else if (PPC::VRRCRegClass.contains(Reg)) {
886 HasVRSaveArea = true;
888 VRegs.push_back(CSI[i]);
894 llvm_unreachable("Unknown RegisterClass!");
898 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
900 int64_t LowerBound = 0;
902 // Take into account stack space reserved for tail calls.
904 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
905 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
906 LowerBound = TCSPDelta;
909 // The Floating-point register save area is right below the back chain word
910 // of the previous stack frame.
912 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
913 int FI = FPRegs[i].getFrameIdx();
915 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
918 LowerBound -= (31 - getPPCRegisterNumbering(MinFPR) + 1) * 8;
921 // Check whether the frame pointer register is allocated. If so, make sure it
922 // is spilled to the correct offset.
924 HasGPSaveArea = true;
926 int FI = PFI->getFramePointerSaveIndex();
927 assert(FI && "No Frame Pointer Save Slot!");
929 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
932 // General register save area starts right below the Floating-point
933 // register save area.
934 if (HasGPSaveArea || HasG8SaveArea) {
935 // Move general register save area spill slots down, taking into account
936 // the size of the Floating-point register save area.
937 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
938 int FI = GPRegs[i].getFrameIdx();
940 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
943 // Move general register save area spill slots down, taking into account
944 // the size of the Floating-point register save area.
945 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
946 int FI = G8Regs[i].getFrameIdx();
948 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
952 std::min<unsigned>(getPPCRegisterNumbering(MinGPR),
953 getPPCRegisterNumbering(MinG8R));
955 if (Subtarget.isPPC64()) {
956 LowerBound -= (31 - MinReg + 1) * 8;
958 LowerBound -= (31 - MinReg + 1) * 4;
962 // For 32-bit only, the CR save area is below the general register
963 // save area. For 64-bit SVR4, the CR save area is addressed relative
964 // to the stack pointer and hence does not need an adjustment here.
965 // Only CR2 (the first nonvolatile spilled) has an associated frame
966 // index so that we have a single uniform save area.
967 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
968 // Adjust the frame index of the CR spill slot.
969 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
970 unsigned Reg = CSI[i].getReg();
972 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
973 // Leave Darwin logic as-is.
974 || (!Subtarget.isSVR4ABI() &&
975 (PPC::CRBITRCRegClass.contains(Reg) ||
976 PPC::CRRCRegClass.contains(Reg)))) {
977 int FI = CSI[i].getFrameIdx();
979 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
983 LowerBound -= 4; // The CR save area is always 4 bytes long.
986 if (HasVRSAVESaveArea) {
987 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
988 // which have the VRSAVE register class?
989 // Adjust the frame index of the VRSAVE spill slot.
990 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
991 unsigned Reg = CSI[i].getReg();
993 if (PPC::VRSAVERCRegClass.contains(Reg)) {
994 int FI = CSI[i].getFrameIdx();
996 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1000 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1003 if (HasVRSaveArea) {
1004 // Insert alignment padding, we need 16-byte alignment.
1005 LowerBound = (LowerBound - 15) & ~(15);
1007 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1008 int FI = VRegs[i].getFrameIdx();
1010 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1016 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1017 MachineBasicBlock::iterator MI,
1018 const std::vector<CalleeSavedInfo> &CSI,
1019 const TargetRegisterInfo *TRI) const {
1021 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1022 // Return false otherwise to maintain pre-existing behavior.
1023 if (!Subtarget.isSVR4ABI())
1026 MachineFunction *MF = MBB.getParent();
1027 const PPCInstrInfo &TII =
1028 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1030 bool CRSpilled = false;
1032 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1033 unsigned Reg = CSI[i].getReg();
1034 // CR2 through CR4 are the nonvolatile CR fields.
1035 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1037 if (CRSpilled && IsCRField)
1040 // Add the callee-saved register as live-in; it's killed at the spill.
1043 // Insert the spill to the stack frame.
1046 // The first time we see a CR field, store the whole CR into the
1047 // save slot via GPR12 (available in the prolog for 32- and 64-bit).
1048 if (Subtarget.isPPC64()) {
1050 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::X12));
1051 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::STW))
1053 getKillRegState(true))
1057 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1058 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1059 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12));
1060 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1062 getKillRegState(true)),
1063 CSI[i].getFrameIdx()));
1066 // Record that we spill the CR in this function.
1067 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1068 FuncInfo->setSpillsCR();
1070 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1071 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1072 CSI[i].getFrameIdx(), RC, TRI);
1079 restoreCRs(bool isPPC64, bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1080 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1081 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1083 MachineFunction *MF = MBB.getParent();
1084 const PPCInstrInfo &TII =
1085 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1087 unsigned RestoreOp, MoveReg;
1091 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::LWZ), PPC::X12)
1094 RestoreOp = PPC::MTCRF8;
1097 // 32-bit: FP-relative
1098 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1100 CSI[CSIIndex].getFrameIdx()));
1101 RestoreOp = PPC::MTCRF;
1106 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1110 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1114 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1119 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1120 MachineBasicBlock::iterator MI,
1121 const std::vector<CalleeSavedInfo> &CSI,
1122 const TargetRegisterInfo *TRI) const {
1124 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1125 // Return false otherwise to maintain pre-existing behavior.
1126 if (!Subtarget.isSVR4ABI())
1129 MachineFunction *MF = MBB.getParent();
1130 const PPCInstrInfo &TII =
1131 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1132 bool CR2Spilled = false;
1133 bool CR3Spilled = false;
1134 bool CR4Spilled = false;
1135 unsigned CSIIndex = 0;
1137 // Initialize insertion-point logic; we will be restoring in reverse
1139 MachineBasicBlock::iterator I = MI, BeforeI = I;
1140 bool AtStart = I == MBB.begin();
1145 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1146 unsigned Reg = CSI[i].getReg();
1148 if (Reg == PPC::CR2) {
1150 // The spill slot is associated only with CR2, which is the
1151 // first nonvolatile spilled. Save it here.
1154 } else if (Reg == PPC::CR3) {
1157 } else if (Reg == PPC::CR4) {
1161 // When we first encounter a non-CR register after seeing at
1162 // least one CR register, restore all spilled CRs together.
1163 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1164 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1165 restoreCRs(Subtarget.isPPC64(), CR2Spilled, CR3Spilled, CR4Spilled,
1166 MBB, I, CSI, CSIIndex);
1167 CR2Spilled = CR3Spilled = CR4Spilled = false;
1170 // Default behavior for non-CR saves.
1171 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1172 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1174 assert(I != MBB.begin() &&
1175 "loadRegFromStackSlot didn't insert any code!");
1178 // Insert in reverse order.
1187 // If we haven't yet spilled the CRs, do so now.
1188 if (CR2Spilled || CR3Spilled || CR4Spilled)
1189 restoreCRs(Subtarget.isPPC64(), CR2Spilled, CR3Spilled, CR4Spilled,
1190 MBB, I, CSI, CSIIndex);