LLVM API Documentation

PPCFrameLowering.cpp
Go to the documentation of this file.
00001 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the PPC implementation of TargetFrameLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCFrameLowering.h"
00015 #include "PPCInstrBuilder.h"
00016 #include "PPCInstrInfo.h"
00017 #include "PPCMachineFunctionInfo.h"
00018 #include "PPCSubtarget.h"
00019 #include "PPCTargetMachine.h"
00020 #include "llvm/CodeGen/MachineFrameInfo.h"
00021 #include "llvm/CodeGen/MachineFunction.h"
00022 #include "llvm/CodeGen/MachineInstrBuilder.h"
00023 #include "llvm/CodeGen/MachineModuleInfo.h"
00024 #include "llvm/CodeGen/MachineRegisterInfo.h"
00025 #include "llvm/CodeGen/RegisterScavenging.h"
00026 #include "llvm/IR/Function.h"
00027 #include "llvm/Target/TargetOptions.h"
00028 
00029 using namespace llvm;
00030 
00031 /// VRRegNo - Map from a numbered VR register to its enum value.
00032 ///
00033 static const uint16_t VRRegNo[] = {
00034  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
00035  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
00036  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
00037  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
00038 };
00039 
00040 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
00041   if (STI.isDarwinABI())
00042     return STI.isPPC64() ? 16 : 8;
00043   // SVR4 ABI:
00044   return STI.isPPC64() ? 16 : 4;
00045 }
00046 
00047 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
00048   return STI.isELFv2ABI() ? 24 : 40;
00049 }
00050 
00051 static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
00052   // For the Darwin ABI:
00053   // We cannot use the TOC save slot (offset +20) in the PowerPC linkage area
00054   // for saving the frame pointer (if needed.)  While the published ABI has
00055   // not used this slot since at least MacOSX 10.2, there is older code
00056   // around that does use it, and that needs to continue to work.
00057   if (STI.isDarwinABI())
00058     return STI.isPPC64() ? -8U : -4U;
00059 
00060   // SVR4 ABI: First slot in the general register save area.
00061   return STI.isPPC64() ? -8U : -4U;
00062 }
00063 
00064 static unsigned computeLinkageSize(const PPCSubtarget &STI) {
00065   if (STI.isDarwinABI() || STI.isPPC64())
00066     return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
00067 
00068   // SVR4 ABI:
00069   return 8;
00070 }
00071 
00072 static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
00073   if (STI.isDarwinABI())
00074     return STI.isPPC64() ? -16U : -8U;
00075 
00076   // SVR4 ABI: First slot in the general register save area.
00077   return STI.isPPC64()
00078              ? -16U
00079              : (STI.getTargetMachine().getRelocationModel() == Reloc::PIC_)
00080                    ? -12U
00081                    : -8U;
00082 }
00083 
00084 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
00085     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
00086                           STI.getPlatformStackAlignment(), 0),
00087       Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
00088       TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
00089       FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
00090       LinkageSize(computeLinkageSize(Subtarget)),
00091       BasePointerSaveOffset(computeBasePointerSaveOffset(STI)) {}
00092 
00093 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
00094 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
00095     unsigned &NumEntries) const {
00096   if (Subtarget.isDarwinABI()) {
00097     NumEntries = 1;
00098     if (Subtarget.isPPC64()) {
00099       static const SpillSlot darwin64Offsets = {PPC::X31, -8};
00100       return &darwin64Offsets;
00101     } else {
00102       static const SpillSlot darwinOffsets = {PPC::R31, -4};
00103       return &darwinOffsets;
00104     }
00105   }
00106 
00107   // Early exit if not using the SVR4 ABI.
00108   if (!Subtarget.isSVR4ABI()) {
00109     NumEntries = 0;
00110     return nullptr;
00111   }
00112 
00113   // Note that the offsets here overlap, but this is fixed up in
00114   // processFunctionBeforeFrameFinalized.
00115 
00116   static const SpillSlot Offsets[] = {
00117       // Floating-point register save area offsets.
00118       {PPC::F31, -8},
00119       {PPC::F30, -16},
00120       {PPC::F29, -24},
00121       {PPC::F28, -32},
00122       {PPC::F27, -40},
00123       {PPC::F26, -48},
00124       {PPC::F25, -56},
00125       {PPC::F24, -64},
00126       {PPC::F23, -72},
00127       {PPC::F22, -80},
00128       {PPC::F21, -88},
00129       {PPC::F20, -96},
00130       {PPC::F19, -104},
00131       {PPC::F18, -112},
00132       {PPC::F17, -120},
00133       {PPC::F16, -128},
00134       {PPC::F15, -136},
00135       {PPC::F14, -144},
00136 
00137       // General register save area offsets.
00138       {PPC::R31, -4},
00139       {PPC::R30, -8},
00140       {PPC::R29, -12},
00141       {PPC::R28, -16},
00142       {PPC::R27, -20},
00143       {PPC::R26, -24},
00144       {PPC::R25, -28},
00145       {PPC::R24, -32},
00146       {PPC::R23, -36},
00147       {PPC::R22, -40},
00148       {PPC::R21, -44},
00149       {PPC::R20, -48},
00150       {PPC::R19, -52},
00151       {PPC::R18, -56},
00152       {PPC::R17, -60},
00153       {PPC::R16, -64},
00154       {PPC::R15, -68},
00155       {PPC::R14, -72},
00156 
00157       // CR save area offset.  We map each of the nonvolatile CR fields
00158       // to the slot for CR2, which is the first of the nonvolatile CR
00159       // fields to be assigned, so that we only allocate one save slot.
00160       // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
00161       {PPC::CR2, -4},
00162 
00163       // VRSAVE save area offset.
00164       {PPC::VRSAVE, -4},
00165 
00166       // Vector register save area
00167       {PPC::V31, -16},
00168       {PPC::V30, -32},
00169       {PPC::V29, -48},
00170       {PPC::V28, -64},
00171       {PPC::V27, -80},
00172       {PPC::V26, -96},
00173       {PPC::V25, -112},
00174       {PPC::V24, -128},
00175       {PPC::V23, -144},
00176       {PPC::V22, -160},
00177       {PPC::V21, -176},
00178       {PPC::V20, -192}};
00179 
00180   static const SpillSlot Offsets64[] = {
00181       // Floating-point register save area offsets.
00182       {PPC::F31, -8},
00183       {PPC::F30, -16},
00184       {PPC::F29, -24},
00185       {PPC::F28, -32},
00186       {PPC::F27, -40},
00187       {PPC::F26, -48},
00188       {PPC::F25, -56},
00189       {PPC::F24, -64},
00190       {PPC::F23, -72},
00191       {PPC::F22, -80},
00192       {PPC::F21, -88},
00193       {PPC::F20, -96},
00194       {PPC::F19, -104},
00195       {PPC::F18, -112},
00196       {PPC::F17, -120},
00197       {PPC::F16, -128},
00198       {PPC::F15, -136},
00199       {PPC::F14, -144},
00200 
00201       // General register save area offsets.
00202       {PPC::X31, -8},
00203       {PPC::X30, -16},
00204       {PPC::X29, -24},
00205       {PPC::X28, -32},
00206       {PPC::X27, -40},
00207       {PPC::X26, -48},
00208       {PPC::X25, -56},
00209       {PPC::X24, -64},
00210       {PPC::X23, -72},
00211       {PPC::X22, -80},
00212       {PPC::X21, -88},
00213       {PPC::X20, -96},
00214       {PPC::X19, -104},
00215       {PPC::X18, -112},
00216       {PPC::X17, -120},
00217       {PPC::X16, -128},
00218       {PPC::X15, -136},
00219       {PPC::X14, -144},
00220 
00221       // VRSAVE save area offset.
00222       {PPC::VRSAVE, -4},
00223 
00224       // Vector register save area
00225       {PPC::V31, -16},
00226       {PPC::V30, -32},
00227       {PPC::V29, -48},
00228       {PPC::V28, -64},
00229       {PPC::V27, -80},
00230       {PPC::V26, -96},
00231       {PPC::V25, -112},
00232       {PPC::V24, -128},
00233       {PPC::V23, -144},
00234       {PPC::V22, -160},
00235       {PPC::V21, -176},
00236       {PPC::V20, -192}};
00237 
00238   if (Subtarget.isPPC64()) {
00239     NumEntries = array_lengthof(Offsets64);
00240 
00241     return Offsets64;
00242   } else {
00243     NumEntries = array_lengthof(Offsets);
00244 
00245     return Offsets;
00246   }
00247 }
00248 
00249 /// RemoveVRSaveCode - We have found that this function does not need any code
00250 /// to manipulate the VRSAVE register, even though it uses vector registers.
00251 /// This can happen when the only registers used are known to be live in or out
00252 /// of the function.  Remove all of the VRSAVE related code from the function.
00253 /// FIXME: The removal of the code results in a compile failure at -O0 when the
00254 /// function contains a function call, as the GPR containing original VRSAVE
00255 /// contents is spilled and reloaded around the call.  Without the prolog code,
00256 /// the spill instruction refers to an undefined register.  This code needs
00257 /// to account for all uses of that GPR.
00258 static void RemoveVRSaveCode(MachineInstr *MI) {
00259   MachineBasicBlock *Entry = MI->getParent();
00260   MachineFunction *MF = Entry->getParent();
00261 
00262   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
00263   MachineBasicBlock::iterator MBBI = MI;
00264   ++MBBI;
00265   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
00266   MBBI->eraseFromParent();
00267 
00268   bool RemovedAllMTVRSAVEs = true;
00269   // See if we can find and remove the MTVRSAVE instruction from all of the
00270   // epilog blocks.
00271   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
00272     // If last instruction is a return instruction, add an epilogue
00273     if (!I->empty() && I->back().isReturn()) {
00274       bool FoundIt = false;
00275       for (MBBI = I->end(); MBBI != I->begin(); ) {
00276         --MBBI;
00277         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
00278           MBBI->eraseFromParent();  // remove it.
00279           FoundIt = true;
00280           break;
00281         }
00282       }
00283       RemovedAllMTVRSAVEs &= FoundIt;
00284     }
00285   }
00286 
00287   // If we found and removed all MTVRSAVE instructions, remove the read of
00288   // VRSAVE as well.
00289   if (RemovedAllMTVRSAVEs) {
00290     MBBI = MI;
00291     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
00292     --MBBI;
00293     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
00294     MBBI->eraseFromParent();
00295   }
00296 
00297   // Finally, nuke the UPDATE_VRSAVE.
00298   MI->eraseFromParent();
00299 }
00300 
00301 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
00302 // instruction selector.  Based on the vector registers that have been used,
00303 // transform this into the appropriate ORI instruction.
00304 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
00305   MachineFunction *MF = MI->getParent()->getParent();
00306   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00307   DebugLoc dl = MI->getDebugLoc();
00308 
00309   unsigned UsedRegMask = 0;
00310   for (unsigned i = 0; i != 32; ++i)
00311     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
00312       UsedRegMask |= 1 << (31-i);
00313 
00314   // Live in and live out values already must be in the mask, so don't bother
00315   // marking them.
00316   for (MachineRegisterInfo::livein_iterator
00317        I = MF->getRegInfo().livein_begin(),
00318        E = MF->getRegInfo().livein_end(); I != E; ++I) {
00319     unsigned RegNo = TRI->getEncodingValue(I->first);
00320     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
00321       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
00322   }
00323 
00324   // Live out registers appear as use operands on return instructions.
00325   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
00326        UsedRegMask != 0 && BI != BE; ++BI) {
00327     const MachineBasicBlock &MBB = *BI;
00328     if (MBB.empty() || !MBB.back().isReturn())
00329       continue;
00330     const MachineInstr &Ret = MBB.back();
00331     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
00332       const MachineOperand &MO = Ret.getOperand(I);
00333       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
00334         continue;
00335       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
00336       UsedRegMask &= ~(1 << (31-RegNo));
00337     }
00338   }
00339 
00340   // If no registers are used, turn this into a copy.
00341   if (UsedRegMask == 0) {
00342     // Remove all VRSAVE code.
00343     RemoveVRSaveCode(MI);
00344     return;
00345   }
00346 
00347   unsigned SrcReg = MI->getOperand(1).getReg();
00348   unsigned DstReg = MI->getOperand(0).getReg();
00349 
00350   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
00351     if (DstReg != SrcReg)
00352       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00353         .addReg(SrcReg)
00354         .addImm(UsedRegMask);
00355     else
00356       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00357         .addReg(SrcReg, RegState::Kill)
00358         .addImm(UsedRegMask);
00359   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
00360     if (DstReg != SrcReg)
00361       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00362         .addReg(SrcReg)
00363         .addImm(UsedRegMask >> 16);
00364     else
00365       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00366         .addReg(SrcReg, RegState::Kill)
00367         .addImm(UsedRegMask >> 16);
00368   } else {
00369     if (DstReg != SrcReg)
00370       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00371         .addReg(SrcReg)
00372         .addImm(UsedRegMask >> 16);
00373     else
00374       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00375         .addReg(SrcReg, RegState::Kill)
00376         .addImm(UsedRegMask >> 16);
00377 
00378     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00379       .addReg(DstReg, RegState::Kill)
00380       .addImm(UsedRegMask & 0xFFFF);
00381   }
00382 
00383   // Remove the old UPDATE_VRSAVE instruction.
00384   MI->eraseFromParent();
00385 }
00386 
00387 static bool spillsCR(const MachineFunction &MF) {
00388   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00389   return FuncInfo->isCRSpilled();
00390 }
00391 
00392 static bool spillsVRSAVE(const MachineFunction &MF) {
00393   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00394   return FuncInfo->isVRSAVESpilled();
00395 }
00396 
00397 static bool hasSpills(const MachineFunction &MF) {
00398   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00399   return FuncInfo->hasSpills();
00400 }
00401 
00402 static bool hasNonRISpills(const MachineFunction &MF) {
00403   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00404   return FuncInfo->hasNonRISpills();
00405 }
00406 
00407 /// MustSaveLR - Return true if this function requires that we save the LR
00408 /// register onto the stack in the prolog and restore it in the epilog of the
00409 /// function.
00410 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
00411   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
00412 
00413   // We need a save/restore of LR if there is any def of LR (which is
00414   // defined by calls, including the PIC setup sequence), or if there is
00415   // some use of the LR stack slot (e.g. for builtin_return_address).
00416   // (LR comes in 32 and 64 bit versions.)
00417   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
00418   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
00419 }
00420 
00421 /// determineFrameLayout - Determine the size of the frame and maximum call
00422 /// frame size.
00423 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
00424                                                 bool UpdateMF,
00425                                                 bool UseEstimate) const {
00426   MachineFrameInfo *MFI = MF.getFrameInfo();
00427 
00428   // Get the number of bytes to allocate from the FrameInfo
00429   unsigned FrameSize =
00430     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
00431 
00432   // Get stack alignments. The frame must be aligned to the greatest of these:
00433   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
00434   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
00435   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
00436 
00437   const PPCRegisterInfo *RegInfo =
00438       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00439 
00440   // If we are a leaf function, and use up to 224 bytes of stack space,
00441   // don't have a frame pointer, calls, or dynamic alloca then we do not need
00442   // to adjust the stack pointer (we fit in the Red Zone).
00443   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
00444   // stackless code if all local vars are reg-allocated.
00445   bool DisableRedZone = MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
00446   unsigned LR = RegInfo->getRARegister();
00447   if (!DisableRedZone &&
00448       (Subtarget.isPPC64() ||                      // 32-bit SVR4, no stack-
00449        !Subtarget.isSVR4ABI() ||                   //   allocated locals.
00450         FrameSize == 0) &&
00451       FrameSize <= 224 &&                          // Fits in red zone.
00452       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
00453       !MFI->adjustsStack() &&                      // No calls.
00454       !MustSaveLR(MF, LR) &&
00455       !RegInfo->hasBasePointer(MF)) { // No special alignment.
00456     // No need for frame
00457     if (UpdateMF)
00458       MFI->setStackSize(0);
00459     return 0;
00460   }
00461 
00462   // Get the maximum call frame size of all the calls.
00463   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
00464 
00465   // Maximum call frame needs to be at least big enough for linkage area.
00466   unsigned minCallFrameSize = getLinkageSize();
00467   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
00468 
00469   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
00470   // that allocations will be aligned.
00471   if (MFI->hasVarSizedObjects())
00472     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
00473 
00474   // Update maximum call frame size.
00475   if (UpdateMF)
00476     MFI->setMaxCallFrameSize(maxCallFrameSize);
00477 
00478   // Include call frame size in total.
00479   FrameSize += maxCallFrameSize;
00480 
00481   // Make sure the frame is aligned.
00482   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
00483 
00484   // Update frame info.
00485   if (UpdateMF)
00486     MFI->setStackSize(FrameSize);
00487 
00488   return FrameSize;
00489 }
00490 
00491 // hasFP - Return true if the specified function actually has a dedicated frame
00492 // pointer register.
00493 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
00494   const MachineFrameInfo *MFI = MF.getFrameInfo();
00495   // FIXME: This is pretty much broken by design: hasFP() might be called really
00496   // early, before the stack layout was calculated and thus hasFP() might return
00497   // true or false here depending on the time of call.
00498   return (MFI->getStackSize()) && needsFP(MF);
00499 }
00500 
00501 // needsFP - Return true if the specified function should have a dedicated frame
00502 // pointer register.  This is true if the function has variable sized allocas or
00503 // if frame pointer elimination is disabled.
00504 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
00505   const MachineFrameInfo *MFI = MF.getFrameInfo();
00506 
00507   // Naked functions have no stack frame pushed, so we don't have a frame
00508   // pointer.
00509   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
00510     return false;
00511 
00512   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
00513     MFI->hasVarSizedObjects() ||
00514     MFI->hasStackMap() || MFI->hasPatchPoint() ||
00515     (MF.getTarget().Options.GuaranteedTailCallOpt &&
00516      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
00517 }
00518 
00519 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
00520   bool is31 = needsFP(MF);
00521   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
00522   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
00523 
00524   const PPCRegisterInfo *RegInfo =
00525       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00526   bool HasBP = RegInfo->hasBasePointer(MF);
00527   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
00528   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
00529 
00530   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
00531        BI != BE; ++BI)
00532     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
00533       --MBBI;
00534       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
00535         MachineOperand &MO = MBBI->getOperand(I);
00536         if (!MO.isReg())
00537           continue;
00538 
00539         switch (MO.getReg()) {
00540         case PPC::FP:
00541           MO.setReg(FPReg);
00542           break;
00543         case PPC::FP8:
00544           MO.setReg(FP8Reg);
00545           break;
00546         case PPC::BP:
00547           MO.setReg(BPReg);
00548           break;
00549         case PPC::BP8:
00550           MO.setReg(BP8Reg);
00551           break;
00552 
00553         }
00554       }
00555     }
00556 }
00557 
00558 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
00559   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
00560   MachineBasicBlock::iterator MBBI = MBB.begin();
00561   MachineFrameInfo *MFI = MF.getFrameInfo();
00562   const PPCInstrInfo &TII =
00563       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
00564   const PPCRegisterInfo *RegInfo =
00565       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00566 
00567   MachineModuleInfo &MMI = MF.getMMI();
00568   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00569   DebugLoc dl;
00570   bool needsCFI = MMI.hasDebugInfo() ||
00571     MF.getFunction()->needsUnwindTableEntry();
00572 
00573   // Get processor type.
00574   bool isPPC64 = Subtarget.isPPC64();
00575   // Get the ABI.
00576   bool isSVR4ABI = Subtarget.isSVR4ABI();
00577   bool isELFv2ABI = Subtarget.isELFv2ABI();
00578   assert((Subtarget.isDarwinABI() || isSVR4ABI) &&
00579          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
00580 
00581   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
00582   // process it.
00583   if (!isSVR4ABI)
00584     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
00585       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
00586         HandleVRSaveUpdate(MBBI, TII);
00587         break;
00588       }
00589     }
00590 
00591   // Move MBBI back to the beginning of the function.
00592   MBBI = MBB.begin();
00593 
00594   // Work out frame sizes.
00595   unsigned FrameSize = determineFrameLayout(MF);
00596   int NegFrameSize = -FrameSize;
00597   if (!isInt<32>(NegFrameSize))
00598     llvm_unreachable("Unhandled stack size!");
00599 
00600   if (MFI->isFrameAddressTaken())
00601     replaceFPWithRealFP(MF);
00602 
00603   // Check if the link register (LR) must be saved.
00604   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
00605   bool MustSaveLR = FI->mustSaveLR();
00606   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
00607   // Do we have a frame pointer and/or base pointer for this function?
00608   bool HasFP = hasFP(MF);
00609   bool HasBP = RegInfo->hasBasePointer(MF);
00610 
00611   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
00612   unsigned BPReg       = RegInfo->getBaseRegister(MF);
00613   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
00614   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
00615   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
00616   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
00617   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
00618   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
00619                                                 : PPC::MFLR );
00620   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
00621                                                  : PPC::STW );
00622   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
00623                                                      : PPC::STWU );
00624   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
00625                                                         : PPC::STWUX);
00626   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
00627                                                           : PPC::LIS );
00628   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
00629                                                  : PPC::ORI );
00630   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
00631                                               : PPC::OR );
00632   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
00633                                                             : PPC::SUBFC);
00634   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
00635                                                                : PPC::SUBFIC);
00636 
00637   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
00638   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
00639   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
00640   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
00641   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
00642          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
00643 
00644   int LROffset = getReturnSaveOffset();
00645 
00646   int FPOffset = 0;
00647   if (HasFP) {
00648     if (isSVR4ABI) {
00649       MachineFrameInfo *FFI = MF.getFrameInfo();
00650       int FPIndex = FI->getFramePointerSaveIndex();
00651       assert(FPIndex && "No Frame Pointer Save Slot!");
00652       FPOffset = FFI->getObjectOffset(FPIndex);
00653     } else {
00654       FPOffset = getFramePointerSaveOffset();
00655     }
00656   }
00657 
00658   int BPOffset = 0;
00659   if (HasBP) {
00660     if (isSVR4ABI) {
00661       MachineFrameInfo *FFI = MF.getFrameInfo();
00662       int BPIndex = FI->getBasePointerSaveIndex();
00663       assert(BPIndex && "No Base Pointer Save Slot!");
00664       BPOffset = FFI->getObjectOffset(BPIndex);
00665     } else {
00666       BPOffset = getBasePointerSaveOffset();
00667     }
00668   }
00669 
00670   int PBPOffset = 0;
00671   if (FI->usesPICBase()) {
00672     MachineFrameInfo *FFI = MF.getFrameInfo();
00673     int PBPIndex = FI->getPICBasePointerSaveIndex();
00674     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
00675     PBPOffset = FFI->getObjectOffset(PBPIndex);
00676   }
00677 
00678   // Get stack alignments.
00679   unsigned MaxAlign = MFI->getMaxAlignment();
00680   if (HasBP && MaxAlign > 1)
00681     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
00682            "Invalid alignment!");
00683 
00684   // Frames of 32KB & larger require special handling because they cannot be
00685   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
00686   bool isLargeFrame = !isInt<16>(NegFrameSize);
00687 
00688   if (MustSaveLR)
00689     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
00690 
00691   assert((isPPC64 || MustSaveCRs.empty()) &&
00692          "Prologue CR saving supported only in 64-bit mode");
00693 
00694   if (!MustSaveCRs.empty()) { // will only occur for PPC64
00695     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
00696     // If only one or two CR fields are clobbered, it could be more
00697     // efficient to use mfocrf to selectively save just those fields.
00698     MachineInstrBuilder MIB =
00699       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
00700     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
00701       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
00702   }
00703 
00704   if (HasFP)
00705     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00706     BuildMI(MBB, MBBI, dl, StoreInst)
00707       .addReg(FPReg)
00708       .addImm(FPOffset)
00709       .addReg(SPReg);
00710 
00711   if (FI->usesPICBase())
00712     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00713     BuildMI(MBB, MBBI, dl, StoreInst)
00714       .addReg(PPC::R30)
00715       .addImm(PBPOffset)
00716       .addReg(SPReg);
00717 
00718   if (HasBP)
00719     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00720     BuildMI(MBB, MBBI, dl, StoreInst)
00721       .addReg(BPReg)
00722       .addImm(BPOffset)
00723       .addReg(SPReg);
00724 
00725   if (MustSaveLR)
00726     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00727     BuildMI(MBB, MBBI, dl, StoreInst)
00728       .addReg(ScratchReg)
00729       .addImm(LROffset)
00730       .addReg(SPReg);
00731 
00732   if (!MustSaveCRs.empty()) // will only occur for PPC64
00733     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
00734       .addReg(TempReg, getKillRegState(true))
00735       .addImm(8)
00736       .addReg(SPReg);
00737 
00738   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
00739   if (!FrameSize) return;
00740 
00741   // Adjust stack pointer: r1 += NegFrameSize.
00742   // If there is a preferred stack alignment, align R1 now
00743 
00744   if (HasBP) {
00745     // Save a copy of r1 as the base pointer.
00746     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
00747       .addReg(SPReg)
00748       .addReg(SPReg);
00749   }
00750 
00751   if (HasBP && MaxAlign > 1) {
00752     if (isPPC64)
00753       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
00754         .addReg(SPReg)
00755         .addImm(0)
00756         .addImm(64 - Log2_32(MaxAlign));
00757     else // PPC32...
00758       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
00759         .addReg(SPReg)
00760         .addImm(0)
00761         .addImm(32 - Log2_32(MaxAlign))
00762         .addImm(31);
00763     if (!isLargeFrame) {
00764       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
00765         .addReg(ScratchReg, RegState::Kill)
00766         .addImm(NegFrameSize);
00767     } else {
00768       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
00769         .addImm(NegFrameSize >> 16);
00770       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
00771         .addReg(TempReg, RegState::Kill)
00772         .addImm(NegFrameSize & 0xFFFF);
00773       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
00774         .addReg(ScratchReg, RegState::Kill)
00775         .addReg(TempReg, RegState::Kill);
00776     }
00777     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00778       .addReg(SPReg, RegState::Kill)
00779       .addReg(SPReg)
00780       .addReg(ScratchReg);
00781 
00782   } else if (!isLargeFrame) {
00783     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
00784       .addReg(SPReg)
00785       .addImm(NegFrameSize)
00786       .addReg(SPReg);
00787 
00788   } else {
00789     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
00790       .addImm(NegFrameSize >> 16);
00791     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
00792       .addReg(ScratchReg, RegState::Kill)
00793       .addImm(NegFrameSize & 0xFFFF);
00794     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00795       .addReg(SPReg, RegState::Kill)
00796       .addReg(SPReg)
00797       .addReg(ScratchReg);
00798   }
00799 
00800   // Add Call Frame Information for the instructions we generated above.
00801   if (needsCFI) {
00802     unsigned CFIIndex;
00803 
00804     if (HasBP) {
00805       // Define CFA in terms of BP. Do this in preference to using FP/SP,
00806       // because if the stack needed aligning then CFA won't be at a fixed
00807       // offset from FP/SP.
00808       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00809       CFIIndex = MMI.addFrameInst(
00810           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00811     } else {
00812       // Adjust the definition of CFA to account for the change in SP.
00813       assert(NegFrameSize);
00814       CFIIndex = MMI.addFrameInst(
00815           MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
00816     }
00817     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00818         .addCFIIndex(CFIIndex);
00819 
00820     if (HasFP) {
00821       // Describe where FP was saved, at a fixed offset from CFA.
00822       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00823       CFIIndex = MMI.addFrameInst(
00824           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
00825       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00826           .addCFIIndex(CFIIndex);
00827     }
00828 
00829     if (FI->usesPICBase()) {
00830       // Describe where FP was saved, at a fixed offset from CFA.
00831       unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
00832       CFIIndex = MMI.addFrameInst(
00833           MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
00834       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00835           .addCFIIndex(CFIIndex);
00836     }
00837 
00838     if (HasBP) {
00839       // Describe where BP was saved, at a fixed offset from CFA.
00840       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00841       CFIIndex = MMI.addFrameInst(
00842           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
00843       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00844           .addCFIIndex(CFIIndex);
00845     }
00846 
00847     if (MustSaveLR) {
00848       // Describe where LR was saved, at a fixed offset from CFA.
00849       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
00850       CFIIndex = MMI.addFrameInst(
00851           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
00852       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00853           .addCFIIndex(CFIIndex);
00854     }
00855   }
00856 
00857   // If there is a frame pointer, copy R1 into R31
00858   if (HasFP) {
00859     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
00860       .addReg(SPReg)
00861       .addReg(SPReg);
00862 
00863     if (!HasBP && needsCFI) {
00864       // Change the definition of CFA from SP+offset to FP+offset, because SP
00865       // will change at every alloca.
00866       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00867       unsigned CFIIndex = MMI.addFrameInst(
00868           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00869 
00870       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00871           .addCFIIndex(CFIIndex);
00872     }
00873   }
00874 
00875   if (needsCFI) {
00876     // Describe where callee saved registers were saved, at fixed offsets from
00877     // CFA.
00878     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00879     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
00880       unsigned Reg = CSI[I].getReg();
00881       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
00882 
00883       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
00884       // subregisters of CR2. We just need to emit a move of CR2.
00885       if (PPC::CRBITRCRegClass.contains(Reg))
00886         continue;
00887 
00888       // For SVR4, don't emit a move for the CR spill slot if we haven't
00889       // spilled CRs.
00890       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
00891           && MustSaveCRs.empty())
00892         continue;
00893 
00894       // For 64-bit SVR4 when we have spilled CRs, the spill location
00895       // is SP+8, not a frame-relative slot.
00896       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
00897         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
00898         // the whole CR word.  In the ELFv2 ABI, every CR that was
00899         // actually saved gets its own CFI record.
00900         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
00901         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00902             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
00903         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00904             .addCFIIndex(CFIIndex);
00905         continue;
00906       }
00907 
00908       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
00909       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00910           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
00911       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00912           .addCFIIndex(CFIIndex);
00913     }
00914   }
00915 }
00916 
00917 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
00918                                 MachineBasicBlock &MBB) const {
00919   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
00920   assert(MBBI != MBB.end() && "Returning block has no terminator");
00921   const PPCInstrInfo &TII =
00922       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
00923   const PPCRegisterInfo *RegInfo =
00924       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00925 
00926   unsigned RetOpcode = MBBI->getOpcode();
00927   DebugLoc dl;
00928 
00929   assert((RetOpcode == PPC::BLR ||
00930           RetOpcode == PPC::BLR8 ||
00931           RetOpcode == PPC::TCRETURNri ||
00932           RetOpcode == PPC::TCRETURNdi ||
00933           RetOpcode == PPC::TCRETURNai ||
00934           RetOpcode == PPC::TCRETURNri8 ||
00935           RetOpcode == PPC::TCRETURNdi8 ||
00936           RetOpcode == PPC::TCRETURNai8) &&
00937          "Can only insert epilog into returning blocks");
00938 
00939   // Get alignment info so we know how to restore the SP.
00940   const MachineFrameInfo *MFI = MF.getFrameInfo();
00941 
00942   // Get the number of bytes allocated from the FrameInfo.
00943   int FrameSize = MFI->getStackSize();
00944 
00945   // Get processor type.
00946   bool isPPC64 = Subtarget.isPPC64();
00947   // Get the ABI.
00948   bool isSVR4ABI = Subtarget.isSVR4ABI();
00949 
00950   // Check if the link register (LR) has been saved.
00951   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
00952   bool MustSaveLR = FI->mustSaveLR();
00953   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
00954   // Do we have a frame pointer and/or base pointer for this function?
00955   bool HasFP = hasFP(MF);
00956   bool HasBP = RegInfo->hasBasePointer(MF);
00957 
00958   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
00959   unsigned BPReg      = RegInfo->getBaseRegister(MF);
00960   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
00961   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
00962   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
00963   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
00964                                                  : PPC::MTLR );
00965   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
00966                                                  : PPC::LWZ );
00967   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
00968                                                            : PPC::LIS );
00969   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
00970                                                   : PPC::ORI );
00971   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
00972                                                    : PPC::ADDI );
00973   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
00974                                                 : PPC::ADD4 );
00975 
00976   int LROffset = getReturnSaveOffset();
00977 
00978   int FPOffset = 0;
00979   if (HasFP) {
00980     if (isSVR4ABI) {
00981       MachineFrameInfo *FFI = MF.getFrameInfo();
00982       int FPIndex = FI->getFramePointerSaveIndex();
00983       assert(FPIndex && "No Frame Pointer Save Slot!");
00984       FPOffset = FFI->getObjectOffset(FPIndex);
00985     } else {
00986       FPOffset = getFramePointerSaveOffset();
00987     }
00988   }
00989 
00990   int BPOffset = 0;
00991   if (HasBP) {
00992     if (isSVR4ABI) {
00993       MachineFrameInfo *FFI = MF.getFrameInfo();
00994       int BPIndex = FI->getBasePointerSaveIndex();
00995       assert(BPIndex && "No Base Pointer Save Slot!");
00996       BPOffset = FFI->getObjectOffset(BPIndex);
00997     } else {
00998       BPOffset = getBasePointerSaveOffset();
00999     }
01000   }
01001 
01002   int PBPOffset = 0;
01003   if (FI->usesPICBase()) {
01004     MachineFrameInfo *FFI = MF.getFrameInfo();
01005     int PBPIndex = FI->getPICBasePointerSaveIndex();
01006     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
01007     PBPOffset = FFI->getObjectOffset(PBPIndex);
01008   }
01009 
01010   bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
01011     RetOpcode == PPC::TCRETURNdi ||
01012     RetOpcode == PPC::TCRETURNai ||
01013     RetOpcode == PPC::TCRETURNri8 ||
01014     RetOpcode == PPC::TCRETURNdi8 ||
01015     RetOpcode == PPC::TCRETURNai8;
01016 
01017   if (UsesTCRet) {
01018     int MaxTCRetDelta = FI->getTailCallSPDelta();
01019     MachineOperand &StackAdjust = MBBI->getOperand(1);
01020     assert(StackAdjust.isImm() && "Expecting immediate value.");
01021     // Adjust stack pointer.
01022     int StackAdj = StackAdjust.getImm();
01023     int Delta = StackAdj - MaxTCRetDelta;
01024     assert((Delta >= 0) && "Delta must be positive");
01025     if (MaxTCRetDelta>0)
01026       FrameSize += (StackAdj +Delta);
01027     else
01028       FrameSize += StackAdj;
01029   }
01030 
01031   // Frames of 32KB & larger require special handling because they cannot be
01032   // indexed into with a simple LD/LWZ immediate offset operand.
01033   bool isLargeFrame = !isInt<16>(FrameSize);
01034 
01035   if (FrameSize) {
01036     // In the prologue, the loaded (or persistent) stack pointer value is offset
01037     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
01038 
01039     // If this function contained a fastcc call and GuaranteedTailCallOpt is
01040     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
01041     // call which invalidates the stack pointer value in SP(0). So we use the
01042     // value of R31 in this case.
01043     if (FI->hasFastCall()) {
01044       assert(HasFP && "Expecting a valid frame pointer.");
01045       if (!isLargeFrame) {
01046         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01047           .addReg(FPReg).addImm(FrameSize);
01048       } else {
01049         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
01050           .addImm(FrameSize >> 16);
01051         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
01052           .addReg(ScratchReg, RegState::Kill)
01053           .addImm(FrameSize & 0xFFFF);
01054         BuildMI(MBB, MBBI, dl, AddInst)
01055           .addReg(SPReg)
01056           .addReg(FPReg)
01057           .addReg(ScratchReg);
01058       }
01059     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
01060       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01061         .addReg(SPReg)
01062         .addImm(FrameSize);
01063     } else {
01064       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
01065         .addImm(0)
01066         .addReg(SPReg);
01067     }
01068 
01069   }
01070 
01071   if (MustSaveLR)
01072     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
01073       .addImm(LROffset)
01074       .addReg(SPReg);
01075 
01076   assert((isPPC64 || MustSaveCRs.empty()) &&
01077          "Epilogue CR restoring supported only in 64-bit mode");
01078 
01079   if (!MustSaveCRs.empty()) // will only occur for PPC64
01080     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
01081       .addImm(8)
01082       .addReg(SPReg);
01083 
01084   if (HasFP)
01085     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
01086       .addImm(FPOffset)
01087       .addReg(SPReg);
01088 
01089   if (FI->usesPICBase())
01090     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
01091     BuildMI(MBB, MBBI, dl, LoadInst)
01092       .addReg(PPC::R30)
01093       .addImm(PBPOffset)
01094       .addReg(SPReg);
01095 
01096   if (HasBP)
01097     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
01098       .addImm(BPOffset)
01099       .addReg(SPReg);
01100 
01101   if (!MustSaveCRs.empty()) // will only occur for PPC64
01102     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
01103       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
01104         .addReg(TempReg, getKillRegState(i == e-1));
01105 
01106   if (MustSaveLR)
01107     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
01108 
01109   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
01110   // call optimization
01111   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01112       (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
01113       MF.getFunction()->getCallingConv() == CallingConv::Fast) {
01114      PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01115      unsigned CallerAllocatedAmt = FI->getMinReservedArea();
01116 
01117      if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
01118        BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01119          .addReg(SPReg).addImm(CallerAllocatedAmt);
01120      } else {
01121        BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
01122           .addImm(CallerAllocatedAmt >> 16);
01123        BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
01124           .addReg(ScratchReg, RegState::Kill)
01125           .addImm(CallerAllocatedAmt & 0xFFFF);
01126        BuildMI(MBB, MBBI, dl, AddInst)
01127           .addReg(SPReg)
01128           .addReg(FPReg)
01129           .addReg(ScratchReg);
01130      }
01131   } else if (RetOpcode == PPC::TCRETURNdi) {
01132     MBBI = MBB.getLastNonDebugInstr();
01133     MachineOperand &JumpTarget = MBBI->getOperand(0);
01134     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
01135       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01136   } else if (RetOpcode == PPC::TCRETURNri) {
01137     MBBI = MBB.getLastNonDebugInstr();
01138     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01139     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
01140   } else if (RetOpcode == PPC::TCRETURNai) {
01141     MBBI = MBB.getLastNonDebugInstr();
01142     MachineOperand &JumpTarget = MBBI->getOperand(0);
01143     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
01144   } else if (RetOpcode == PPC::TCRETURNdi8) {
01145     MBBI = MBB.getLastNonDebugInstr();
01146     MachineOperand &JumpTarget = MBBI->getOperand(0);
01147     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
01148       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01149   } else if (RetOpcode == PPC::TCRETURNri8) {
01150     MBBI = MBB.getLastNonDebugInstr();
01151     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01152     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
01153   } else if (RetOpcode == PPC::TCRETURNai8) {
01154     MBBI = MBB.getLastNonDebugInstr();
01155     MachineOperand &JumpTarget = MBBI->getOperand(0);
01156     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
01157   }
01158 }
01159 
01160 void
01161 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
01162                                                    RegScavenger *) const {
01163   const PPCRegisterInfo *RegInfo =
01164       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
01165 
01166   //  Save and clear the LR state.
01167   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01168   unsigned LR = RegInfo->getRARegister();
01169   FI->setMustSaveLR(MustSaveLR(MF, LR));
01170   MachineRegisterInfo &MRI = MF.getRegInfo();
01171   MRI.setPhysRegUnused(LR);
01172 
01173   //  Save R31 if necessary
01174   int FPSI = FI->getFramePointerSaveIndex();
01175   bool isPPC64 = Subtarget.isPPC64();
01176   bool isDarwinABI  = Subtarget.isDarwinABI();
01177   MachineFrameInfo *MFI = MF.getFrameInfo();
01178 
01179   // If the frame pointer save index hasn't been defined yet.
01180   if (!FPSI && needsFP(MF)) {
01181     // Find out what the fix offset of the frame pointer save area.
01182     int FPOffset = getFramePointerSaveOffset();
01183     // Allocate the frame index for frame pointer save area.
01184     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
01185     // Save the result.
01186     FI->setFramePointerSaveIndex(FPSI);
01187   }
01188 
01189   int BPSI = FI->getBasePointerSaveIndex();
01190   if (!BPSI && RegInfo->hasBasePointer(MF)) {
01191     int BPOffset = getBasePointerSaveOffset();
01192     // Allocate the frame index for the base pointer save area.
01193     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
01194     // Save the result.
01195     FI->setBasePointerSaveIndex(BPSI);
01196   }
01197 
01198   // Reserve stack space for the PIC Base register (R30).
01199   // Only used in SVR4 32-bit.
01200   if (FI->usesPICBase()) {
01201     int PBPSI = FI->getPICBasePointerSaveIndex();
01202     PBPSI = MFI->CreateFixedObject(4, -8, true);
01203     FI->setPICBasePointerSaveIndex(PBPSI);
01204   }
01205 
01206   // Reserve stack space to move the linkage area to in case of a tail call.
01207   int TCSPDelta = 0;
01208   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01209       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
01210     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
01211   }
01212 
01213   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
01214   // function uses CR 2, 3, or 4.
01215   if (!isPPC64 && !isDarwinABI &&
01216       (MRI.isPhysRegUsed(PPC::CR2) ||
01217        MRI.isPhysRegUsed(PPC::CR3) ||
01218        MRI.isPhysRegUsed(PPC::CR4))) {
01219     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
01220     FI->setCRSpillFrameIndex(FrameIdx);
01221   }
01222 }
01223 
01224 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
01225                                                        RegScavenger *RS) const {
01226   // Early exit if not using the SVR4 ABI.
01227   if (!Subtarget.isSVR4ABI()) {
01228     addScavengingSpillSlot(MF, RS);
01229     return;
01230   }
01231 
01232   // Get callee saved register information.
01233   MachineFrameInfo *FFI = MF.getFrameInfo();
01234   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
01235 
01236   // Early exit if no callee saved registers are modified!
01237   if (CSI.empty() && !needsFP(MF)) {
01238     addScavengingSpillSlot(MF, RS);
01239     return;
01240   }
01241 
01242   unsigned MinGPR = PPC::R31;
01243   unsigned MinG8R = PPC::X31;
01244   unsigned MinFPR = PPC::F31;
01245   unsigned MinVR = PPC::V31;
01246 
01247   bool HasGPSaveArea = false;
01248   bool HasG8SaveArea = false;
01249   bool HasFPSaveArea = false;
01250   bool HasVRSAVESaveArea = false;
01251   bool HasVRSaveArea = false;
01252 
01253   SmallVector<CalleeSavedInfo, 18> GPRegs;
01254   SmallVector<CalleeSavedInfo, 18> G8Regs;
01255   SmallVector<CalleeSavedInfo, 18> FPRegs;
01256   SmallVector<CalleeSavedInfo, 18> VRegs;
01257 
01258   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01259     unsigned Reg = CSI[i].getReg();
01260     if (PPC::GPRCRegClass.contains(Reg)) {
01261       HasGPSaveArea = true;
01262 
01263       GPRegs.push_back(CSI[i]);
01264 
01265       if (Reg < MinGPR) {
01266         MinGPR = Reg;
01267       }
01268     } else if (PPC::G8RCRegClass.contains(Reg)) {
01269       HasG8SaveArea = true;
01270 
01271       G8Regs.push_back(CSI[i]);
01272 
01273       if (Reg < MinG8R) {
01274         MinG8R = Reg;
01275       }
01276     } else if (PPC::F8RCRegClass.contains(Reg)) {
01277       HasFPSaveArea = true;
01278 
01279       FPRegs.push_back(CSI[i]);
01280 
01281       if (Reg < MinFPR) {
01282         MinFPR = Reg;
01283       }
01284     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
01285                PPC::CRRCRegClass.contains(Reg)) {
01286       ; // do nothing, as we already know whether CRs are spilled
01287     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
01288       HasVRSAVESaveArea = true;
01289     } else if (PPC::VRRCRegClass.contains(Reg)) {
01290       HasVRSaveArea = true;
01291 
01292       VRegs.push_back(CSI[i]);
01293 
01294       if (Reg < MinVR) {
01295         MinVR = Reg;
01296       }
01297     } else {
01298       llvm_unreachable("Unknown RegisterClass!");
01299     }
01300   }
01301 
01302   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
01303   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
01304 
01305   int64_t LowerBound = 0;
01306 
01307   // Take into account stack space reserved for tail calls.
01308   int TCSPDelta = 0;
01309   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01310       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
01311     LowerBound = TCSPDelta;
01312   }
01313 
01314   // The Floating-point register save area is right below the back chain word
01315   // of the previous stack frame.
01316   if (HasFPSaveArea) {
01317     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
01318       int FI = FPRegs[i].getFrameIdx();
01319 
01320       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01321     }
01322 
01323     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
01324   }
01325 
01326   // Check whether the frame pointer register is allocated. If so, make sure it
01327   // is spilled to the correct offset.
01328   if (needsFP(MF)) {
01329     HasGPSaveArea = true;
01330 
01331     int FI = PFI->getFramePointerSaveIndex();
01332     assert(FI && "No Frame Pointer Save Slot!");
01333 
01334     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01335   }
01336 
01337   if (PFI->usesPICBase()) {
01338     HasGPSaveArea = true;
01339 
01340     int FI = PFI->getPICBasePointerSaveIndex();
01341     assert(FI && "No PIC Base Pointer Save Slot!");
01342 
01343     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01344   }
01345 
01346   const PPCRegisterInfo *RegInfo =
01347       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
01348   if (RegInfo->hasBasePointer(MF)) {
01349     HasGPSaveArea = true;
01350 
01351     int FI = PFI->getBasePointerSaveIndex();
01352     assert(FI && "No Base Pointer Save Slot!");
01353 
01354     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01355   }
01356 
01357   // General register save area starts right below the Floating-point
01358   // register save area.
01359   if (HasGPSaveArea || HasG8SaveArea) {
01360     // Move general register save area spill slots down, taking into account
01361     // the size of the Floating-point register save area.
01362     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
01363       int FI = GPRegs[i].getFrameIdx();
01364 
01365       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01366     }
01367 
01368     // Move general register save area spill slots down, taking into account
01369     // the size of the Floating-point register save area.
01370     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
01371       int FI = G8Regs[i].getFrameIdx();
01372 
01373       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01374     }
01375 
01376     unsigned MinReg =
01377       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
01378                          TRI->getEncodingValue(MinG8R));
01379 
01380     if (Subtarget.isPPC64()) {
01381       LowerBound -= (31 - MinReg + 1) * 8;
01382     } else {
01383       LowerBound -= (31 - MinReg + 1) * 4;
01384     }
01385   }
01386 
01387   // For 32-bit only, the CR save area is below the general register
01388   // save area.  For 64-bit SVR4, the CR save area is addressed relative
01389   // to the stack pointer and hence does not need an adjustment here.
01390   // Only CR2 (the first nonvolatile spilled) has an associated frame
01391   // index so that we have a single uniform save area.
01392   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
01393     // Adjust the frame index of the CR spill slot.
01394     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01395       unsigned Reg = CSI[i].getReg();
01396 
01397       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
01398           // Leave Darwin logic as-is.
01399           || (!Subtarget.isSVR4ABI() &&
01400               (PPC::CRBITRCRegClass.contains(Reg) ||
01401                PPC::CRRCRegClass.contains(Reg)))) {
01402         int FI = CSI[i].getFrameIdx();
01403 
01404         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01405       }
01406     }
01407 
01408     LowerBound -= 4; // The CR save area is always 4 bytes long.
01409   }
01410 
01411   if (HasVRSAVESaveArea) {
01412     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
01413     //             which have the VRSAVE register class?
01414     // Adjust the frame index of the VRSAVE spill slot.
01415     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01416       unsigned Reg = CSI[i].getReg();
01417 
01418       if (PPC::VRSAVERCRegClass.contains(Reg)) {
01419         int FI = CSI[i].getFrameIdx();
01420 
01421         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01422       }
01423     }
01424 
01425     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
01426   }
01427 
01428   if (HasVRSaveArea) {
01429     // Insert alignment padding, we need 16-byte alignment.
01430     LowerBound = (LowerBound - 15) & ~(15);
01431 
01432     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
01433       int FI = VRegs[i].getFrameIdx();
01434 
01435       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01436     }
01437   }
01438 
01439   addScavengingSpillSlot(MF, RS);
01440 }
01441 
01442 void
01443 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
01444                                          RegScavenger *RS) const {
01445   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
01446   // a large stack, which will require scavenging a register to materialize a
01447   // large offset.
01448 
01449   // We need to have a scavenger spill slot for spills if the frame size is
01450   // large. In case there is no free register for large-offset addressing,
01451   // this slot is used for the necessary emergency spill. Also, we need the
01452   // slot for dynamic stack allocations.
01453 
01454   // The scavenger might be invoked if the frame offset does not fit into
01455   // the 16-bit immediate. We don't know the complete frame size here
01456   // because we've not yet computed callee-saved register spills or the
01457   // needed alignment padding.
01458   unsigned StackSize = determineFrameLayout(MF, false, true);
01459   MachineFrameInfo *MFI = MF.getFrameInfo();
01460   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
01461       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
01462     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
01463     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
01464     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
01465     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01466                                                        RC->getAlignment(),
01467                                                        false));
01468 
01469     // Might we have over-aligned allocas?
01470     bool HasAlVars = MFI->hasVarSizedObjects() &&
01471                      MFI->getMaxAlignment() > getStackAlignment();
01472 
01473     // These kinds of spills might need two registers.
01474     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
01475       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01476                                                          RC->getAlignment(),
01477                                                          false));
01478 
01479   }
01480 }
01481 
01482 bool
01483 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
01484                                      MachineBasicBlock::iterator MI,
01485                                      const std::vector<CalleeSavedInfo> &CSI,
01486                                      const TargetRegisterInfo *TRI) const {
01487 
01488   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01489   // Return false otherwise to maintain pre-existing behavior.
01490   if (!Subtarget.isSVR4ABI())
01491     return false;
01492 
01493   MachineFunction *MF = MBB.getParent();
01494   const PPCInstrInfo &TII =
01495       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
01496   DebugLoc DL;
01497   bool CRSpilled = false;
01498   MachineInstrBuilder CRMIB;
01499 
01500   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01501     unsigned Reg = CSI[i].getReg();
01502     // Only Darwin actually uses the VRSAVE register, but it can still appear
01503     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01504     // Darwin, ignore it.
01505     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01506       continue;
01507 
01508     // CR2 through CR4 are the nonvolatile CR fields.
01509     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
01510 
01511     // Add the callee-saved register as live-in; it's killed at the spill.
01512     MBB.addLiveIn(Reg);
01513 
01514     if (CRSpilled && IsCRField) {
01515       CRMIB.addReg(Reg, RegState::ImplicitKill);
01516       continue;
01517     }
01518 
01519     // Insert the spill to the stack frame.
01520     if (IsCRField) {
01521       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
01522       if (Subtarget.isPPC64()) {
01523         // The actual spill will happen at the start of the prologue.
01524         FuncInfo->addMustSaveCR(Reg);
01525       } else {
01526         CRSpilled = true;
01527         FuncInfo->setSpillsCR();
01528 
01529         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
01530         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
01531         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
01532                   .addReg(Reg, RegState::ImplicitKill);
01533 
01534         MBB.insert(MI, CRMIB);
01535         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
01536                                          .addReg(PPC::R12,
01537                                                  getKillRegState(true)),
01538                                          CSI[i].getFrameIdx()));
01539       }
01540     } else {
01541       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01542       TII.storeRegToStackSlot(MBB, MI, Reg, true,
01543                               CSI[i].getFrameIdx(), RC, TRI);
01544     }
01545   }
01546   return true;
01547 }
01548 
01549 static void
01550 restoreCRs(bool isPPC64, bool is31,
01551            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
01552            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01553            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
01554 
01555   MachineFunction *MF = MBB.getParent();
01556   const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
01557   DebugLoc DL;
01558   unsigned RestoreOp, MoveReg;
01559 
01560   if (isPPC64)
01561     // This is handled during epilogue generation.
01562     return;
01563   else {
01564     // 32-bit:  FP-relative
01565     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
01566                                              PPC::R12),
01567                                      CSI[CSIIndex].getFrameIdx()));
01568     RestoreOp = PPC::MTOCRF;
01569     MoveReg = PPC::R12;
01570   }
01571 
01572   if (CR2Spilled)
01573     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
01574                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
01575 
01576   if (CR3Spilled)
01577     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
01578                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
01579 
01580   if (CR4Spilled)
01581     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
01582                .addReg(MoveReg, getKillRegState(true)));
01583 }
01584 
01585 void PPCFrameLowering::
01586 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01587                               MachineBasicBlock::iterator I) const {
01588   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
01589   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01590       I->getOpcode() == PPC::ADJCALLSTACKUP) {
01591     // Add (actually subtract) back the amount the callee popped on return.
01592     if (int CalleeAmt =  I->getOperand(1).getImm()) {
01593       bool is64Bit = Subtarget.isPPC64();
01594       CalleeAmt *= -1;
01595       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
01596       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
01597       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
01598       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
01599       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
01600       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
01601       MachineInstr *MI = I;
01602       DebugLoc dl = MI->getDebugLoc();
01603 
01604       if (isInt<16>(CalleeAmt)) {
01605         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
01606           .addReg(StackReg, RegState::Kill)
01607           .addImm(CalleeAmt);
01608       } else {
01609         MachineBasicBlock::iterator MBBI = I;
01610         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
01611           .addImm(CalleeAmt >> 16);
01612         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
01613           .addReg(TmpReg, RegState::Kill)
01614           .addImm(CalleeAmt & 0xFFFF);
01615         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
01616           .addReg(StackReg, RegState::Kill)
01617           .addReg(TmpReg);
01618       }
01619     }
01620   }
01621   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
01622   MBB.erase(I);
01623 }
01624 
01625 bool
01626 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01627                                         MachineBasicBlock::iterator MI,
01628                                         const std::vector<CalleeSavedInfo> &CSI,
01629                                         const TargetRegisterInfo *TRI) const {
01630 
01631   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01632   // Return false otherwise to maintain pre-existing behavior.
01633   if (!Subtarget.isSVR4ABI())
01634     return false;
01635 
01636   MachineFunction *MF = MBB.getParent();
01637   const PPCInstrInfo &TII =
01638       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
01639   bool CR2Spilled = false;
01640   bool CR3Spilled = false;
01641   bool CR4Spilled = false;
01642   unsigned CSIIndex = 0;
01643 
01644   // Initialize insertion-point logic; we will be restoring in reverse
01645   // order of spill.
01646   MachineBasicBlock::iterator I = MI, BeforeI = I;
01647   bool AtStart = I == MBB.begin();
01648 
01649   if (!AtStart)
01650     --BeforeI;
01651 
01652   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01653     unsigned Reg = CSI[i].getReg();
01654 
01655     // Only Darwin actually uses the VRSAVE register, but it can still appear
01656     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01657     // Darwin, ignore it.
01658     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01659       continue;
01660 
01661     if (Reg == PPC::CR2) {
01662       CR2Spilled = true;
01663       // The spill slot is associated only with CR2, which is the
01664       // first nonvolatile spilled.  Save it here.
01665       CSIIndex = i;
01666       continue;
01667     } else if (Reg == PPC::CR3) {
01668       CR3Spilled = true;
01669       continue;
01670     } else if (Reg == PPC::CR4) {
01671       CR4Spilled = true;
01672       continue;
01673     } else {
01674       // When we first encounter a non-CR register after seeing at
01675       // least one CR register, restore all spilled CRs together.
01676       if ((CR2Spilled || CR3Spilled || CR4Spilled)
01677           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
01678         bool is31 = needsFP(*MF);
01679         restoreCRs(Subtarget.isPPC64(), is31,
01680                    CR2Spilled, CR3Spilled, CR4Spilled,
01681                    MBB, I, CSI, CSIIndex);
01682         CR2Spilled = CR3Spilled = CR4Spilled = false;
01683       }
01684 
01685       // Default behavior for non-CR saves.
01686       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01687       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
01688                                RC, TRI);
01689       assert(I != MBB.begin() &&
01690              "loadRegFromStackSlot didn't insert any code!");
01691       }
01692 
01693     // Insert in reverse order.
01694     if (AtStart)
01695       I = MBB.begin();
01696     else {
01697       I = BeforeI;
01698       ++I;
01699     }
01700   }
01701 
01702   // If we haven't yet spilled the CRs, do so now.
01703   if (CR2Spilled || CR3Spilled || CR4Spilled) {
01704     bool is31 = needsFP(*MF);
01705     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
01706                MBB, I, CSI, CSIIndex);
01707   }
01708 
01709   return true;
01710 }