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 "PPCInstrInfo.h"
16 #include "PPCInstrBuilder.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "llvm/Function.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/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 static void RemoveVRSaveCode(MachineInstr *MI) {
54 MachineBasicBlock *Entry = MI->getParent();
55 MachineFunction *MF = Entry->getParent();
57 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
58 MachineBasicBlock::iterator MBBI = MI;
60 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
61 MBBI->eraseFromParent();
63 bool RemovedAllMTVRSAVEs = true;
64 // See if we can find and remove the MTVRSAVE instruction from all of the
66 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
67 // If last instruction is a return instruction, add an epilogue
68 if (!I->empty() && I->back().isReturn()) {
70 for (MBBI = I->end(); MBBI != I->begin(); ) {
72 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
73 MBBI->eraseFromParent(); // remove it.
78 RemovedAllMTVRSAVEs &= FoundIt;
82 // If we found and removed all MTVRSAVE instructions, remove the read of
84 if (RemovedAllMTVRSAVEs) {
86 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
88 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
89 MBBI->eraseFromParent();
92 // Finally, nuke the UPDATE_VRSAVE.
93 MI->eraseFromParent();
96 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
97 // instruction selector. Based on the vector registers that have been used,
98 // transform this into the appropriate ORI instruction.
99 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
100 MachineFunction *MF = MI->getParent()->getParent();
101 DebugLoc dl = MI->getDebugLoc();
103 unsigned UsedRegMask = 0;
104 for (unsigned i = 0; i != 32; ++i)
105 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
106 UsedRegMask |= 1 << (31-i);
108 // Live in and live out values already must be in the mask, so don't bother
110 for (MachineRegisterInfo::livein_iterator
111 I = MF->getRegInfo().livein_begin(),
112 E = MF->getRegInfo().livein_end(); I != E; ++I) {
113 unsigned RegNo = getPPCRegisterNumbering(I->first);
114 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
115 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
117 for (MachineRegisterInfo::liveout_iterator
118 I = MF->getRegInfo().liveout_begin(),
119 E = MF->getRegInfo().liveout_end(); I != E; ++I) {
120 unsigned RegNo = getPPCRegisterNumbering(*I);
121 if (VRRegNo[RegNo] == *I) // If this really is a vector reg.
122 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
125 // If no registers are used, turn this into a copy.
126 if (UsedRegMask == 0) {
127 // Remove all VRSAVE code.
128 RemoveVRSaveCode(MI);
132 unsigned SrcReg = MI->getOperand(1).getReg();
133 unsigned DstReg = MI->getOperand(0).getReg();
135 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
136 if (DstReg != SrcReg)
137 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
139 .addImm(UsedRegMask);
141 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
142 .addReg(SrcReg, RegState::Kill)
143 .addImm(UsedRegMask);
144 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
145 if (DstReg != SrcReg)
146 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
148 .addImm(UsedRegMask >> 16);
150 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
151 .addReg(SrcReg, RegState::Kill)
152 .addImm(UsedRegMask >> 16);
154 if (DstReg != SrcReg)
155 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
157 .addImm(UsedRegMask >> 16);
159 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
160 .addReg(SrcReg, RegState::Kill)
161 .addImm(UsedRegMask >> 16);
163 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
164 .addReg(DstReg, RegState::Kill)
165 .addImm(UsedRegMask & 0xFFFF);
168 // Remove the old UPDATE_VRSAVE instruction.
169 MI->eraseFromParent();
172 static bool spillsCR(const MachineFunction &MF) {
173 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
174 return FuncInfo->isCRSpilled();
177 /// determineFrameLayout - Determine the size of the frame and maximum call
179 void PPCFrameLowering::determineFrameLayout(MachineFunction &MF) const {
180 MachineFrameInfo *MFI = MF.getFrameInfo();
182 // Get the number of bytes to allocate from the FrameInfo
183 unsigned FrameSize = MFI->getStackSize();
185 // Get the alignments provided by the target, and the maximum alignment
186 // (if any) of the fixed frame objects.
187 unsigned MaxAlign = MFI->getMaxAlignment();
188 unsigned TargetAlign = getStackAlignment();
189 unsigned AlignMask = TargetAlign - 1; //
191 // If we are a leaf function, and use up to 224 bytes of stack space,
192 // don't have a frame pointer, calls, or dynamic alloca then we do not need
193 // to adjust the stack pointer (we fit in the Red Zone). For 64-bit
194 // SVR4, we also require a stack frame if we need to spill the CR,
195 // since this spill area is addressed relative to the stack pointer.
196 bool DisableRedZone = MF.getFunction()->hasFnAttr(Attribute::NoRedZone);
197 // FIXME SVR4 The 32-bit SVR4 ABI has no red zone. However, it can
198 // still generate stackless code if all local vars are reg-allocated.
199 // Try: (FrameSize <= 224
200 // || (FrameSize == 0 && Subtarget.isPPC32 && Subtarget.isSVR4ABI()))
201 if (!DisableRedZone &&
202 FrameSize <= 224 && // Fits in red zone.
203 !MFI->hasVarSizedObjects() && // No dynamic alloca.
204 !MFI->adjustsStack() && // No calls.
205 !(Subtarget.isPPC64() && // No 64-bit SVR4 CRsave.
206 Subtarget.isSVR4ABI()
208 (!ALIGN_STACK || MaxAlign <= TargetAlign)) { // No special alignment.
210 MFI->setStackSize(0);
214 // Get the maximum call frame size of all the calls.
215 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
217 // Maximum call frame needs to be at least big enough for linkage and 8 args.
218 unsigned minCallFrameSize = getMinCallFrameSize(Subtarget.isPPC64(),
219 Subtarget.isDarwinABI());
220 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
222 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
223 // that allocations will be aligned.
224 if (MFI->hasVarSizedObjects())
225 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
227 // Update maximum call frame size.
228 MFI->setMaxCallFrameSize(maxCallFrameSize);
230 // Include call frame size in total.
231 FrameSize += maxCallFrameSize;
233 // Make sure the frame is aligned.
234 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
236 // Update frame info.
237 MFI->setStackSize(FrameSize);
240 // hasFP - Return true if the specified function actually has a dedicated frame
242 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
243 const MachineFrameInfo *MFI = MF.getFrameInfo();
244 // FIXME: This is pretty much broken by design: hasFP() might be called really
245 // early, before the stack layout was calculated and thus hasFP() might return
246 // true or false here depending on the time of call.
247 return (MFI->getStackSize()) && needsFP(MF);
250 // needsFP - Return true if the specified function should have a dedicated frame
251 // pointer register. This is true if the function has variable sized allocas or
252 // if frame pointer elimination is disabled.
253 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
254 const MachineFrameInfo *MFI = MF.getFrameInfo();
256 // Naked functions have no stack frame pushed, so we don't have a frame
258 if (MF.getFunction()->hasFnAttr(Attribute::Naked))
261 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
262 MFI->hasVarSizedObjects() ||
263 (MF.getTarget().Options.GuaranteedTailCallOpt &&
264 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
268 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
269 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
270 MachineBasicBlock::iterator MBBI = MBB.begin();
271 MachineFrameInfo *MFI = MF.getFrameInfo();
272 const PPCInstrInfo &TII =
273 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
275 MachineModuleInfo &MMI = MF.getMMI();
277 bool needsFrameMoves = MMI.hasDebugInfo() ||
278 MF.getFunction()->needsUnwindTableEntry();
280 // Prepare for frame info.
281 MCSymbol *FrameLabel = 0;
283 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
285 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
286 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
287 HandleVRSaveUpdate(MBBI, TII);
292 // Move MBBI back to the beginning of the function.
295 // Work out frame sizes.
296 // FIXME: determineFrameLayout() may change the frame size. This should be
297 // moved upper, to some hook.
298 determineFrameLayout(MF);
299 unsigned FrameSize = MFI->getStackSize();
301 int NegFrameSize = -FrameSize;
303 // Get processor type.
304 bool isPPC64 = Subtarget.isPPC64();
305 // Get operating system
306 bool isDarwinABI = Subtarget.isDarwinABI();
307 // Check if the link register (LR) must be saved.
308 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
309 bool MustSaveLR = FI->mustSaveLR();
310 // Do we have a frame pointer for this function?
311 bool HasFP = hasFP(MF);
313 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
317 if (Subtarget.isSVR4ABI()) {
318 MachineFrameInfo *FFI = MF.getFrameInfo();
319 int FPIndex = FI->getFramePointerSaveIndex();
320 assert(FPIndex && "No Frame Pointer Save Slot!");
321 FPOffset = FFI->getObjectOffset(FPIndex);
323 FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
329 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR8), PPC::X0);
332 BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
338 BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
340 .addImm(LROffset / 4)
344 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR), PPC::R0);
347 // FIXME: On PPC32 SVR4, FPOffset is negative and access to negative
348 // offsets of R1 is not allowed.
349 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
355 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
361 // Skip if a leaf routine.
362 if (!FrameSize) return;
364 // Get stack alignments.
365 unsigned TargetAlign = getStackAlignment();
366 unsigned MaxAlign = MFI->getMaxAlignment();
368 // Adjust stack pointer: r1 += NegFrameSize.
369 // If there is a preferred stack alignment, align R1 now
372 if (ALIGN_STACK && MaxAlign > TargetAlign) {
373 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
374 "Invalid alignment!");
375 assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
377 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), PPC::R0)
380 .addImm(32 - Log2_32(MaxAlign))
382 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC) ,PPC::R0)
383 .addReg(PPC::R0, RegState::Kill)
384 .addImm(NegFrameSize);
385 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX), PPC::R1)
386 .addReg(PPC::R1, RegState::Kill)
389 } else if (isInt<16>(NegFrameSize)) {
390 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1)
392 .addImm(NegFrameSize)
395 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
396 .addImm(NegFrameSize >> 16);
397 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
398 .addReg(PPC::R0, RegState::Kill)
399 .addImm(NegFrameSize & 0xFFFF);
400 BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX), PPC::R1)
401 .addReg(PPC::R1, RegState::Kill)
406 if (ALIGN_STACK && MaxAlign > TargetAlign) {
407 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
408 "Invalid alignment!");
409 assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
411 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), PPC::X0)
414 .addImm(64 - Log2_32(MaxAlign));
415 BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC8), PPC::X0)
417 .addImm(NegFrameSize);
418 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX), PPC::X1)
419 .addReg(PPC::X1, RegState::Kill)
422 } else if (isInt<16>(NegFrameSize)) {
423 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1)
425 .addImm(NegFrameSize / 4)
428 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
429 .addImm(NegFrameSize >> 16);
430 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
431 .addReg(PPC::X0, RegState::Kill)
432 .addImm(NegFrameSize & 0xFFFF);
433 BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX), PPC::X1)
434 .addReg(PPC::X1, RegState::Kill)
440 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
442 // Add the "machine moves" for the instructions we generated above, but in
444 if (needsFrameMoves) {
445 // Mark effective beginning of when frame pointer becomes valid.
446 FrameLabel = MMI.getContext().CreateTempSymbol();
447 BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(FrameLabel);
449 // Show update of SP.
451 MachineLocation SPDst(MachineLocation::VirtualFP);
452 MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
453 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
455 MachineLocation SP(isPPC64 ? PPC::X31 : PPC::R31);
456 Moves.push_back(MachineMove(FrameLabel, SP, SP));
460 MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
461 MachineLocation FPSrc(isPPC64 ? PPC::X31 : PPC::R31);
462 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
466 MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
467 MachineLocation LRSrc(isPPC64 ? PPC::LR8 : PPC::LR);
468 Moves.push_back(MachineMove(FrameLabel, LRDst, LRSrc));
472 MCSymbol *ReadyLabel = 0;
474 // If there is a frame pointer, copy R1 into R31
477 BuildMI(MBB, MBBI, dl, TII.get(PPC::OR), PPC::R31)
481 BuildMI(MBB, MBBI, dl, TII.get(PPC::OR8), PPC::X31)
486 if (needsFrameMoves) {
487 ReadyLabel = MMI.getContext().CreateTempSymbol();
489 // Mark effective beginning of when frame pointer is ready.
490 BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(ReadyLabel);
492 MachineLocation FPDst(HasFP ? (isPPC64 ? PPC::X31 : PPC::R31) :
493 (isPPC64 ? PPC::X1 : PPC::R1));
494 MachineLocation FPSrc(MachineLocation::VirtualFP);
495 Moves.push_back(MachineMove(ReadyLabel, FPDst, FPSrc));
499 if (needsFrameMoves) {
500 MCSymbol *Label = HasFP ? ReadyLabel : FrameLabel;
502 // Add callee saved registers to move list.
503 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
504 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
505 unsigned Reg = CSI[I].getReg();
506 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
508 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
509 // subregisters of CR2. We just need to emit a move of CR2.
510 if (PPC::CRBITRCRegClass.contains(Reg))
513 // For SVR4, don't emit a move for the CR spill slot if we haven't
515 if (Subtarget.isSVR4ABI()
516 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
520 // For 64-bit SVR4 when we have spilled CRs, the spill location
521 // is SP+8, not a frame-relative slot.
522 if (Subtarget.isSVR4ABI()
523 && Subtarget.isPPC64()
524 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
525 MachineLocation CSDst(PPC::X1, 8);
526 MachineLocation CSSrc(PPC::CR2);
527 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
531 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
532 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
533 MachineLocation CSSrc(Reg);
534 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
539 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
540 MachineBasicBlock &MBB) const {
541 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
542 assert(MBBI != MBB.end() && "Returning block has no terminator");
543 const PPCInstrInfo &TII =
544 *static_cast<const PPCInstrInfo*>(MF.getTarget().getInstrInfo());
546 unsigned RetOpcode = MBBI->getOpcode();
549 assert((RetOpcode == PPC::BLR ||
550 RetOpcode == PPC::TCRETURNri ||
551 RetOpcode == PPC::TCRETURNdi ||
552 RetOpcode == PPC::TCRETURNai ||
553 RetOpcode == PPC::TCRETURNri8 ||
554 RetOpcode == PPC::TCRETURNdi8 ||
555 RetOpcode == PPC::TCRETURNai8) &&
556 "Can only insert epilog into returning blocks");
558 // Get alignment info so we know how to restore r1
559 const MachineFrameInfo *MFI = MF.getFrameInfo();
560 unsigned TargetAlign = getStackAlignment();
561 unsigned MaxAlign = MFI->getMaxAlignment();
563 // Get the number of bytes allocated from the FrameInfo.
564 int FrameSize = MFI->getStackSize();
566 // Get processor type.
567 bool isPPC64 = Subtarget.isPPC64();
568 // Get operating system
569 bool isDarwinABI = Subtarget.isDarwinABI();
570 // Check if the link register (LR) has been saved.
571 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
572 bool MustSaveLR = FI->mustSaveLR();
573 // Do we have a frame pointer for this function?
574 bool HasFP = hasFP(MF);
576 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
580 if (Subtarget.isSVR4ABI()) {
581 MachineFrameInfo *FFI = MF.getFrameInfo();
582 int FPIndex = FI->getFramePointerSaveIndex();
583 assert(FPIndex && "No Frame Pointer Save Slot!");
584 FPOffset = FFI->getObjectOffset(FPIndex);
586 FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
590 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
591 RetOpcode == PPC::TCRETURNdi ||
592 RetOpcode == PPC::TCRETURNai ||
593 RetOpcode == PPC::TCRETURNri8 ||
594 RetOpcode == PPC::TCRETURNdi8 ||
595 RetOpcode == PPC::TCRETURNai8;
598 int MaxTCRetDelta = FI->getTailCallSPDelta();
599 MachineOperand &StackAdjust = MBBI->getOperand(1);
600 assert(StackAdjust.isImm() && "Expecting immediate value.");
601 // Adjust stack pointer.
602 int StackAdj = StackAdjust.getImm();
603 int Delta = StackAdj - MaxTCRetDelta;
604 assert((Delta >= 0) && "Delta must be positive");
606 FrameSize += (StackAdj +Delta);
608 FrameSize += StackAdj;
612 // The loaded (or persistent) stack pointer value is offset by the 'stwu'
613 // on entry to the function. Add this offset back now.
615 // If this function contained a fastcc call and GuaranteedTailCallOpt is
616 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
617 // call which invalidates the stack pointer value in SP(0). So we use the
618 // value of R31 in this case.
619 if (FI->hasFastCall() && isInt<16>(FrameSize)) {
620 assert(hasFP(MF) && "Expecting a valid the frame pointer.");
621 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
622 .addReg(PPC::R31).addImm(FrameSize);
623 } else if(FI->hasFastCall()) {
624 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
625 .addImm(FrameSize >> 16);
626 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
627 .addReg(PPC::R0, RegState::Kill)
628 .addImm(FrameSize & 0xFFFF);
629 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD4))
633 } else if (isInt<16>(FrameSize) &&
634 (!ALIGN_STACK || TargetAlign >= MaxAlign) &&
635 !MFI->hasVarSizedObjects()) {
636 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
637 .addReg(PPC::R1).addImm(FrameSize);
639 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ),PPC::R1)
640 .addImm(0).addReg(PPC::R1);
643 if (FI->hasFastCall() && isInt<16>(FrameSize)) {
644 assert(hasFP(MF) && "Expecting a valid the frame pointer.");
645 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
646 .addReg(PPC::X31).addImm(FrameSize);
647 } else if(FI->hasFastCall()) {
648 BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
649 .addImm(FrameSize >> 16);
650 BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
651 .addReg(PPC::X0, RegState::Kill)
652 .addImm(FrameSize & 0xFFFF);
653 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD8))
657 } else if (isInt<16>(FrameSize) && TargetAlign >= MaxAlign &&
658 !MFI->hasVarSizedObjects()) {
659 BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
660 .addReg(PPC::X1).addImm(FrameSize);
662 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X1)
663 .addImm(0).addReg(PPC::X1);
670 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X0)
671 .addImm(LROffset/4).addReg(PPC::X1);
674 BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X31)
675 .addImm(FPOffset/4).addReg(PPC::X1);
678 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR8)).addReg(PPC::X0);
681 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R0)
682 .addImm(LROffset).addReg(PPC::R1);
685 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R31)
686 .addImm(FPOffset).addReg(PPC::R1);
689 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR)).addReg(PPC::R0);
692 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
694 if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
695 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
696 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
697 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
698 unsigned StackReg = isPPC64 ? PPC::X1 : PPC::R1;
699 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
700 unsigned TmpReg = isPPC64 ? PPC::X0 : PPC::R0;
701 unsigned ADDIInstr = isPPC64 ? PPC::ADDI8 : PPC::ADDI;
702 unsigned ADDInstr = isPPC64 ? PPC::ADD8 : PPC::ADD4;
703 unsigned LISInstr = isPPC64 ? PPC::LIS8 : PPC::LIS;
704 unsigned ORIInstr = isPPC64 ? PPC::ORI8 : PPC::ORI;
706 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
707 BuildMI(MBB, MBBI, dl, TII.get(ADDIInstr), StackReg)
708 .addReg(StackReg).addImm(CallerAllocatedAmt);
710 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
711 .addImm(CallerAllocatedAmt >> 16);
712 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
713 .addReg(TmpReg, RegState::Kill)
714 .addImm(CallerAllocatedAmt & 0xFFFF);
715 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
720 } else if (RetOpcode == PPC::TCRETURNdi) {
721 MBBI = MBB.getLastNonDebugInstr();
722 MachineOperand &JumpTarget = MBBI->getOperand(0);
723 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
724 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
725 } else if (RetOpcode == PPC::TCRETURNri) {
726 MBBI = MBB.getLastNonDebugInstr();
727 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
728 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
729 } else if (RetOpcode == PPC::TCRETURNai) {
730 MBBI = MBB.getLastNonDebugInstr();
731 MachineOperand &JumpTarget = MBBI->getOperand(0);
732 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
733 } else if (RetOpcode == PPC::TCRETURNdi8) {
734 MBBI = MBB.getLastNonDebugInstr();
735 MachineOperand &JumpTarget = MBBI->getOperand(0);
736 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
737 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
738 } else if (RetOpcode == PPC::TCRETURNri8) {
739 MBBI = MBB.getLastNonDebugInstr();
740 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
741 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
742 } else if (RetOpcode == PPC::TCRETURNai8) {
743 MBBI = MBB.getLastNonDebugInstr();
744 MachineOperand &JumpTarget = MBBI->getOperand(0);
745 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
749 /// MustSaveLR - Return true if this function requires that we save the LR
750 /// register onto the stack in the prolog and restore it in the epilog of the
752 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
753 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
755 // We need a save/restore of LR if there is any def of LR (which is
756 // defined by calls, including the PIC setup sequence), or if there is
757 // some use of the LR stack slot (e.g. for builtin_return_address).
758 // (LR comes in 32 and 64 bit versions.)
759 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
760 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
764 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
765 RegScavenger *RS) const {
766 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
768 // Save and clear the LR state.
769 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
770 unsigned LR = RegInfo->getRARegister();
771 FI->setMustSaveLR(MustSaveLR(MF, LR));
772 MF.getRegInfo().setPhysRegUnused(LR);
774 // Save R31 if necessary
775 int FPSI = FI->getFramePointerSaveIndex();
776 bool isPPC64 = Subtarget.isPPC64();
777 bool isDarwinABI = Subtarget.isDarwinABI();
778 MachineFrameInfo *MFI = MF.getFrameInfo();
780 // If the frame pointer save index hasn't been defined yet.
781 if (!FPSI && needsFP(MF)) {
782 // Find out what the fix offset of the frame pointer save area.
783 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
784 // Allocate the frame index for frame pointer save area.
785 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
787 FI->setFramePointerSaveIndex(FPSI);
790 // Reserve stack space to move the linkage area to in case of a tail call.
792 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
793 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
794 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
797 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
798 // a large stack, which will require scavenging a register to materialize a
800 // FIXME: this doesn't actually check stack size, so is a bit pessimistic
801 // FIXME: doesn't detect whether or not we need to spill vXX, which requires
804 if (RegInfo->requiresRegisterScavenging(MF))
805 if (needsFP(MF) || spillsCR(MF)) {
806 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
807 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
808 const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
809 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
815 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF)
817 // Early exit if not using the SVR4 ABI.
818 if (!Subtarget.isSVR4ABI())
821 // Get callee saved register information.
822 MachineFrameInfo *FFI = MF.getFrameInfo();
823 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
825 // Early exit if no callee saved registers are modified!
826 if (CSI.empty() && !needsFP(MF)) {
830 unsigned MinGPR = PPC::R31;
831 unsigned MinG8R = PPC::X31;
832 unsigned MinFPR = PPC::F31;
833 unsigned MinVR = PPC::V31;
835 bool HasGPSaveArea = false;
836 bool HasG8SaveArea = false;
837 bool HasFPSaveArea = false;
838 bool HasVRSAVESaveArea = false;
839 bool HasVRSaveArea = false;
841 SmallVector<CalleeSavedInfo, 18> GPRegs;
842 SmallVector<CalleeSavedInfo, 18> G8Regs;
843 SmallVector<CalleeSavedInfo, 18> FPRegs;
844 SmallVector<CalleeSavedInfo, 18> VRegs;
846 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
847 unsigned Reg = CSI[i].getReg();
848 if (PPC::GPRCRegClass.contains(Reg)) {
849 HasGPSaveArea = true;
851 GPRegs.push_back(CSI[i]);
856 } else if (PPC::G8RCRegClass.contains(Reg)) {
857 HasG8SaveArea = true;
859 G8Regs.push_back(CSI[i]);
864 } else if (PPC::F8RCRegClass.contains(Reg)) {
865 HasFPSaveArea = true;
867 FPRegs.push_back(CSI[i]);
872 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
873 PPC::CRRCRegClass.contains(Reg)) {
874 ; // do nothing, as we already know whether CRs are spilled
875 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
876 HasVRSAVESaveArea = true;
877 } else if (PPC::VRRCRegClass.contains(Reg)) {
878 HasVRSaveArea = true;
880 VRegs.push_back(CSI[i]);
886 llvm_unreachable("Unknown RegisterClass!");
890 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
892 int64_t LowerBound = 0;
894 // Take into account stack space reserved for tail calls.
896 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
897 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
898 LowerBound = TCSPDelta;
901 // The Floating-point register save area is right below the back chain word
902 // of the previous stack frame.
904 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
905 int FI = FPRegs[i].getFrameIdx();
907 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
910 LowerBound -= (31 - getPPCRegisterNumbering(MinFPR) + 1) * 8;
913 // Check whether the frame pointer register is allocated. If so, make sure it
914 // is spilled to the correct offset.
916 HasGPSaveArea = true;
918 int FI = PFI->getFramePointerSaveIndex();
919 assert(FI && "No Frame Pointer Save Slot!");
921 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
924 // General register save area starts right below the Floating-point
925 // register save area.
926 if (HasGPSaveArea || HasG8SaveArea) {
927 // Move general register save area spill slots down, taking into account
928 // the size of the Floating-point register save area.
929 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
930 int FI = GPRegs[i].getFrameIdx();
932 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
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 = G8Regs.size(); i != e; ++i) {
938 int FI = G8Regs[i].getFrameIdx();
940 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
944 std::min<unsigned>(getPPCRegisterNumbering(MinGPR),
945 getPPCRegisterNumbering(MinG8R));
947 if (Subtarget.isPPC64()) {
948 LowerBound -= (31 - MinReg + 1) * 8;
950 LowerBound -= (31 - MinReg + 1) * 4;
954 // For 32-bit only, the CR save area is below the general register
955 // save area. For 64-bit SVR4, the CR save area is addressed relative
956 // to the stack pointer and hence does not need an adjustment here.
957 // Only CR2 (the first nonvolatile spilled) has an associated frame
958 // index so that we have a single uniform save area.
959 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
960 // Adjust the frame index of the CR spill slot.
961 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
962 unsigned Reg = CSI[i].getReg();
964 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
965 // Leave Darwin logic as-is.
966 || (!Subtarget.isSVR4ABI() &&
967 (PPC::CRBITRCRegClass.contains(Reg) ||
968 PPC::CRRCRegClass.contains(Reg)))) {
969 int FI = CSI[i].getFrameIdx();
971 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
975 LowerBound -= 4; // The CR save area is always 4 bytes long.
978 if (HasVRSAVESaveArea) {
979 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
980 // which have the VRSAVE register class?
981 // Adjust the frame index of the VRSAVE spill slot.
982 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
983 unsigned Reg = CSI[i].getReg();
985 if (PPC::VRSAVERCRegClass.contains(Reg)) {
986 int FI = CSI[i].getFrameIdx();
988 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
992 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
996 // Insert alignment padding, we need 16-byte alignment.
997 LowerBound = (LowerBound - 15) & ~(15);
999 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1000 int FI = VRegs[i].getFrameIdx();
1002 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1008 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1009 MachineBasicBlock::iterator MI,
1010 const std::vector<CalleeSavedInfo> &CSI,
1011 const TargetRegisterInfo *TRI) const {
1013 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1014 // Return false otherwise to maintain pre-existing behavior.
1015 if (!Subtarget.isSVR4ABI())
1018 MachineFunction *MF = MBB.getParent();
1019 const PPCInstrInfo &TII =
1020 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1022 bool CRSpilled = false;
1024 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1025 unsigned Reg = CSI[i].getReg();
1026 // CR2 through CR4 are the nonvolatile CR fields.
1027 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1029 if (CRSpilled && IsCRField)
1032 // Add the callee-saved register as live-in; it's killed at the spill.
1035 // Insert the spill to the stack frame.
1038 // The first time we see a CR field, store the whole CR into the
1039 // save slot via GPR12 (available in the prolog for 32- and 64-bit).
1040 if (Subtarget.isPPC64()) {
1042 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::X12));
1043 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::STW))
1045 getKillRegState(true))
1049 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1050 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1051 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12));
1052 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1054 getKillRegState(true)),
1055 CSI[i].getFrameIdx()));
1058 // Record that we spill the CR in this function.
1059 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1060 FuncInfo->setSpillsCR();
1062 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1063 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1064 CSI[i].getFrameIdx(), RC, TRI);
1071 restoreCRs(bool isPPC64, bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1072 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1073 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1075 MachineFunction *MF = MBB.getParent();
1076 const PPCInstrInfo &TII =
1077 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1079 unsigned RestoreOp, MoveReg;
1083 MBB.insert(MI, BuildMI(*MF, DL, TII.get(PPC::LWZ), PPC::X12)
1086 RestoreOp = PPC::MTCRF8;
1089 // 32-bit: FP-relative
1090 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1092 CSI[CSIIndex].getFrameIdx()));
1093 RestoreOp = PPC::MTCRF;
1098 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1102 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1106 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1111 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1112 MachineBasicBlock::iterator MI,
1113 const std::vector<CalleeSavedInfo> &CSI,
1114 const TargetRegisterInfo *TRI) const {
1116 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1117 // Return false otherwise to maintain pre-existing behavior.
1118 if (!Subtarget.isSVR4ABI())
1121 MachineFunction *MF = MBB.getParent();
1122 const PPCInstrInfo &TII =
1123 *static_cast<const PPCInstrInfo*>(MF->getTarget().getInstrInfo());
1124 bool CR2Spilled = false;
1125 bool CR3Spilled = false;
1126 bool CR4Spilled = false;
1127 unsigned CSIIndex = 0;
1129 // Initialize insertion-point logic; we will be restoring in reverse
1131 MachineBasicBlock::iterator I = MI, BeforeI = I;
1132 bool AtStart = I == MBB.begin();
1137 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1138 unsigned Reg = CSI[i].getReg();
1140 if (Reg == PPC::CR2) {
1142 // The spill slot is associated only with CR2, which is the
1143 // first nonvolatile spilled. Save it here.
1146 } else if (Reg == PPC::CR3) {
1149 } else if (Reg == PPC::CR4) {
1153 // When we first encounter a non-CR register after seeing at
1154 // least one CR register, restore all spilled CRs together.
1155 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1156 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1157 restoreCRs(Subtarget.isPPC64(), CR2Spilled, CR3Spilled, CR4Spilled,
1158 MBB, I, CSI, CSIIndex);
1159 CR2Spilled = CR3Spilled = CR4Spilled = false;
1162 // Default behavior for non-CR saves.
1163 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1164 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1166 assert(I != MBB.begin() &&
1167 "loadRegFromStackSlot didn't insert any code!");
1170 // Insert in reverse order.
1179 // If we haven't yet spilled the CRs, do so now.
1180 if (CR2Spilled || CR3Spilled || CR4Spilled)
1181 restoreCRs(Subtarget.isPPC64(), CR2Spilled, CR3Spilled, CR4Spilled,
1182 MBB, I, CSI, CSIIndex);