LLVM  mainline
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 MCPhysReg 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->isReturnBlock()) {
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   const MachineRegisterInfo &MRI = MF->getRegInfo();
00310   unsigned UsedRegMask = 0;
00311   for (unsigned i = 0; i != 32; ++i)
00312     if (MRI.isPhysRegModified(VRRegNo[i]))
00313       UsedRegMask |= 1 << (31-i);
00314 
00315   // Live in and live out values already must be in the mask, so don't bother
00316   // marking them.
00317   for (MachineRegisterInfo::livein_iterator
00318        I = MF->getRegInfo().livein_begin(),
00319        E = MF->getRegInfo().livein_end(); I != E; ++I) {
00320     unsigned RegNo = TRI->getEncodingValue(I->first);
00321     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
00322       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
00323   }
00324 
00325   // Live out registers appear as use operands on return instructions.
00326   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
00327        UsedRegMask != 0 && BI != BE; ++BI) {
00328     const MachineBasicBlock &MBB = *BI;
00329     if (!MBB.isReturnBlock())
00330       continue;
00331     const MachineInstr &Ret = MBB.back();
00332     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
00333       const MachineOperand &MO = Ret.getOperand(I);
00334       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
00335         continue;
00336       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
00337       UsedRegMask &= ~(1 << (31-RegNo));
00338     }
00339   }
00340 
00341   // If no registers are used, turn this into a copy.
00342   if (UsedRegMask == 0) {
00343     // Remove all VRSAVE code.
00344     RemoveVRSaveCode(MI);
00345     return;
00346   }
00347 
00348   unsigned SrcReg = MI->getOperand(1).getReg();
00349   unsigned DstReg = MI->getOperand(0).getReg();
00350 
00351   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
00352     if (DstReg != SrcReg)
00353       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00354         .addReg(SrcReg)
00355         .addImm(UsedRegMask);
00356     else
00357       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00358         .addReg(SrcReg, RegState::Kill)
00359         .addImm(UsedRegMask);
00360   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
00361     if (DstReg != SrcReg)
00362       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00363         .addReg(SrcReg)
00364         .addImm(UsedRegMask >> 16);
00365     else
00366       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00367         .addReg(SrcReg, RegState::Kill)
00368         .addImm(UsedRegMask >> 16);
00369   } else {
00370     if (DstReg != SrcReg)
00371       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00372         .addReg(SrcReg)
00373         .addImm(UsedRegMask >> 16);
00374     else
00375       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00376         .addReg(SrcReg, RegState::Kill)
00377         .addImm(UsedRegMask >> 16);
00378 
00379     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00380       .addReg(DstReg, RegState::Kill)
00381       .addImm(UsedRegMask & 0xFFFF);
00382   }
00383 
00384   // Remove the old UPDATE_VRSAVE instruction.
00385   MI->eraseFromParent();
00386 }
00387 
00388 static bool spillsCR(const MachineFunction &MF) {
00389   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00390   return FuncInfo->isCRSpilled();
00391 }
00392 
00393 static bool spillsVRSAVE(const MachineFunction &MF) {
00394   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00395   return FuncInfo->isVRSAVESpilled();
00396 }
00397 
00398 static bool hasSpills(const MachineFunction &MF) {
00399   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00400   return FuncInfo->hasSpills();
00401 }
00402 
00403 static bool hasNonRISpills(const MachineFunction &MF) {
00404   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00405   return FuncInfo->hasNonRISpills();
00406 }
00407 
00408 /// MustSaveLR - Return true if this function requires that we save the LR
00409 /// register onto the stack in the prolog and restore it in the epilog of the
00410 /// function.
00411 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
00412   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
00413 
00414   // We need a save/restore of LR if there is any def of LR (which is
00415   // defined by calls, including the PIC setup sequence), or if there is
00416   // some use of the LR stack slot (e.g. for builtin_return_address).
00417   // (LR comes in 32 and 64 bit versions.)
00418   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
00419   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
00420 }
00421 
00422 /// determineFrameLayout - Determine the size of the frame and maximum call
00423 /// frame size.
00424 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
00425                                                 bool UpdateMF,
00426                                                 bool UseEstimate) const {
00427   MachineFrameInfo *MFI = MF.getFrameInfo();
00428 
00429   // Get the number of bytes to allocate from the FrameInfo
00430   unsigned FrameSize =
00431     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
00432 
00433   // Get stack alignments. The frame must be aligned to the greatest of these:
00434   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
00435   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
00436   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
00437 
00438   const PPCRegisterInfo *RegInfo =
00439       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00440 
00441   // If we are a leaf function, and use up to 224 bytes of stack space,
00442   // don't have a frame pointer, calls, or dynamic alloca then we do not need
00443   // to adjust the stack pointer (we fit in the Red Zone).
00444   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
00445   // stackless code if all local vars are reg-allocated.
00446   bool DisableRedZone = MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
00447   unsigned LR = RegInfo->getRARegister();
00448   if (!DisableRedZone &&
00449       (Subtarget.isPPC64() ||                      // 32-bit SVR4, no stack-
00450        !Subtarget.isSVR4ABI() ||                   //   allocated locals.
00451         FrameSize == 0) &&
00452       FrameSize <= 224 &&                          // Fits in red zone.
00453       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
00454       !MFI->adjustsStack() &&                      // No calls.
00455       !MustSaveLR(MF, LR) &&
00456       !RegInfo->hasBasePointer(MF)) { // No special alignment.
00457     // No need for frame
00458     if (UpdateMF)
00459       MFI->setStackSize(0);
00460     return 0;
00461   }
00462 
00463   // Get the maximum call frame size of all the calls.
00464   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
00465 
00466   // Maximum call frame needs to be at least big enough for linkage area.
00467   unsigned minCallFrameSize = getLinkageSize();
00468   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
00469 
00470   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
00471   // that allocations will be aligned.
00472   if (MFI->hasVarSizedObjects())
00473     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
00474 
00475   // Update maximum call frame size.
00476   if (UpdateMF)
00477     MFI->setMaxCallFrameSize(maxCallFrameSize);
00478 
00479   // Include call frame size in total.
00480   FrameSize += maxCallFrameSize;
00481 
00482   // Make sure the frame is aligned.
00483   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
00484 
00485   // Update frame info.
00486   if (UpdateMF)
00487     MFI->setStackSize(FrameSize);
00488 
00489   return FrameSize;
00490 }
00491 
00492 // hasFP - Return true if the specified function actually has a dedicated frame
00493 // pointer register.
00494 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
00495   const MachineFrameInfo *MFI = MF.getFrameInfo();
00496   // FIXME: This is pretty much broken by design: hasFP() might be called really
00497   // early, before the stack layout was calculated and thus hasFP() might return
00498   // true or false here depending on the time of call.
00499   return (MFI->getStackSize()) && needsFP(MF);
00500 }
00501 
00502 // needsFP - Return true if the specified function should have a dedicated frame
00503 // pointer register.  This is true if the function has variable sized allocas or
00504 // if frame pointer elimination is disabled.
00505 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
00506   const MachineFrameInfo *MFI = MF.getFrameInfo();
00507 
00508   // Naked functions have no stack frame pushed, so we don't have a frame
00509   // pointer.
00510   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
00511     return false;
00512 
00513   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
00514     MFI->hasVarSizedObjects() ||
00515     MFI->hasStackMap() || MFI->hasPatchPoint() ||
00516     (MF.getTarget().Options.GuaranteedTailCallOpt &&
00517      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
00518 }
00519 
00520 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
00521   bool is31 = needsFP(MF);
00522   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
00523   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
00524 
00525   const PPCRegisterInfo *RegInfo =
00526       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00527   bool HasBP = RegInfo->hasBasePointer(MF);
00528   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
00529   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
00530 
00531   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
00532        BI != BE; ++BI)
00533     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
00534       --MBBI;
00535       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
00536         MachineOperand &MO = MBBI->getOperand(I);
00537         if (!MO.isReg())
00538           continue;
00539 
00540         switch (MO.getReg()) {
00541         case PPC::FP:
00542           MO.setReg(FPReg);
00543           break;
00544         case PPC::FP8:
00545           MO.setReg(FP8Reg);
00546           break;
00547         case PPC::BP:
00548           MO.setReg(BPReg);
00549           break;
00550         case PPC::BP8:
00551           MO.setReg(BP8Reg);
00552           break;
00553 
00554         }
00555       }
00556     }
00557 }
00558 
00559 bool PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
00560                                            bool UseAtEnd,
00561                                            unsigned *ScratchRegister) const {
00562   RegScavenger RS;
00563   unsigned     R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
00564 
00565   if (ScratchRegister)
00566     *ScratchRegister = R0;
00567 
00568   // If MBB is an entry or exit block, use R0 as the scratch register
00569   if ((UseAtEnd && MBB->isReturnBlock()) ||
00570       (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
00571     return true;
00572 
00573   RS.enterBasicBlock(MBB);
00574 
00575   if (UseAtEnd && !MBB->empty()) {
00576     // The scratch register will be used at the end of the block, so must consider
00577     // all registers used within the block
00578 
00579     MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
00580     // If no terminator, back iterator up to previous instruction.
00581     if (MBBI == MBB->end())
00582       MBBI = std::prev(MBBI);
00583 
00584     if (MBBI != MBB->begin())
00585       RS.forward(MBBI);
00586   }
00587   
00588   if (!RS.isRegUsed(R0)) 
00589     return true;
00590 
00591   unsigned Reg = RS.FindUnusedReg(Subtarget.isPPC64() ? &PPC::G8RCRegClass
00592                                   : &PPC::GPRCRegClass);
00593   
00594   // Make sure the register scavenger was able to find an available register
00595   // If not, use R0 but return false to indicate no register was available and
00596   // R0 must be used (as recommended by the ABI)
00597   if (Reg == 0)
00598     return false;
00599 
00600   if (ScratchRegister)
00601     *ScratchRegister = Reg;
00602 
00603   return true;
00604 }
00605 
00606 bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
00607   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
00608 
00609   return findScratchRegister(TmpMBB, false, nullptr);
00610 }
00611 
00612 bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
00613   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
00614 
00615   return findScratchRegister(TmpMBB, true, nullptr);
00616 }
00617 
00618 void PPCFrameLowering::emitPrologue(MachineFunction &MF,
00619                                     MachineBasicBlock &MBB) const {
00620   MachineBasicBlock::iterator MBBI = MBB.begin();
00621   MachineFrameInfo *MFI = MF.getFrameInfo();
00622   const PPCInstrInfo &TII =
00623       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
00624   const PPCRegisterInfo *RegInfo =
00625       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00626 
00627   MachineModuleInfo &MMI = MF.getMMI();
00628   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00629   DebugLoc dl;
00630   bool needsCFI = MMI.hasDebugInfo() ||
00631     MF.getFunction()->needsUnwindTableEntry();
00632 
00633   // Get processor type.
00634   bool isPPC64 = Subtarget.isPPC64();
00635   // Get the ABI.
00636   bool isSVR4ABI = Subtarget.isSVR4ABI();
00637   bool isELFv2ABI = Subtarget.isELFv2ABI();
00638   assert((Subtarget.isDarwinABI() || isSVR4ABI) &&
00639          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
00640 
00641   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
00642   // process it.
00643   if (!isSVR4ABI)
00644     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
00645       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
00646         HandleVRSaveUpdate(MBBI, TII);
00647         break;
00648       }
00649     }
00650 
00651   // Move MBBI back to the beginning of the prologue block.
00652   MBBI = MBB.begin();
00653 
00654   // Work out frame sizes.
00655   unsigned FrameSize = determineFrameLayout(MF);
00656   int NegFrameSize = -FrameSize;
00657   if (!isInt<32>(NegFrameSize))
00658     llvm_unreachable("Unhandled stack size!");
00659 
00660   if (MFI->isFrameAddressTaken())
00661     replaceFPWithRealFP(MF);
00662 
00663   // Check if the link register (LR) must be saved.
00664   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
00665   bool MustSaveLR = FI->mustSaveLR();
00666   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
00667   // Do we have a frame pointer and/or base pointer for this function?
00668   bool HasFP = hasFP(MF);
00669   bool HasBP = RegInfo->hasBasePointer(MF);
00670 
00671   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
00672   unsigned BPReg       = RegInfo->getBaseRegister(MF);
00673   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
00674   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
00675   unsigned ScratchReg  = 0;
00676   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
00677   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
00678   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
00679                                                 : PPC::MFLR );
00680   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
00681                                                  : PPC::STW );
00682   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
00683                                                      : PPC::STWU );
00684   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
00685                                                         : PPC::STWUX);
00686   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
00687                                                           : PPC::LIS );
00688   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
00689                                                  : PPC::ORI );
00690   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
00691                                               : PPC::OR );
00692   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
00693                                                             : PPC::SUBFC);
00694   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
00695                                                                : PPC::SUBFIC);
00696 
00697   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
00698   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
00699   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
00700   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
00701   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
00702          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
00703 
00704   findScratchRegister(&MBB, false, &ScratchReg);
00705   assert(ScratchReg && "No scratch register!");
00706          
00707   int LROffset = getReturnSaveOffset();
00708 
00709   int FPOffset = 0;
00710   if (HasFP) {
00711     if (isSVR4ABI) {
00712       MachineFrameInfo *FFI = MF.getFrameInfo();
00713       int FPIndex = FI->getFramePointerSaveIndex();
00714       assert(FPIndex && "No Frame Pointer Save Slot!");
00715       FPOffset = FFI->getObjectOffset(FPIndex);
00716     } else {
00717       FPOffset = getFramePointerSaveOffset();
00718     }
00719   }
00720 
00721   int BPOffset = 0;
00722   if (HasBP) {
00723     if (isSVR4ABI) {
00724       MachineFrameInfo *FFI = MF.getFrameInfo();
00725       int BPIndex = FI->getBasePointerSaveIndex();
00726       assert(BPIndex && "No Base Pointer Save Slot!");
00727       BPOffset = FFI->getObjectOffset(BPIndex);
00728     } else {
00729       BPOffset = getBasePointerSaveOffset();
00730     }
00731   }
00732 
00733   int PBPOffset = 0;
00734   if (FI->usesPICBase()) {
00735     MachineFrameInfo *FFI = MF.getFrameInfo();
00736     int PBPIndex = FI->getPICBasePointerSaveIndex();
00737     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
00738     PBPOffset = FFI->getObjectOffset(PBPIndex);
00739   }
00740 
00741   // Get stack alignments.
00742   unsigned MaxAlign = MFI->getMaxAlignment();
00743   if (HasBP && MaxAlign > 1)
00744     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
00745            "Invalid alignment!");
00746 
00747   // Frames of 32KB & larger require special handling because they cannot be
00748   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
00749   bool isLargeFrame = !isInt<16>(NegFrameSize);
00750 
00751   if (MustSaveLR)
00752     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
00753 
00754   assert((isPPC64 || MustSaveCRs.empty()) &&
00755          "Prologue CR saving supported only in 64-bit mode");
00756 
00757   if (!MustSaveCRs.empty()) { // will only occur for PPC64
00758     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
00759     // If only one or two CR fields are clobbered, it could be more
00760     // efficient to use mfocrf to selectively save just those fields.
00761     MachineInstrBuilder MIB =
00762       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
00763     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
00764       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
00765   }
00766 
00767   if (HasFP)
00768     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00769     BuildMI(MBB, MBBI, dl, StoreInst)
00770       .addReg(FPReg)
00771       .addImm(FPOffset)
00772       .addReg(SPReg);
00773 
00774   if (FI->usesPICBase())
00775     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00776     BuildMI(MBB, MBBI, dl, StoreInst)
00777       .addReg(PPC::R30)
00778       .addImm(PBPOffset)
00779       .addReg(SPReg);
00780 
00781   if (HasBP)
00782     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00783     BuildMI(MBB, MBBI, dl, StoreInst)
00784       .addReg(BPReg)
00785       .addImm(BPOffset)
00786       .addReg(SPReg);
00787 
00788   if (MustSaveLR)
00789     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00790     BuildMI(MBB, MBBI, dl, StoreInst)
00791       .addReg(ScratchReg)
00792       .addImm(LROffset)
00793       .addReg(SPReg);
00794 
00795   if (!MustSaveCRs.empty()) // will only occur for PPC64
00796     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
00797       .addReg(TempReg, getKillRegState(true))
00798       .addImm(8)
00799       .addReg(SPReg);
00800 
00801   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
00802   if (!FrameSize) return;
00803 
00804   // Adjust stack pointer: r1 += NegFrameSize.
00805   // If there is a preferred stack alignment, align R1 now
00806 
00807   if (HasBP) {
00808     // Save a copy of r1 as the base pointer.
00809     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
00810       .addReg(SPReg)
00811       .addReg(SPReg);
00812   }
00813 
00814   if (HasBP && MaxAlign > 1) {
00815     if (isPPC64)
00816       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
00817         .addReg(SPReg)
00818         .addImm(0)
00819         .addImm(64 - Log2_32(MaxAlign));
00820     else // PPC32...
00821       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
00822         .addReg(SPReg)
00823         .addImm(0)
00824         .addImm(32 - Log2_32(MaxAlign))
00825         .addImm(31);
00826     if (!isLargeFrame) {
00827       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
00828         .addReg(ScratchReg, RegState::Kill)
00829         .addImm(NegFrameSize);
00830     } else {
00831       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
00832         .addImm(NegFrameSize >> 16);
00833       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
00834         .addReg(TempReg, RegState::Kill)
00835         .addImm(NegFrameSize & 0xFFFF);
00836       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
00837         .addReg(ScratchReg, RegState::Kill)
00838         .addReg(TempReg, RegState::Kill);
00839     }
00840     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00841       .addReg(SPReg, RegState::Kill)
00842       .addReg(SPReg)
00843       .addReg(ScratchReg);
00844 
00845   } else if (!isLargeFrame) {
00846     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
00847       .addReg(SPReg)
00848       .addImm(NegFrameSize)
00849       .addReg(SPReg);
00850 
00851   } else {
00852     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
00853       .addImm(NegFrameSize >> 16);
00854     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
00855       .addReg(ScratchReg, RegState::Kill)
00856       .addImm(NegFrameSize & 0xFFFF);
00857     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00858       .addReg(SPReg, RegState::Kill)
00859       .addReg(SPReg)
00860       .addReg(ScratchReg);
00861   }
00862 
00863   // Add Call Frame Information for the instructions we generated above.
00864   if (needsCFI) {
00865     unsigned CFIIndex;
00866 
00867     if (HasBP) {
00868       // Define CFA in terms of BP. Do this in preference to using FP/SP,
00869       // because if the stack needed aligning then CFA won't be at a fixed
00870       // offset from FP/SP.
00871       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00872       CFIIndex = MMI.addFrameInst(
00873           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00874     } else {
00875       // Adjust the definition of CFA to account for the change in SP.
00876       assert(NegFrameSize);
00877       CFIIndex = MMI.addFrameInst(
00878           MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
00879     }
00880     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00881         .addCFIIndex(CFIIndex);
00882 
00883     if (HasFP) {
00884       // Describe where FP was saved, at a fixed offset from CFA.
00885       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00886       CFIIndex = MMI.addFrameInst(
00887           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
00888       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00889           .addCFIIndex(CFIIndex);
00890     }
00891 
00892     if (FI->usesPICBase()) {
00893       // Describe where FP was saved, at a fixed offset from CFA.
00894       unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
00895       CFIIndex = MMI.addFrameInst(
00896           MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
00897       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00898           .addCFIIndex(CFIIndex);
00899     }
00900 
00901     if (HasBP) {
00902       // Describe where BP was saved, at a fixed offset from CFA.
00903       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00904       CFIIndex = MMI.addFrameInst(
00905           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
00906       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00907           .addCFIIndex(CFIIndex);
00908     }
00909 
00910     if (MustSaveLR) {
00911       // Describe where LR was saved, at a fixed offset from CFA.
00912       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
00913       CFIIndex = MMI.addFrameInst(
00914           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
00915       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00916           .addCFIIndex(CFIIndex);
00917     }
00918   }
00919 
00920   // If there is a frame pointer, copy R1 into R31
00921   if (HasFP) {
00922     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
00923       .addReg(SPReg)
00924       .addReg(SPReg);
00925 
00926     if (!HasBP && needsCFI) {
00927       // Change the definition of CFA from SP+offset to FP+offset, because SP
00928       // will change at every alloca.
00929       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00930       unsigned CFIIndex = MMI.addFrameInst(
00931           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00932 
00933       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00934           .addCFIIndex(CFIIndex);
00935     }
00936   }
00937 
00938   if (needsCFI) {
00939     // Describe where callee saved registers were saved, at fixed offsets from
00940     // CFA.
00941     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00942     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
00943       unsigned Reg = CSI[I].getReg();
00944       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
00945 
00946       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
00947       // subregisters of CR2. We just need to emit a move of CR2.
00948       if (PPC::CRBITRCRegClass.contains(Reg))
00949         continue;
00950 
00951       // For SVR4, don't emit a move for the CR spill slot if we haven't
00952       // spilled CRs.
00953       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
00954           && MustSaveCRs.empty())
00955         continue;
00956 
00957       // For 64-bit SVR4 when we have spilled CRs, the spill location
00958       // is SP+8, not a frame-relative slot.
00959       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
00960         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
00961         // the whole CR word.  In the ELFv2 ABI, every CR that was
00962         // actually saved gets its own CFI record.
00963         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
00964         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00965             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
00966         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00967             .addCFIIndex(CFIIndex);
00968         continue;
00969       }
00970 
00971       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
00972       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00973           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
00974       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00975           .addCFIIndex(CFIIndex);
00976     }
00977   }
00978 }
00979 
00980 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
00981                                     MachineBasicBlock &MBB) const {
00982   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
00983   DebugLoc dl;
00984 
00985   if (MBBI != MBB.end())
00986     dl = MBBI->getDebugLoc();
00987   
00988   const PPCInstrInfo &TII =
00989       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
00990   const PPCRegisterInfo *RegInfo =
00991       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
00992 
00993   // Get alignment info so we know how to restore the SP.
00994   const MachineFrameInfo *MFI = MF.getFrameInfo();
00995 
00996   // Get the number of bytes allocated from the FrameInfo.
00997   int FrameSize = MFI->getStackSize();
00998 
00999   // Get processor type.
01000   bool isPPC64 = Subtarget.isPPC64();
01001   // Get the ABI.
01002   bool isSVR4ABI = Subtarget.isSVR4ABI();
01003 
01004   // Check if the link register (LR) has been saved.
01005   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01006   bool MustSaveLR = FI->mustSaveLR();
01007   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
01008   // Do we have a frame pointer and/or base pointer for this function?
01009   bool HasFP = hasFP(MF);
01010   bool HasBP = RegInfo->hasBasePointer(MF);
01011 
01012   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
01013   unsigned BPReg      = RegInfo->getBaseRegister(MF);
01014   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
01015   unsigned ScratchReg = 0;
01016   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
01017   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
01018                                                  : PPC::MTLR );
01019   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
01020                                                  : PPC::LWZ );
01021   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
01022                                                            : PPC::LIS );
01023   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
01024                                                   : PPC::ORI );
01025   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
01026                                                    : PPC::ADDI );
01027   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
01028                                                 : PPC::ADD4 );
01029   
01030   int LROffset = getReturnSaveOffset();
01031 
01032   int FPOffset = 0;
01033 
01034   findScratchRegister(&MBB, true, &ScratchReg);
01035   assert(ScratchReg && "No scratch register!");
01036   
01037   if (HasFP) {
01038     if (isSVR4ABI) {
01039       MachineFrameInfo *FFI = MF.getFrameInfo();
01040       int FPIndex = FI->getFramePointerSaveIndex();
01041       assert(FPIndex && "No Frame Pointer Save Slot!");
01042       FPOffset = FFI->getObjectOffset(FPIndex);
01043     } else {
01044       FPOffset = getFramePointerSaveOffset();
01045     }
01046   }
01047 
01048   int BPOffset = 0;
01049   if (HasBP) {
01050     if (isSVR4ABI) {
01051       MachineFrameInfo *FFI = MF.getFrameInfo();
01052       int BPIndex = FI->getBasePointerSaveIndex();
01053       assert(BPIndex && "No Base Pointer Save Slot!");
01054       BPOffset = FFI->getObjectOffset(BPIndex);
01055     } else {
01056       BPOffset = getBasePointerSaveOffset();
01057     }
01058   }
01059 
01060   int PBPOffset = 0;
01061   if (FI->usesPICBase()) {
01062     MachineFrameInfo *FFI = MF.getFrameInfo();
01063     int PBPIndex = FI->getPICBasePointerSaveIndex();
01064     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
01065     PBPOffset = FFI->getObjectOffset(PBPIndex);
01066   }
01067 
01068   bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
01069   
01070   if (IsReturnBlock) {
01071     unsigned RetOpcode = MBBI->getOpcode();
01072     bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
01073                       RetOpcode == PPC::TCRETURNdi ||
01074                       RetOpcode == PPC::TCRETURNai ||
01075                       RetOpcode == PPC::TCRETURNri8 ||
01076                       RetOpcode == PPC::TCRETURNdi8 ||
01077                       RetOpcode == PPC::TCRETURNai8;
01078 
01079     if (UsesTCRet) {
01080       int MaxTCRetDelta = FI->getTailCallSPDelta();
01081       MachineOperand &StackAdjust = MBBI->getOperand(1);
01082       assert(StackAdjust.isImm() && "Expecting immediate value.");
01083       // Adjust stack pointer.
01084       int StackAdj = StackAdjust.getImm();
01085       int Delta = StackAdj - MaxTCRetDelta;
01086       assert((Delta >= 0) && "Delta must be positive");
01087       if (MaxTCRetDelta>0)
01088         FrameSize += (StackAdj +Delta);
01089       else
01090         FrameSize += StackAdj;
01091     }
01092   }
01093 
01094   // Frames of 32KB & larger require special handling because they cannot be
01095   // indexed into with a simple LD/LWZ immediate offset operand.
01096   bool isLargeFrame = !isInt<16>(FrameSize);
01097 
01098   if (FrameSize) {
01099     // In the prologue, the loaded (or persistent) stack pointer value is offset
01100     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
01101 
01102     // If this function contained a fastcc call and GuaranteedTailCallOpt is
01103     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
01104     // call which invalidates the stack pointer value in SP(0). So we use the
01105     // value of R31 in this case.
01106     if (FI->hasFastCall()) {
01107       assert(HasFP && "Expecting a valid frame pointer.");
01108       if (!isLargeFrame) {
01109         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01110           .addReg(FPReg).addImm(FrameSize);
01111       } else {
01112         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
01113           .addImm(FrameSize >> 16);
01114         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
01115           .addReg(ScratchReg, RegState::Kill)
01116           .addImm(FrameSize & 0xFFFF);
01117         BuildMI(MBB, MBBI, dl, AddInst)
01118           .addReg(SPReg)
01119           .addReg(FPReg)
01120           .addReg(ScratchReg);
01121       }
01122     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
01123       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01124         .addReg(SPReg)
01125         .addImm(FrameSize);
01126     } else {
01127       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
01128         .addImm(0)
01129         .addReg(SPReg);
01130     }
01131   }
01132 
01133   if (MustSaveLR)
01134     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
01135       .addImm(LROffset)
01136       .addReg(SPReg);
01137 
01138   assert((isPPC64 || MustSaveCRs.empty()) &&
01139          "Epilogue CR restoring supported only in 64-bit mode");
01140 
01141   if (!MustSaveCRs.empty()) // will only occur for PPC64
01142     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
01143       .addImm(8)
01144       .addReg(SPReg);
01145 
01146   if (HasFP)
01147     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
01148       .addImm(FPOffset)
01149       .addReg(SPReg);
01150 
01151   if (FI->usesPICBase())
01152     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
01153     BuildMI(MBB, MBBI, dl, LoadInst)
01154       .addReg(PPC::R30)
01155       .addImm(PBPOffset)
01156       .addReg(SPReg);
01157 
01158   if (HasBP)
01159     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
01160       .addImm(BPOffset)
01161       .addReg(SPReg);
01162 
01163   if (!MustSaveCRs.empty()) // will only occur for PPC64
01164     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
01165       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
01166         .addReg(TempReg, getKillRegState(i == e-1));
01167 
01168   if (MustSaveLR)
01169     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
01170 
01171   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
01172   // call optimization
01173   if (IsReturnBlock) {
01174     unsigned RetOpcode = MBBI->getOpcode();
01175     if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01176         (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
01177         MF.getFunction()->getCallingConv() == CallingConv::Fast) {
01178       PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01179       unsigned CallerAllocatedAmt = FI->getMinReservedArea();
01180 
01181       if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
01182         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01183           .addReg(SPReg).addImm(CallerAllocatedAmt);
01184       } else {
01185         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
01186           .addImm(CallerAllocatedAmt >> 16);
01187         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
01188           .addReg(ScratchReg, RegState::Kill)
01189           .addImm(CallerAllocatedAmt & 0xFFFF);
01190         BuildMI(MBB, MBBI, dl, AddInst)
01191           .addReg(SPReg)
01192           .addReg(FPReg)
01193           .addReg(ScratchReg);
01194       }
01195     } else if (RetOpcode == PPC::TCRETURNdi) {
01196       MBBI = MBB.getLastNonDebugInstr();
01197       MachineOperand &JumpTarget = MBBI->getOperand(0);
01198       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
01199         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01200     } else if (RetOpcode == PPC::TCRETURNri) {
01201       MBBI = MBB.getLastNonDebugInstr();
01202       assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01203       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
01204     } else if (RetOpcode == PPC::TCRETURNai) {
01205       MBBI = MBB.getLastNonDebugInstr();
01206       MachineOperand &JumpTarget = MBBI->getOperand(0);
01207       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
01208     } else if (RetOpcode == PPC::TCRETURNdi8) {
01209       MBBI = MBB.getLastNonDebugInstr();
01210       MachineOperand &JumpTarget = MBBI->getOperand(0);
01211       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
01212         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01213     } else if (RetOpcode == PPC::TCRETURNri8) {
01214       MBBI = MBB.getLastNonDebugInstr();
01215       assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01216       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
01217     } else if (RetOpcode == PPC::TCRETURNai8) {
01218       MBBI = MBB.getLastNonDebugInstr();
01219       MachineOperand &JumpTarget = MBBI->getOperand(0);
01220       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
01221     }
01222   }
01223 }
01224 
01225 void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,
01226                                             BitVector &SavedRegs,
01227                                             RegScavenger *RS) const {
01228   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
01229 
01230   const PPCRegisterInfo *RegInfo =
01231       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
01232 
01233   //  Save and clear the LR state.
01234   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01235   unsigned LR = RegInfo->getRARegister();
01236   FI->setMustSaveLR(MustSaveLR(MF, LR));
01237   SavedRegs.reset(LR);
01238 
01239   //  Save R31 if necessary
01240   int FPSI = FI->getFramePointerSaveIndex();
01241   bool isPPC64 = Subtarget.isPPC64();
01242   bool isDarwinABI  = Subtarget.isDarwinABI();
01243   MachineFrameInfo *MFI = MF.getFrameInfo();
01244 
01245   // If the frame pointer save index hasn't been defined yet.
01246   if (!FPSI && needsFP(MF)) {
01247     // Find out what the fix offset of the frame pointer save area.
01248     int FPOffset = getFramePointerSaveOffset();
01249     // Allocate the frame index for frame pointer save area.
01250     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
01251     // Save the result.
01252     FI->setFramePointerSaveIndex(FPSI);
01253   }
01254 
01255   int BPSI = FI->getBasePointerSaveIndex();
01256   if (!BPSI && RegInfo->hasBasePointer(MF)) {
01257     int BPOffset = getBasePointerSaveOffset();
01258     // Allocate the frame index for the base pointer save area.
01259     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
01260     // Save the result.
01261     FI->setBasePointerSaveIndex(BPSI);
01262   }
01263 
01264   // Reserve stack space for the PIC Base register (R30).
01265   // Only used in SVR4 32-bit.
01266   if (FI->usesPICBase()) {
01267     int PBPSI = MFI->CreateFixedObject(4, -8, true);
01268     FI->setPICBasePointerSaveIndex(PBPSI);
01269   }
01270 
01271   // Reserve stack space to move the linkage area to in case of a tail call.
01272   int TCSPDelta = 0;
01273   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01274       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
01275     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
01276   }
01277 
01278   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
01279   // function uses CR 2, 3, or 4.
01280   if (!isPPC64 && !isDarwinABI &&
01281       (SavedRegs.test(PPC::CR2) ||
01282        SavedRegs.test(PPC::CR3) ||
01283        SavedRegs.test(PPC::CR4))) {
01284     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
01285     FI->setCRSpillFrameIndex(FrameIdx);
01286   }
01287 }
01288 
01289 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
01290                                                        RegScavenger *RS) const {
01291   // Early exit if not using the SVR4 ABI.
01292   if (!Subtarget.isSVR4ABI()) {
01293     addScavengingSpillSlot(MF, RS);
01294     return;
01295   }
01296 
01297   // Get callee saved register information.
01298   MachineFrameInfo *FFI = MF.getFrameInfo();
01299   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
01300 
01301   // Early exit if no callee saved registers are modified!
01302   if (CSI.empty() && !needsFP(MF)) {
01303     addScavengingSpillSlot(MF, RS);
01304     return;
01305   }
01306 
01307   unsigned MinGPR = PPC::R31;
01308   unsigned MinG8R = PPC::X31;
01309   unsigned MinFPR = PPC::F31;
01310   unsigned MinVR = PPC::V31;
01311 
01312   bool HasGPSaveArea = false;
01313   bool HasG8SaveArea = false;
01314   bool HasFPSaveArea = false;
01315   bool HasVRSAVESaveArea = false;
01316   bool HasVRSaveArea = false;
01317 
01318   SmallVector<CalleeSavedInfo, 18> GPRegs;
01319   SmallVector<CalleeSavedInfo, 18> G8Regs;
01320   SmallVector<CalleeSavedInfo, 18> FPRegs;
01321   SmallVector<CalleeSavedInfo, 18> VRegs;
01322 
01323   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01324     unsigned Reg = CSI[i].getReg();
01325     if (PPC::GPRCRegClass.contains(Reg)) {
01326       HasGPSaveArea = true;
01327 
01328       GPRegs.push_back(CSI[i]);
01329 
01330       if (Reg < MinGPR) {
01331         MinGPR = Reg;
01332       }
01333     } else if (PPC::G8RCRegClass.contains(Reg)) {
01334       HasG8SaveArea = true;
01335 
01336       G8Regs.push_back(CSI[i]);
01337 
01338       if (Reg < MinG8R) {
01339         MinG8R = Reg;
01340       }
01341     } else if (PPC::F8RCRegClass.contains(Reg)) {
01342       HasFPSaveArea = true;
01343 
01344       FPRegs.push_back(CSI[i]);
01345 
01346       if (Reg < MinFPR) {
01347         MinFPR = Reg;
01348       }
01349     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
01350                PPC::CRRCRegClass.contains(Reg)) {
01351       ; // do nothing, as we already know whether CRs are spilled
01352     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
01353       HasVRSAVESaveArea = true;
01354     } else if (PPC::VRRCRegClass.contains(Reg)) {
01355       HasVRSaveArea = true;
01356 
01357       VRegs.push_back(CSI[i]);
01358 
01359       if (Reg < MinVR) {
01360         MinVR = Reg;
01361       }
01362     } else {
01363       llvm_unreachable("Unknown RegisterClass!");
01364     }
01365   }
01366 
01367   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
01368   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
01369 
01370   int64_t LowerBound = 0;
01371 
01372   // Take into account stack space reserved for tail calls.
01373   int TCSPDelta = 0;
01374   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01375       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
01376     LowerBound = TCSPDelta;
01377   }
01378 
01379   // The Floating-point register save area is right below the back chain word
01380   // of the previous stack frame.
01381   if (HasFPSaveArea) {
01382     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
01383       int FI = FPRegs[i].getFrameIdx();
01384 
01385       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01386     }
01387 
01388     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
01389   }
01390 
01391   // Check whether the frame pointer register is allocated. If so, make sure it
01392   // is spilled to the correct offset.
01393   if (needsFP(MF)) {
01394     HasGPSaveArea = true;
01395 
01396     int FI = PFI->getFramePointerSaveIndex();
01397     assert(FI && "No Frame Pointer Save Slot!");
01398 
01399     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01400   }
01401 
01402   if (PFI->usesPICBase()) {
01403     HasGPSaveArea = true;
01404 
01405     int FI = PFI->getPICBasePointerSaveIndex();
01406     assert(FI && "No PIC Base Pointer Save Slot!");
01407 
01408     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01409   }
01410 
01411   const PPCRegisterInfo *RegInfo =
01412       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
01413   if (RegInfo->hasBasePointer(MF)) {
01414     HasGPSaveArea = true;
01415 
01416     int FI = PFI->getBasePointerSaveIndex();
01417     assert(FI && "No Base Pointer Save Slot!");
01418 
01419     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01420   }
01421 
01422   // General register save area starts right below the Floating-point
01423   // register save area.
01424   if (HasGPSaveArea || HasG8SaveArea) {
01425     // Move general register save area spill slots down, taking into account
01426     // the size of the Floating-point register save area.
01427     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
01428       int FI = GPRegs[i].getFrameIdx();
01429 
01430       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01431     }
01432 
01433     // Move general register save area spill slots down, taking into account
01434     // the size of the Floating-point register save area.
01435     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
01436       int FI = G8Regs[i].getFrameIdx();
01437 
01438       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01439     }
01440 
01441     unsigned MinReg =
01442       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
01443                          TRI->getEncodingValue(MinG8R));
01444 
01445     if (Subtarget.isPPC64()) {
01446       LowerBound -= (31 - MinReg + 1) * 8;
01447     } else {
01448       LowerBound -= (31 - MinReg + 1) * 4;
01449     }
01450   }
01451 
01452   // For 32-bit only, the CR save area is below the general register
01453   // save area.  For 64-bit SVR4, the CR save area is addressed relative
01454   // to the stack pointer and hence does not need an adjustment here.
01455   // Only CR2 (the first nonvolatile spilled) has an associated frame
01456   // index so that we have a single uniform save area.
01457   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
01458     // Adjust the frame index of the CR spill slot.
01459     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01460       unsigned Reg = CSI[i].getReg();
01461 
01462       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
01463           // Leave Darwin logic as-is.
01464           || (!Subtarget.isSVR4ABI() &&
01465               (PPC::CRBITRCRegClass.contains(Reg) ||
01466                PPC::CRRCRegClass.contains(Reg)))) {
01467         int FI = CSI[i].getFrameIdx();
01468 
01469         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01470       }
01471     }
01472 
01473     LowerBound -= 4; // The CR save area is always 4 bytes long.
01474   }
01475 
01476   if (HasVRSAVESaveArea) {
01477     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
01478     //             which have the VRSAVE register class?
01479     // Adjust the frame index of the VRSAVE spill slot.
01480     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01481       unsigned Reg = CSI[i].getReg();
01482 
01483       if (PPC::VRSAVERCRegClass.contains(Reg)) {
01484         int FI = CSI[i].getFrameIdx();
01485 
01486         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01487       }
01488     }
01489 
01490     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
01491   }
01492 
01493   if (HasVRSaveArea) {
01494     // Insert alignment padding, we need 16-byte alignment.
01495     LowerBound = (LowerBound - 15) & ~(15);
01496 
01497     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
01498       int FI = VRegs[i].getFrameIdx();
01499 
01500       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01501     }
01502   }
01503 
01504   addScavengingSpillSlot(MF, RS);
01505 }
01506 
01507 void
01508 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
01509                                          RegScavenger *RS) const {
01510   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
01511   // a large stack, which will require scavenging a register to materialize a
01512   // large offset.
01513 
01514   // We need to have a scavenger spill slot for spills if the frame size is
01515   // large. In case there is no free register for large-offset addressing,
01516   // this slot is used for the necessary emergency spill. Also, we need the
01517   // slot for dynamic stack allocations.
01518 
01519   // The scavenger might be invoked if the frame offset does not fit into
01520   // the 16-bit immediate. We don't know the complete frame size here
01521   // because we've not yet computed callee-saved register spills or the
01522   // needed alignment padding.
01523   unsigned StackSize = determineFrameLayout(MF, false, true);
01524   MachineFrameInfo *MFI = MF.getFrameInfo();
01525   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
01526       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
01527     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
01528     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
01529     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
01530     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01531                                                        RC->getAlignment(),
01532                                                        false));
01533 
01534     // Might we have over-aligned allocas?
01535     bool HasAlVars = MFI->hasVarSizedObjects() &&
01536                      MFI->getMaxAlignment() > getStackAlignment();
01537 
01538     // These kinds of spills might need two registers.
01539     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
01540       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01541                                                          RC->getAlignment(),
01542                                                          false));
01543 
01544   }
01545 }
01546 
01547 bool
01548 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
01549                                      MachineBasicBlock::iterator MI,
01550                                      const std::vector<CalleeSavedInfo> &CSI,
01551                                      const TargetRegisterInfo *TRI) const {
01552 
01553   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01554   // Return false otherwise to maintain pre-existing behavior.
01555   if (!Subtarget.isSVR4ABI())
01556     return false;
01557 
01558   MachineFunction *MF = MBB.getParent();
01559   const PPCInstrInfo &TII =
01560       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
01561   DebugLoc DL;
01562   bool CRSpilled = false;
01563   MachineInstrBuilder CRMIB;
01564 
01565   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01566     unsigned Reg = CSI[i].getReg();
01567     // Only Darwin actually uses the VRSAVE register, but it can still appear
01568     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01569     // Darwin, ignore it.
01570     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01571       continue;
01572 
01573     // CR2 through CR4 are the nonvolatile CR fields.
01574     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
01575 
01576     // Add the callee-saved register as live-in; it's killed at the spill.
01577     MBB.addLiveIn(Reg);
01578 
01579     if (CRSpilled && IsCRField) {
01580       CRMIB.addReg(Reg, RegState::ImplicitKill);
01581       continue;
01582     }
01583 
01584     // Insert the spill to the stack frame.
01585     if (IsCRField) {
01586       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
01587       if (Subtarget.isPPC64()) {
01588         // The actual spill will happen at the start of the prologue.
01589         FuncInfo->addMustSaveCR(Reg);
01590       } else {
01591         CRSpilled = true;
01592         FuncInfo->setSpillsCR();
01593 
01594         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
01595         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
01596         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
01597                   .addReg(Reg, RegState::ImplicitKill);
01598 
01599         MBB.insert(MI, CRMIB);
01600         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
01601                                          .addReg(PPC::R12,
01602                                                  getKillRegState(true)),
01603                                          CSI[i].getFrameIdx()));
01604       }
01605     } else {
01606       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01607       TII.storeRegToStackSlot(MBB, MI, Reg, true,
01608                               CSI[i].getFrameIdx(), RC, TRI);
01609     }
01610   }
01611   return true;
01612 }
01613 
01614 static void
01615 restoreCRs(bool isPPC64, bool is31,
01616            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
01617            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01618            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
01619 
01620   MachineFunction *MF = MBB.getParent();
01621   const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
01622   DebugLoc DL;
01623   unsigned RestoreOp, MoveReg;
01624 
01625   if (isPPC64)
01626     // This is handled during epilogue generation.
01627     return;
01628   else {
01629     // 32-bit:  FP-relative
01630     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
01631                                              PPC::R12),
01632                                      CSI[CSIIndex].getFrameIdx()));
01633     RestoreOp = PPC::MTOCRF;
01634     MoveReg = PPC::R12;
01635   }
01636 
01637   if (CR2Spilled)
01638     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
01639                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
01640 
01641   if (CR3Spilled)
01642     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
01643                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
01644 
01645   if (CR4Spilled)
01646     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
01647                .addReg(MoveReg, getKillRegState(true)));
01648 }
01649 
01650 void PPCFrameLowering::
01651 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01652                               MachineBasicBlock::iterator I) const {
01653   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
01654   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01655       I->getOpcode() == PPC::ADJCALLSTACKUP) {
01656     // Add (actually subtract) back the amount the callee popped on return.
01657     if (int CalleeAmt =  I->getOperand(1).getImm()) {
01658       bool is64Bit = Subtarget.isPPC64();
01659       CalleeAmt *= -1;
01660       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
01661       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
01662       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
01663       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
01664       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
01665       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
01666       MachineInstr *MI = I;
01667       DebugLoc dl = MI->getDebugLoc();
01668 
01669       if (isInt<16>(CalleeAmt)) {
01670         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
01671           .addReg(StackReg, RegState::Kill)
01672           .addImm(CalleeAmt);
01673       } else {
01674         MachineBasicBlock::iterator MBBI = I;
01675         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
01676           .addImm(CalleeAmt >> 16);
01677         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
01678           .addReg(TmpReg, RegState::Kill)
01679           .addImm(CalleeAmt & 0xFFFF);
01680         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
01681           .addReg(StackReg, RegState::Kill)
01682           .addReg(TmpReg);
01683       }
01684     }
01685   }
01686   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
01687   MBB.erase(I);
01688 }
01689 
01690 bool
01691 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01692                                         MachineBasicBlock::iterator MI,
01693                                         const std::vector<CalleeSavedInfo> &CSI,
01694                                         const TargetRegisterInfo *TRI) const {
01695 
01696   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01697   // Return false otherwise to maintain pre-existing behavior.
01698   if (!Subtarget.isSVR4ABI())
01699     return false;
01700 
01701   MachineFunction *MF = MBB.getParent();
01702   const PPCInstrInfo &TII =
01703       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
01704   bool CR2Spilled = false;
01705   bool CR3Spilled = false;
01706   bool CR4Spilled = false;
01707   unsigned CSIIndex = 0;
01708 
01709   // Initialize insertion-point logic; we will be restoring in reverse
01710   // order of spill.
01711   MachineBasicBlock::iterator I = MI, BeforeI = I;
01712   bool AtStart = I == MBB.begin();
01713 
01714   if (!AtStart)
01715     --BeforeI;
01716 
01717   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01718     unsigned Reg = CSI[i].getReg();
01719 
01720     // Only Darwin actually uses the VRSAVE register, but it can still appear
01721     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01722     // Darwin, ignore it.
01723     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01724       continue;
01725 
01726     if (Reg == PPC::CR2) {
01727       CR2Spilled = true;
01728       // The spill slot is associated only with CR2, which is the
01729       // first nonvolatile spilled.  Save it here.
01730       CSIIndex = i;
01731       continue;
01732     } else if (Reg == PPC::CR3) {
01733       CR3Spilled = true;
01734       continue;
01735     } else if (Reg == PPC::CR4) {
01736       CR4Spilled = true;
01737       continue;
01738     } else {
01739       // When we first encounter a non-CR register after seeing at
01740       // least one CR register, restore all spilled CRs together.
01741       if ((CR2Spilled || CR3Spilled || CR4Spilled)
01742           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
01743         bool is31 = needsFP(*MF);
01744         restoreCRs(Subtarget.isPPC64(), is31,
01745                    CR2Spilled, CR3Spilled, CR4Spilled,
01746                    MBB, I, CSI, CSIIndex);
01747         CR2Spilled = CR3Spilled = CR4Spilled = false;
01748       }
01749 
01750       // Default behavior for non-CR saves.
01751       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01752       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
01753                                RC, TRI);
01754       assert(I != MBB.begin() &&
01755              "loadRegFromStackSlot didn't insert any code!");
01756       }
01757 
01758     // Insert in reverse order.
01759     if (AtStart)
01760       I = MBB.begin();
01761     else {
01762       I = BeforeI;
01763       ++I;
01764     }
01765   }
01766 
01767   // If we haven't yet spilled the CRs, do so now.
01768   if (CR2Spilled || CR3Spilled || CR4Spilled) {
01769     bool is31 = needsFP(*MF);
01770     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
01771                MBB, I, CSI, CSIIndex);
01772   }
01773 
01774   return true;
01775 }
01776 
01777 bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
01778   return (MF.getSubtarget<PPCSubtarget>().isSVR4ABI() &&
01779           MF.getSubtarget<PPCSubtarget>().isPPC64());
01780 }