LLVM API Documentation

ARMFrameLowering.cpp
Go to the documentation of this file.
00001 //===-- ARMFrameLowering.cpp - ARM 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 ARM implementation of TargetFrameLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ARMFrameLowering.h"
00015 #include "ARMBaseInstrInfo.h"
00016 #include "ARMBaseRegisterInfo.h"
00017 #include "ARMMachineFunctionInfo.h"
00018 #include "MCTargetDesc/ARMAddressingModes.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/RegisterScavenging.h"
00024 #include "llvm/IR/CallingConv.h"
00025 #include "llvm/IR/Function.h"
00026 #include "llvm/Support/CommandLine.h"
00027 #include "llvm/Target/TargetOptions.h"
00028 
00029 using namespace llvm;
00030 
00031 static cl::opt<bool>
00032 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
00033                      cl::desc("Align ARM NEON spills in prolog and epilog"));
00034 
00035 static MachineBasicBlock::iterator
00036 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
00037                         unsigned NumAlignedDPRCS2Regs);
00038 
00039 /// hasFP - Return true if the specified function should have a dedicated frame
00040 /// pointer register.  This is true if the function has variable sized allocas
00041 /// or if frame pointer elimination is disabled.
00042 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
00043   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
00044 
00045   // iOS requires FP not to be clobbered for backtracing purpose.
00046   if (STI.isTargetIOS())
00047     return true;
00048 
00049   const MachineFrameInfo *MFI = MF.getFrameInfo();
00050   // Always eliminate non-leaf frame pointers.
00051   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
00052            MFI->hasCalls()) ||
00053           RegInfo->needsStackRealignment(MF) ||
00054           MFI->hasVarSizedObjects() ||
00055           MFI->isFrameAddressTaken());
00056 }
00057 
00058 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
00059 /// not required, we reserve argument space for call sites in the function
00060 /// immediately on entry to the current function.  This eliminates the need for
00061 /// add/sub sp brackets around call sites.  Returns true if the call frame is
00062 /// included as part of the stack frame.
00063 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
00064   const MachineFrameInfo *FFI = MF.getFrameInfo();
00065   unsigned CFSize = FFI->getMaxCallFrameSize();
00066   // It's not always a good idea to include the call frame as part of the
00067   // stack frame. ARM (especially Thumb) has small immediate offset to
00068   // address the stack frame. So a large call frame can cause poor codegen
00069   // and may even makes it impossible to scavenge a register.
00070   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
00071     return false;
00072 
00073   return !MF.getFrameInfo()->hasVarSizedObjects();
00074 }
00075 
00076 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
00077 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
00078 /// is not sufficient here since we still may reference some objects via SP
00079 /// even when FP is available in Thumb2 mode.
00080 bool
00081 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
00082   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
00083 }
00084 
00085 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
00086   for (unsigned i = 0; CSRegs[i]; ++i)
00087     if (Reg == CSRegs[i])
00088       return true;
00089   return false;
00090 }
00091 
00092 static bool isCSRestore(MachineInstr *MI,
00093                         const ARMBaseInstrInfo &TII,
00094                         const uint16_t *CSRegs) {
00095   // Integer spill area is handled with "pop".
00096   if (MI->getOpcode() == ARM::LDMIA_RET ||
00097       MI->getOpcode() == ARM::t2LDMIA_RET ||
00098       MI->getOpcode() == ARM::LDMIA_UPD ||
00099       MI->getOpcode() == ARM::t2LDMIA_UPD ||
00100       MI->getOpcode() == ARM::VLDMDIA_UPD) {
00101     // The first two operands are predicates. The last two are
00102     // imp-def and imp-use of SP. Check everything in between.
00103     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
00104       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
00105         return false;
00106     return true;
00107   }
00108   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
00109        MI->getOpcode() == ARM::LDR_POST_REG ||
00110        MI->getOpcode() == ARM::t2LDR_POST) &&
00111       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
00112       MI->getOperand(1).getReg() == ARM::SP)
00113     return true;
00114 
00115   return false;
00116 }
00117 
00118 static void
00119 emitSPUpdate(bool isARM,
00120              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
00121              DebugLoc dl, const ARMBaseInstrInfo &TII,
00122              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
00123              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
00124   if (isARM)
00125     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
00126                             Pred, PredReg, TII, MIFlags);
00127   else
00128     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
00129                            Pred, PredReg, TII, MIFlags);
00130 }
00131 
00132 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
00133   MachineBasicBlock &MBB = MF.front();
00134   MachineBasicBlock::iterator MBBI = MBB.begin();
00135   MachineFrameInfo  *MFI = MF.getFrameInfo();
00136   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00137   const ARMBaseRegisterInfo *RegInfo =
00138     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
00139   const ARMBaseInstrInfo &TII =
00140     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
00141   assert(!AFI->isThumb1OnlyFunction() &&
00142          "This emitPrologue does not support Thumb1!");
00143   bool isARM = !AFI->isThumbFunction();
00144   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
00145   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
00146   unsigned NumBytes = MFI->getStackSize();
00147   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00148   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
00149   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00150 
00151   // Determine the sizes of each callee-save spill areas and record which frame
00152   // belongs to which callee-save spill areas.
00153   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
00154   int FramePtrSpillFI = 0;
00155   int D8SpillFI = 0;
00156 
00157   // All calls are tail calls in GHC calling conv, and functions have no
00158   // prologue/epilogue.
00159   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
00160     return;
00161 
00162   // Allocate the vararg register save area. This is not counted in NumBytes.
00163   if (ArgRegsSaveSize)
00164     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
00165                  MachineInstr::FrameSetup);
00166 
00167   if (!AFI->hasStackFrame()) {
00168     if (NumBytes != 0)
00169       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
00170                    MachineInstr::FrameSetup);
00171     return;
00172   }
00173 
00174   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
00175     unsigned Reg = CSI[i].getReg();
00176     int FI = CSI[i].getFrameIdx();
00177     switch (Reg) {
00178     case ARM::R4:
00179     case ARM::R5:
00180     case ARM::R6:
00181     case ARM::R7:
00182     case ARM::LR:
00183       if (Reg == FramePtr)
00184         FramePtrSpillFI = FI;
00185       AFI->addGPRCalleeSavedArea1Frame(FI);
00186       GPRCS1Size += 4;
00187       break;
00188     case ARM::R8:
00189     case ARM::R9:
00190     case ARM::R10:
00191     case ARM::R11:
00192       if (Reg == FramePtr)
00193         FramePtrSpillFI = FI;
00194       if (STI.isTargetIOS()) {
00195         AFI->addGPRCalleeSavedArea2Frame(FI);
00196         GPRCS2Size += 4;
00197       } else {
00198         AFI->addGPRCalleeSavedArea1Frame(FI);
00199         GPRCS1Size += 4;
00200       }
00201       break;
00202     default:
00203       // This is a DPR. Exclude the aligned DPRCS2 spills.
00204       if (Reg == ARM::D8)
00205         D8SpillFI = FI;
00206       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
00207         AFI->addDPRCalleeSavedAreaFrame(FI);
00208         DPRCSSize += 8;
00209       }
00210     }
00211   }
00212 
00213   // Move past area 1.
00214   if (GPRCS1Size > 0) MBBI++;
00215 
00216   // Set FP to point to the stack slot that contains the previous FP.
00217   // For iOS, FP is R7, which has now been stored in spill area 1.
00218   // Otherwise, if this is not iOS, all the callee-saved registers go
00219   // into spill area 1, including the FP in R11.  In either case, it is
00220   // now safe to emit this assignment.
00221   bool HasFP = hasFP(MF);
00222   if (HasFP) {
00223     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
00224     MachineInstrBuilder MIB =
00225       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
00226       .addFrameIndex(FramePtrSpillFI).addImm(0)
00227       .setMIFlag(MachineInstr::FrameSetup);
00228     AddDefaultCC(AddDefaultPred(MIB));
00229   }
00230 
00231   // Move past area 2.
00232   if (GPRCS2Size > 0) MBBI++;
00233 
00234   // Determine starting offsets of spill areas.
00235   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
00236   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
00237   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
00238   if (HasFP)
00239     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
00240                                 NumBytes);
00241   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
00242   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
00243   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
00244 
00245   // Move past area 3.
00246   if (DPRCSSize > 0) {
00247     MBBI++;
00248     // Since vpush register list cannot have gaps, there may be multiple vpush
00249     // instructions in the prologue.
00250     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
00251       MBBI++;
00252   }
00253 
00254   // Move past the aligned DPRCS2 area.
00255   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
00256     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
00257     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
00258     // leaves the stack pointer pointing to the DPRCS2 area.
00259     //
00260     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
00261     NumBytes += MFI->getObjectOffset(D8SpillFI);
00262   } else
00263     NumBytes = DPRCSOffset;
00264 
00265   if (NumBytes) {
00266     // Adjust SP after all the callee-save spills.
00267     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
00268                  MachineInstr::FrameSetup);
00269     if (HasFP && isARM)
00270       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
00271       // Note it's not safe to do this in Thumb2 mode because it would have
00272       // taken two instructions:
00273       // mov sp, r7
00274       // sub sp, #24
00275       // If an interrupt is taken between the two instructions, then sp is in
00276       // an inconsistent state (pointing to the middle of callee-saved area).
00277       // The interrupt handler can end up clobbering the registers.
00278       AFI->setShouldRestoreSPFromFP(true);
00279   }
00280 
00281   if (STI.isTargetELF() && hasFP(MF))
00282     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
00283                              AFI->getFramePtrSpillOffset());
00284 
00285   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
00286   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
00287   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
00288 
00289   // If we need dynamic stack realignment, do it here. Be paranoid and make
00290   // sure if we also have VLAs, we have a base pointer for frame access.
00291   // If aligned NEON registers were spilled, the stack has already been
00292   // realigned.
00293   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
00294     unsigned MaxAlign = MFI->getMaxAlignment();
00295     assert (!AFI->isThumb1OnlyFunction());
00296     if (!AFI->isThumbFunction()) {
00297       // Emit bic sp, sp, MaxAlign
00298       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
00299                                           TII.get(ARM::BICri), ARM::SP)
00300                                   .addReg(ARM::SP, RegState::Kill)
00301                                   .addImm(MaxAlign-1)));
00302     } else {
00303       // We cannot use sp as source/dest register here, thus we're emitting the
00304       // following sequence:
00305       // mov r4, sp
00306       // bic r4, r4, MaxAlign
00307       // mov sp, r4
00308       // FIXME: It will be better just to find spare register here.
00309       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
00310         .addReg(ARM::SP, RegState::Kill));
00311       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
00312                                           TII.get(ARM::t2BICri), ARM::R4)
00313                                   .addReg(ARM::R4, RegState::Kill)
00314                                   .addImm(MaxAlign-1)));
00315       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
00316         .addReg(ARM::R4, RegState::Kill));
00317     }
00318 
00319     AFI->setShouldRestoreSPFromFP(true);
00320   }
00321 
00322   // If we need a base pointer, set it up here. It's whatever the value
00323   // of the stack pointer is at this point. Any variable size objects
00324   // will be allocated after this, so we can still use the base pointer
00325   // to reference locals.
00326   // FIXME: Clarify FrameSetup flags here.
00327   if (RegInfo->hasBasePointer(MF)) {
00328     if (isARM)
00329       BuildMI(MBB, MBBI, dl,
00330               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
00331         .addReg(ARM::SP)
00332         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
00333     else
00334       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
00335                              RegInfo->getBaseRegister())
00336         .addReg(ARM::SP));
00337   }
00338 
00339   // If the frame has variable sized objects then the epilogue must restore
00340   // the sp from fp. We can assume there's an FP here since hasFP already
00341   // checks for hasVarSizedObjects.
00342   if (MFI->hasVarSizedObjects())
00343     AFI->setShouldRestoreSPFromFP(true);
00344 }
00345 
00346 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
00347                                     MachineBasicBlock &MBB) const {
00348   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
00349   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
00350   unsigned RetOpcode = MBBI->getOpcode();
00351   DebugLoc dl = MBBI->getDebugLoc();
00352   MachineFrameInfo *MFI = MF.getFrameInfo();
00353   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00354   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
00355   const ARMBaseInstrInfo &TII =
00356     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
00357   assert(!AFI->isThumb1OnlyFunction() &&
00358          "This emitEpilogue does not support Thumb1!");
00359   bool isARM = !AFI->isThumbFunction();
00360 
00361   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
00362   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
00363   int NumBytes = (int)MFI->getStackSize();
00364   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00365 
00366   // All calls are tail calls in GHC calling conv, and functions have no
00367   // prologue/epilogue.
00368   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
00369     return;
00370 
00371   if (!AFI->hasStackFrame()) {
00372     if (NumBytes != 0)
00373       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
00374   } else {
00375     // Unwind MBBI to point to first LDR / VLDRD.
00376     const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
00377     if (MBBI != MBB.begin()) {
00378       do
00379         --MBBI;
00380       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
00381       if (!isCSRestore(MBBI, TII, CSRegs))
00382         ++MBBI;
00383     }
00384 
00385     // Move SP to start of FP callee save spill area.
00386     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
00387                  AFI->getGPRCalleeSavedArea2Size() +
00388                  AFI->getDPRCalleeSavedAreaSize());
00389 
00390     // Reset SP based on frame pointer only if the stack frame extends beyond
00391     // frame pointer stack slot or target is ELF and the function has FP.
00392     if (AFI->shouldRestoreSPFromFP()) {
00393       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
00394       if (NumBytes) {
00395         if (isARM)
00396           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
00397                                   ARMCC::AL, 0, TII);
00398         else {
00399           // It's not possible to restore SP from FP in a single instruction.
00400           // For iOS, this looks like:
00401           // mov sp, r7
00402           // sub sp, #24
00403           // This is bad, if an interrupt is taken after the mov, sp is in an
00404           // inconsistent state.
00405           // Use the first callee-saved register as a scratch register.
00406           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
00407                  "No scratch register to restore SP from FP!");
00408           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
00409                                  ARMCC::AL, 0, TII);
00410           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
00411                                  ARM::SP)
00412             .addReg(ARM::R4));
00413         }
00414       } else {
00415         // Thumb2 or ARM.
00416         if (isARM)
00417           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
00418             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
00419         else
00420           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
00421                                  ARM::SP)
00422             .addReg(FramePtr));
00423       }
00424     } else if (NumBytes)
00425       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
00426 
00427     // Increment past our save areas.
00428     if (AFI->getDPRCalleeSavedAreaSize()) {
00429       MBBI++;
00430       // Since vpop register list cannot have gaps, there may be multiple vpop
00431       // instructions in the epilogue.
00432       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
00433         MBBI++;
00434     }
00435     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
00436     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
00437   }
00438 
00439   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
00440     // Tail call return: adjust the stack pointer and jump to callee.
00441     MBBI = MBB.getLastNonDebugInstr();
00442     MachineOperand &JumpTarget = MBBI->getOperand(0);
00443 
00444     // Jump to label or value in register.
00445     if (RetOpcode == ARM::TCRETURNdi) {
00446       unsigned TCOpcode = STI.isThumb() ?
00447                (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
00448                ARM::TAILJMPd;
00449       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
00450       if (JumpTarget.isGlobal())
00451         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
00452                              JumpTarget.getTargetFlags());
00453       else {
00454         assert(JumpTarget.isSymbol());
00455         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
00456                               JumpTarget.getTargetFlags());
00457       }
00458 
00459       // Add the default predicate in Thumb mode.
00460       if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
00461     } else if (RetOpcode == ARM::TCRETURNri) {
00462       BuildMI(MBB, MBBI, dl,
00463               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
00464         addReg(JumpTarget.getReg(), RegState::Kill);
00465     }
00466 
00467     MachineInstr *NewMI = prior(MBBI);
00468     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
00469       NewMI->addOperand(MBBI->getOperand(i));
00470 
00471     // Delete the pseudo instruction TCRETURN.
00472     MBB.erase(MBBI);
00473     MBBI = NewMI;
00474   }
00475 
00476   if (ArgRegsSaveSize)
00477     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
00478 }
00479 
00480 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
00481 /// debug info.  It's the same as what we use for resolving the code-gen
00482 /// references for now.  FIXME: This can go wrong when references are
00483 /// SP-relative and simple call frames aren't used.
00484 int
00485 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
00486                                          unsigned &FrameReg) const {
00487   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
00488 }
00489 
00490 int
00491 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
00492                                              int FI, unsigned &FrameReg,
00493                                              int SPAdj) const {
00494   const MachineFrameInfo *MFI = MF.getFrameInfo();
00495   const ARMBaseRegisterInfo *RegInfo =
00496     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
00497   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00498   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
00499   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
00500   bool isFixed = MFI->isFixedObjectIndex(FI);
00501 
00502   FrameReg = ARM::SP;
00503   Offset += SPAdj;
00504   if (AFI->isGPRCalleeSavedArea1Frame(FI))
00505     return Offset - AFI->getGPRCalleeSavedArea1Offset();
00506   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
00507     return Offset - AFI->getGPRCalleeSavedArea2Offset();
00508   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
00509     return Offset - AFI->getDPRCalleeSavedAreaOffset();
00510 
00511   // SP can move around if there are allocas.  We may also lose track of SP
00512   // when emergency spilling inside a non-reserved call frame setup.
00513   bool hasMovingSP = !hasReservedCallFrame(MF);
00514 
00515   // When dynamically realigning the stack, use the frame pointer for
00516   // parameters, and the stack/base pointer for locals.
00517   if (RegInfo->needsStackRealignment(MF)) {
00518     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
00519     if (isFixed) {
00520       FrameReg = RegInfo->getFrameRegister(MF);
00521       Offset = FPOffset;
00522     } else if (hasMovingSP) {
00523       assert(RegInfo->hasBasePointer(MF) &&
00524              "VLAs and dynamic stack alignment, but missing base pointer!");
00525       FrameReg = RegInfo->getBaseRegister();
00526     }
00527     return Offset;
00528   }
00529 
00530   // If there is a frame pointer, use it when we can.
00531   if (hasFP(MF) && AFI->hasStackFrame()) {
00532     // Use frame pointer to reference fixed objects. Use it for locals if
00533     // there are VLAs (and thus the SP isn't reliable as a base).
00534     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
00535       FrameReg = RegInfo->getFrameRegister(MF);
00536       return FPOffset;
00537     } else if (hasMovingSP) {
00538       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
00539       if (AFI->isThumb2Function()) {
00540         // Try to use the frame pointer if we can, else use the base pointer
00541         // since it's available. This is handy for the emergency spill slot, in
00542         // particular.
00543         if (FPOffset >= -255 && FPOffset < 0) {
00544           FrameReg = RegInfo->getFrameRegister(MF);
00545           return FPOffset;
00546         }
00547       }
00548     } else if (AFI->isThumb2Function()) {
00549       // Use  add <rd>, sp, #<imm8>
00550       //      ldr <rd>, [sp, #<imm8>]
00551       // if at all possible to save space.
00552       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
00553         return Offset;
00554       // In Thumb2 mode, the negative offset is very limited. Try to avoid
00555       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
00556       if (FPOffset >= -255 && FPOffset < 0) {
00557         FrameReg = RegInfo->getFrameRegister(MF);
00558         return FPOffset;
00559       }
00560     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
00561       // Otherwise, use SP or FP, whichever is closer to the stack slot.
00562       FrameReg = RegInfo->getFrameRegister(MF);
00563       return FPOffset;
00564     }
00565   }
00566   // Use the base pointer if we have one.
00567   if (RegInfo->hasBasePointer(MF))
00568     FrameReg = RegInfo->getBaseRegister();
00569   return Offset;
00570 }
00571 
00572 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
00573                                           int FI) const {
00574   unsigned FrameReg;
00575   return getFrameIndexReference(MF, FI, FrameReg);
00576 }
00577 
00578 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
00579                                     MachineBasicBlock::iterator MI,
00580                                     const std::vector<CalleeSavedInfo> &CSI,
00581                                     unsigned StmOpc, unsigned StrOpc,
00582                                     bool NoGap,
00583                                     bool(*Func)(unsigned, bool),
00584                                     unsigned NumAlignedDPRCS2Regs,
00585                                     unsigned MIFlags) const {
00586   MachineFunction &MF = *MBB.getParent();
00587   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
00588 
00589   DebugLoc DL;
00590   if (MI != MBB.end()) DL = MI->getDebugLoc();
00591 
00592   SmallVector<std::pair<unsigned,bool>, 4> Regs;
00593   unsigned i = CSI.size();
00594   while (i != 0) {
00595     unsigned LastReg = 0;
00596     for (; i != 0; --i) {
00597       unsigned Reg = CSI[i-1].getReg();
00598       if (!(Func)(Reg, STI.isTargetIOS())) continue;
00599 
00600       // D-registers in the aligned area DPRCS2 are NOT spilled here.
00601       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
00602         continue;
00603 
00604       // Add the callee-saved register as live-in unless it's LR and
00605       // @llvm.returnaddress is called. If LR is returned for
00606       // @llvm.returnaddress then it's already added to the function and
00607       // entry block live-in sets.
00608       bool isKill = true;
00609       if (Reg == ARM::LR) {
00610         if (MF.getFrameInfo()->isReturnAddressTaken() &&
00611             MF.getRegInfo().isLiveIn(Reg))
00612           isKill = false;
00613       }
00614 
00615       if (isKill)
00616         MBB.addLiveIn(Reg);
00617 
00618       // If NoGap is true, push consecutive registers and then leave the rest
00619       // for other instructions. e.g.
00620       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
00621       if (NoGap && LastReg && LastReg != Reg-1)
00622         break;
00623       LastReg = Reg;
00624       Regs.push_back(std::make_pair(Reg, isKill));
00625     }
00626 
00627     if (Regs.empty())
00628       continue;
00629     if (Regs.size() > 1 || StrOpc== 0) {
00630       MachineInstrBuilder MIB =
00631         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
00632                        .addReg(ARM::SP).setMIFlags(MIFlags));
00633       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
00634         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
00635     } else if (Regs.size() == 1) {
00636       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
00637                                         ARM::SP)
00638         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
00639         .addReg(ARM::SP).setMIFlags(MIFlags)
00640         .addImm(-4);
00641       AddDefaultPred(MIB);
00642     }
00643     Regs.clear();
00644   }
00645 }
00646 
00647 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
00648                                    MachineBasicBlock::iterator MI,
00649                                    const std::vector<CalleeSavedInfo> &CSI,
00650                                    unsigned LdmOpc, unsigned LdrOpc,
00651                                    bool isVarArg, bool NoGap,
00652                                    bool(*Func)(unsigned, bool),
00653                                    unsigned NumAlignedDPRCS2Regs) const {
00654   MachineFunction &MF = *MBB.getParent();
00655   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
00656   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00657   DebugLoc DL = MI->getDebugLoc();
00658   unsigned RetOpcode = MI->getOpcode();
00659   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
00660                      RetOpcode == ARM::TCRETURNri);
00661 
00662   SmallVector<unsigned, 4> Regs;
00663   unsigned i = CSI.size();
00664   while (i != 0) {
00665     unsigned LastReg = 0;
00666     bool DeleteRet = false;
00667     for (; i != 0; --i) {
00668       unsigned Reg = CSI[i-1].getReg();
00669       if (!(Func)(Reg, STI.isTargetIOS())) continue;
00670 
00671       // The aligned reloads from area DPRCS2 are not inserted here.
00672       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
00673         continue;
00674 
00675       if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
00676         Reg = ARM::PC;
00677         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
00678         // Fold the return instruction into the LDM.
00679         DeleteRet = true;
00680       }
00681 
00682       // If NoGap is true, pop consecutive registers and then leave the rest
00683       // for other instructions. e.g.
00684       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
00685       if (NoGap && LastReg && LastReg != Reg-1)
00686         break;
00687 
00688       LastReg = Reg;
00689       Regs.push_back(Reg);
00690     }
00691 
00692     if (Regs.empty())
00693       continue;
00694     if (Regs.size() > 1 || LdrOpc == 0) {
00695       MachineInstrBuilder MIB =
00696         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
00697                        .addReg(ARM::SP));
00698       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
00699         MIB.addReg(Regs[i], getDefRegState(true));
00700       if (DeleteRet) {
00701         MIB.copyImplicitOps(&*MI);
00702         MI->eraseFromParent();
00703       }
00704       MI = MIB;
00705     } else if (Regs.size() == 1) {
00706       // If we adjusted the reg to PC from LR above, switch it back here. We
00707       // only do that for LDM.
00708       if (Regs[0] == ARM::PC)
00709         Regs[0] = ARM::LR;
00710       MachineInstrBuilder MIB =
00711         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
00712           .addReg(ARM::SP, RegState::Define)
00713           .addReg(ARM::SP);
00714       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
00715       // that refactoring is complete (eventually).
00716       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
00717         MIB.addReg(0);
00718         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
00719       } else
00720         MIB.addImm(4);
00721       AddDefaultPred(MIB);
00722     }
00723     Regs.clear();
00724   }
00725 }
00726 
00727 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
00728 /// starting from d8.  Also insert stack realignment code and leave the stack
00729 /// pointer pointing to the d8 spill slot.
00730 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
00731                                     MachineBasicBlock::iterator MI,
00732                                     unsigned NumAlignedDPRCS2Regs,
00733                                     const std::vector<CalleeSavedInfo> &CSI,
00734                                     const TargetRegisterInfo *TRI) {
00735   MachineFunction &MF = *MBB.getParent();
00736   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00737   DebugLoc DL = MI->getDebugLoc();
00738   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
00739   MachineFrameInfo &MFI = *MF.getFrameInfo();
00740 
00741   // Mark the D-register spill slots as properly aligned.  Since MFI computes
00742   // stack slot layout backwards, this can actually mean that the d-reg stack
00743   // slot offsets can be wrong. The offset for d8 will always be correct.
00744   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
00745     unsigned DNum = CSI[i].getReg() - ARM::D8;
00746     if (DNum >= 8)
00747       continue;
00748     int FI = CSI[i].getFrameIdx();
00749     // The even-numbered registers will be 16-byte aligned, the odd-numbered
00750     // registers will be 8-byte aligned.
00751     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
00752 
00753     // The stack slot for D8 needs to be maximally aligned because this is
00754     // actually the point where we align the stack pointer.  MachineFrameInfo
00755     // computes all offsets relative to the incoming stack pointer which is a
00756     // bit weird when realigning the stack.  Any extra padding for this
00757     // over-alignment is not realized because the code inserted below adjusts
00758     // the stack pointer by numregs * 8 before aligning the stack pointer.
00759     if (DNum == 0)
00760       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
00761   }
00762 
00763   // Move the stack pointer to the d8 spill slot, and align it at the same
00764   // time. Leave the stack slot address in the scratch register r4.
00765   //
00766   //   sub r4, sp, #numregs * 8
00767   //   bic r4, r4, #align - 1
00768   //   mov sp, r4
00769   //
00770   bool isThumb = AFI->isThumbFunction();
00771   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
00772   AFI->setShouldRestoreSPFromFP(true);
00773 
00774   // sub r4, sp, #numregs * 8
00775   // The immediate is <= 64, so it doesn't need any special encoding.
00776   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
00777   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
00778                               .addReg(ARM::SP)
00779                               .addImm(8 * NumAlignedDPRCS2Regs)));
00780 
00781   // bic r4, r4, #align-1
00782   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
00783   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
00784   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
00785                               .addReg(ARM::R4, RegState::Kill)
00786                               .addImm(MaxAlign - 1)));
00787 
00788   // mov sp, r4
00789   // The stack pointer must be adjusted before spilling anything, otherwise
00790   // the stack slots could be clobbered by an interrupt handler.
00791   // Leave r4 live, it is used below.
00792   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
00793   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
00794                             .addReg(ARM::R4);
00795   MIB = AddDefaultPred(MIB);
00796   if (!isThumb)
00797     AddDefaultCC(MIB);
00798 
00799   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
00800   // r4 holds the stack slot address.
00801   unsigned NextReg = ARM::D8;
00802 
00803   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
00804   // The writeback is only needed when emitting two vst1.64 instructions.
00805   if (NumAlignedDPRCS2Regs >= 6) {
00806     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00807                                                &ARM::QQPRRegClass);
00808     MBB.addLiveIn(SupReg);
00809     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
00810                            ARM::R4)
00811                    .addReg(ARM::R4, RegState::Kill).addImm(16)
00812                    .addReg(NextReg)
00813                    .addReg(SupReg, RegState::ImplicitKill));
00814     NextReg += 4;
00815     NumAlignedDPRCS2Regs -= 4;
00816   }
00817 
00818   // We won't modify r4 beyond this point.  It currently points to the next
00819   // register to be spilled.
00820   unsigned R4BaseReg = NextReg;
00821 
00822   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
00823   if (NumAlignedDPRCS2Regs >= 4) {
00824     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00825                                                &ARM::QQPRRegClass);
00826     MBB.addLiveIn(SupReg);
00827     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
00828                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
00829                    .addReg(SupReg, RegState::ImplicitKill));
00830     NextReg += 4;
00831     NumAlignedDPRCS2Regs -= 4;
00832   }
00833 
00834   // 16-byte aligned vst1.64 with 2 d-regs.
00835   if (NumAlignedDPRCS2Regs >= 2) {
00836     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00837                                                &ARM::QPRRegClass);
00838     MBB.addLiveIn(SupReg);
00839     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
00840                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
00841     NextReg += 2;
00842     NumAlignedDPRCS2Regs -= 2;
00843   }
00844 
00845   // Finally, use a vanilla vstr.64 for the odd last register.
00846   if (NumAlignedDPRCS2Regs) {
00847     MBB.addLiveIn(NextReg);
00848     // vstr.64 uses addrmode5 which has an offset scale of 4.
00849     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
00850                    .addReg(NextReg)
00851                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
00852   }
00853 
00854   // The last spill instruction inserted should kill the scratch register r4.
00855   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
00856 }
00857 
00858 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
00859 /// iterator to the following instruction.
00860 static MachineBasicBlock::iterator
00861 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
00862                         unsigned NumAlignedDPRCS2Regs) {
00863   //   sub r4, sp, #numregs * 8
00864   //   bic r4, r4, #align - 1
00865   //   mov sp, r4
00866   ++MI; ++MI; ++MI;
00867   assert(MI->mayStore() && "Expecting spill instruction");
00868 
00869   // These switches all fall through.
00870   switch(NumAlignedDPRCS2Regs) {
00871   case 7:
00872     ++MI;
00873     assert(MI->mayStore() && "Expecting spill instruction");
00874   default:
00875     ++MI;
00876     assert(MI->mayStore() && "Expecting spill instruction");
00877   case 1:
00878   case 2:
00879   case 4:
00880     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
00881     ++MI;
00882   }
00883   return MI;
00884 }
00885 
00886 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
00887 /// starting from d8.  These instructions are assumed to execute while the
00888 /// stack is still aligned, unlike the code inserted by emitPopInst.
00889 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
00890                                       MachineBasicBlock::iterator MI,
00891                                       unsigned NumAlignedDPRCS2Regs,
00892                                       const std::vector<CalleeSavedInfo> &CSI,
00893                                       const TargetRegisterInfo *TRI) {
00894   MachineFunction &MF = *MBB.getParent();
00895   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00896   DebugLoc DL = MI->getDebugLoc();
00897   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
00898 
00899   // Find the frame index assigned to d8.
00900   int D8SpillFI = 0;
00901   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
00902     if (CSI[i].getReg() == ARM::D8) {
00903       D8SpillFI = CSI[i].getFrameIdx();
00904       break;
00905     }
00906 
00907   // Materialize the address of the d8 spill slot into the scratch register r4.
00908   // This can be fairly complicated if the stack frame is large, so just use
00909   // the normal frame index elimination mechanism to do it.  This code runs as
00910   // the initial part of the epilog where the stack and base pointers haven't
00911   // been changed yet.
00912   bool isThumb = AFI->isThumbFunction();
00913   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
00914 
00915   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
00916   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
00917                               .addFrameIndex(D8SpillFI).addImm(0)));
00918 
00919   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
00920   unsigned NextReg = ARM::D8;
00921 
00922   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
00923   if (NumAlignedDPRCS2Regs >= 6) {
00924     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00925                                                &ARM::QQPRRegClass);
00926     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
00927                    .addReg(ARM::R4, RegState::Define)
00928                    .addReg(ARM::R4, RegState::Kill).addImm(16)
00929                    .addReg(SupReg, RegState::ImplicitDefine));
00930     NextReg += 4;
00931     NumAlignedDPRCS2Regs -= 4;
00932   }
00933 
00934   // We won't modify r4 beyond this point.  It currently points to the next
00935   // register to be spilled.
00936   unsigned R4BaseReg = NextReg;
00937 
00938   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
00939   if (NumAlignedDPRCS2Regs >= 4) {
00940     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00941                                                &ARM::QQPRRegClass);
00942     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
00943                    .addReg(ARM::R4).addImm(16)
00944                    .addReg(SupReg, RegState::ImplicitDefine));
00945     NextReg += 4;
00946     NumAlignedDPRCS2Regs -= 4;
00947   }
00948 
00949   // 16-byte aligned vld1.64 with 2 d-regs.
00950   if (NumAlignedDPRCS2Regs >= 2) {
00951     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
00952                                                &ARM::QPRRegClass);
00953     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
00954                    .addReg(ARM::R4).addImm(16));
00955     NextReg += 2;
00956     NumAlignedDPRCS2Regs -= 2;
00957   }
00958 
00959   // Finally, use a vanilla vldr.64 for the remaining odd register.
00960   if (NumAlignedDPRCS2Regs)
00961     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
00962                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
00963 
00964   // Last store kills r4.
00965   llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
00966 }
00967 
00968 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
00969                                         MachineBasicBlock::iterator MI,
00970                                         const std::vector<CalleeSavedInfo> &CSI,
00971                                         const TargetRegisterInfo *TRI) const {
00972   if (CSI.empty())
00973     return false;
00974 
00975   MachineFunction &MF = *MBB.getParent();
00976   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00977 
00978   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
00979   unsigned PushOneOpc = AFI->isThumbFunction() ?
00980     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
00981   unsigned FltOpc = ARM::VSTMDDB_UPD;
00982   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
00983   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
00984                MachineInstr::FrameSetup);
00985   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
00986                MachineInstr::FrameSetup);
00987   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
00988                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
00989 
00990   // The code above does not insert spill code for the aligned DPRCS2 registers.
00991   // The stack realignment code will be inserted between the push instructions
00992   // and these spills.
00993   if (NumAlignedDPRCS2Regs)
00994     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
00995 
00996   return true;
00997 }
00998 
00999 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01000                                         MachineBasicBlock::iterator MI,
01001                                         const std::vector<CalleeSavedInfo> &CSI,
01002                                         const TargetRegisterInfo *TRI) const {
01003   if (CSI.empty())
01004     return false;
01005 
01006   MachineFunction &MF = *MBB.getParent();
01007   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01008   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
01009   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
01010 
01011   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
01012   // registers. Do that here instead.
01013   if (NumAlignedDPRCS2Regs)
01014     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
01015 
01016   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
01017   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
01018   unsigned FltOpc = ARM::VLDMDIA_UPD;
01019   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
01020               NumAlignedDPRCS2Regs);
01021   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
01022               &isARMArea2Register, 0);
01023   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
01024               &isARMArea1Register, 0);
01025 
01026   return true;
01027 }
01028 
01029 // FIXME: Make generic?
01030 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
01031                                        const ARMBaseInstrInfo &TII) {
01032   unsigned FnSize = 0;
01033   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
01034        MBBI != E; ++MBBI) {
01035     const MachineBasicBlock &MBB = *MBBI;
01036     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
01037          I != E; ++I)
01038       FnSize += TII.GetInstSizeInBytes(I);
01039   }
01040   return FnSize;
01041 }
01042 
01043 /// estimateRSStackSizeLimit - Look at each instruction that references stack
01044 /// frames and return the stack size limit beyond which some of these
01045 /// instructions will require a scratch register during their expansion later.
01046 // FIXME: Move to TII?
01047 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
01048                                          const TargetFrameLowering *TFI) {
01049   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01050   unsigned Limit = (1 << 12) - 1;
01051   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
01052     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
01053          I != E; ++I) {
01054       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
01055         if (!I->getOperand(i).isFI()) continue;
01056 
01057         // When using ADDri to get the address of a stack object, 255 is the
01058         // largest offset guaranteed to fit in the immediate offset.
01059         if (I->getOpcode() == ARM::ADDri) {
01060           Limit = std::min(Limit, (1U << 8) - 1);
01061           break;
01062         }
01063 
01064         // Otherwise check the addressing mode.
01065         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
01066         case ARMII::AddrMode3:
01067         case ARMII::AddrModeT2_i8:
01068           Limit = std::min(Limit, (1U << 8) - 1);
01069           break;
01070         case ARMII::AddrMode5:
01071         case ARMII::AddrModeT2_i8s4:
01072           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
01073           break;
01074         case ARMII::AddrModeT2_i12:
01075           // i12 supports only positive offset so these will be converted to
01076           // i8 opcodes. See llvm::rewriteT2FrameIndex.
01077           if (TFI->hasFP(MF) && AFI->hasStackFrame())
01078             Limit = std::min(Limit, (1U << 8) - 1);
01079           break;
01080         case ARMII::AddrMode4:
01081         case ARMII::AddrMode6:
01082           // Addressing modes 4 & 6 (load/store) instructions can't encode an
01083           // immediate offset for stack references.
01084           return 0;
01085         default:
01086           break;
01087         }
01088         break; // At most one FI per instruction
01089       }
01090     }
01091   }
01092 
01093   return Limit;
01094 }
01095 
01096 // In functions that realign the stack, it can be an advantage to spill the
01097 // callee-saved vector registers after realigning the stack. The vst1 and vld1
01098 // instructions take alignment hints that can improve performance.
01099 //
01100 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
01101   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
01102   if (!SpillAlignedNEONRegs)
01103     return;
01104 
01105   // Naked functions don't spill callee-saved registers.
01106   if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
01107                                                      Attribute::Naked))
01108     return;
01109 
01110   // We are planning to use NEON instructions vst1 / vld1.
01111   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
01112     return;
01113 
01114   // Don't bother if the default stack alignment is sufficiently high.
01115   if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
01116     return;
01117 
01118   // Aligned spills require stack realignment.
01119   const ARMBaseRegisterInfo *RegInfo =
01120     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
01121   if (!RegInfo->canRealignStack(MF))
01122     return;
01123 
01124   // We always spill contiguous d-registers starting from d8. Count how many
01125   // needs spilling.  The register allocator will almost always use the
01126   // callee-saved registers in order, but it can happen that there are holes in
01127   // the range.  Registers above the hole will be spilled to the standard DPRCS
01128   // area.
01129   MachineRegisterInfo &MRI = MF.getRegInfo();
01130   unsigned NumSpills = 0;
01131   for (; NumSpills < 8; ++NumSpills)
01132     if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
01133       break;
01134 
01135   // Don't do this for just one d-register. It's not worth it.
01136   if (NumSpills < 2)
01137     return;
01138 
01139   // Spill the first NumSpills D-registers after realigning the stack.
01140   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
01141 
01142   // A scratch register is required for the vst1 / vld1 instructions.
01143   MF.getRegInfo().setPhysRegUsed(ARM::R4);
01144 }
01145 
01146 void
01147 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
01148                                                        RegScavenger *RS) const {
01149   // This tells PEI to spill the FP as if it is any other callee-save register
01150   // to take advantage the eliminateFrameIndex machinery. This also ensures it
01151   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
01152   // to combine multiple loads / stores.
01153   bool CanEliminateFrame = true;
01154   bool CS1Spilled = false;
01155   bool LRSpilled = false;
01156   unsigned NumGPRSpills = 0;
01157   SmallVector<unsigned, 4> UnspilledCS1GPRs;
01158   SmallVector<unsigned, 4> UnspilledCS2GPRs;
01159   const ARMBaseRegisterInfo *RegInfo =
01160     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
01161   const ARMBaseInstrInfo &TII =
01162     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
01163   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01164   MachineFrameInfo *MFI = MF.getFrameInfo();
01165   MachineRegisterInfo &MRI = MF.getRegInfo();
01166   unsigned FramePtr = RegInfo->getFrameRegister(MF);
01167 
01168   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
01169   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
01170   // since it's not always possible to restore sp from fp in a single
01171   // instruction.
01172   // FIXME: It will be better just to find spare register here.
01173   if (AFI->isThumb2Function() &&
01174       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
01175     MRI.setPhysRegUsed(ARM::R4);
01176 
01177   if (AFI->isThumb1OnlyFunction()) {
01178     // Spill LR if Thumb1 function uses variable length argument lists.
01179     if (AFI->getArgRegsSaveSize() > 0)
01180       MRI.setPhysRegUsed(ARM::LR);
01181 
01182     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
01183     // for sure what the stack size will be, but for this, an estimate is good
01184     // enough. If there anything changes it, it'll be a spill, which implies
01185     // we've used all the registers and so R4 is already used, so not marking
01186     // it here will be OK.
01187     // FIXME: It will be better just to find spare register here.
01188     unsigned StackSize = MFI->estimateStackSize(MF);
01189     if (MFI->hasVarSizedObjects() || StackSize > 508)
01190       MRI.setPhysRegUsed(ARM::R4);
01191   }
01192 
01193   // See if we can spill vector registers to aligned stack.
01194   checkNumAlignedDPRCS2Regs(MF);
01195 
01196   // Spill the BasePtr if it's used.
01197   if (RegInfo->hasBasePointer(MF))
01198     MRI.setPhysRegUsed(RegInfo->getBaseRegister());
01199 
01200   // Don't spill FP if the frame can be eliminated. This is determined
01201   // by scanning the callee-save registers to see if any is used.
01202   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
01203   for (unsigned i = 0; CSRegs[i]; ++i) {
01204     unsigned Reg = CSRegs[i];
01205     bool Spilled = false;
01206     if (MRI.isPhysRegUsed(Reg)) {
01207       Spilled = true;
01208       CanEliminateFrame = false;
01209     }
01210 
01211     if (!ARM::GPRRegClass.contains(Reg))
01212       continue;
01213 
01214     if (Spilled) {
01215       NumGPRSpills++;
01216 
01217       if (!STI.isTargetIOS()) {
01218         if (Reg == ARM::LR)
01219           LRSpilled = true;
01220         CS1Spilled = true;
01221         continue;
01222       }
01223 
01224       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
01225       switch (Reg) {
01226       case ARM::LR:
01227         LRSpilled = true;
01228         // Fallthrough
01229       case ARM::R4: case ARM::R5:
01230       case ARM::R6: case ARM::R7:
01231         CS1Spilled = true;
01232         break;
01233       default:
01234         break;
01235       }
01236     } else {
01237       if (!STI.isTargetIOS()) {
01238         UnspilledCS1GPRs.push_back(Reg);
01239         continue;
01240       }
01241 
01242       switch (Reg) {
01243       case ARM::R4: case ARM::R5:
01244       case ARM::R6: case ARM::R7:
01245       case ARM::LR:
01246         UnspilledCS1GPRs.push_back(Reg);
01247         break;
01248       default:
01249         UnspilledCS2GPRs.push_back(Reg);
01250         break;
01251       }
01252     }
01253   }
01254 
01255   bool ForceLRSpill = false;
01256   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
01257     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
01258     // Force LR to be spilled if the Thumb function size is > 2048. This enables
01259     // use of BL to implement far jump. If it turns out that it's not needed
01260     // then the branch fix up path will undo it.
01261     if (FnSize >= (1 << 11)) {
01262       CanEliminateFrame = false;
01263       ForceLRSpill = true;
01264     }
01265   }
01266 
01267   // If any of the stack slot references may be out of range of an immediate
01268   // offset, make sure a register (or a spill slot) is available for the
01269   // register scavenger. Note that if we're indexing off the frame pointer, the
01270   // effective stack size is 4 bytes larger since the FP points to the stack
01271   // slot of the previous FP. Also, if we have variable sized objects in the
01272   // function, stack slot references will often be negative, and some of
01273   // our instructions are positive-offset only, so conservatively consider
01274   // that case to want a spill slot (or register) as well. Similarly, if
01275   // the function adjusts the stack pointer during execution and the
01276   // adjustments aren't already part of our stack size estimate, our offset
01277   // calculations may be off, so be conservative.
01278   // FIXME: We could add logic to be more precise about negative offsets
01279   //        and which instructions will need a scratch register for them. Is it
01280   //        worth the effort and added fragility?
01281   bool BigStack =
01282     (RS &&
01283      (MFI->estimateStackSize(MF) +
01284       ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
01285       estimateRSStackSizeLimit(MF, this)))
01286     || MFI->hasVarSizedObjects()
01287     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
01288 
01289   bool ExtraCSSpill = false;
01290   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
01291     AFI->setHasStackFrame(true);
01292 
01293     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
01294     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
01295     if (!LRSpilled && CS1Spilled) {
01296       MRI.setPhysRegUsed(ARM::LR);
01297       NumGPRSpills++;
01298       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
01299                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
01300       ForceLRSpill = false;
01301       ExtraCSSpill = true;
01302     }
01303 
01304     if (hasFP(MF)) {
01305       MRI.setPhysRegUsed(FramePtr);
01306       NumGPRSpills++;
01307     }
01308 
01309     // If stack and double are 8-byte aligned and we are spilling an odd number
01310     // of GPRs, spill one extra callee save GPR so we won't have to pad between
01311     // the integer and double callee save areas.
01312     unsigned TargetAlign = getStackAlignment();
01313     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
01314       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
01315         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
01316           unsigned Reg = UnspilledCS1GPRs[i];
01317           // Don't spill high register if the function is thumb1
01318           if (!AFI->isThumb1OnlyFunction() ||
01319               isARMLowRegister(Reg) || Reg == ARM::LR) {
01320             MRI.setPhysRegUsed(Reg);
01321             if (!MRI.isReserved(Reg))
01322               ExtraCSSpill = true;
01323             break;
01324           }
01325         }
01326       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
01327         unsigned Reg = UnspilledCS2GPRs.front();
01328         MRI.setPhysRegUsed(Reg);
01329         if (!MRI.isReserved(Reg))
01330           ExtraCSSpill = true;
01331       }
01332     }
01333 
01334     // Estimate if we might need to scavenge a register at some point in order
01335     // to materialize a stack offset. If so, either spill one additional
01336     // callee-saved register or reserve a special spill slot to facilitate
01337     // register scavenging. Thumb1 needs a spill slot for stack pointer
01338     // adjustments also, even when the frame itself is small.
01339     if (BigStack && !ExtraCSSpill) {
01340       // If any non-reserved CS register isn't spilled, just spill one or two
01341       // extra. That should take care of it!
01342       unsigned NumExtras = TargetAlign / 4;
01343       SmallVector<unsigned, 2> Extras;
01344       while (NumExtras && !UnspilledCS1GPRs.empty()) {
01345         unsigned Reg = UnspilledCS1GPRs.back();
01346         UnspilledCS1GPRs.pop_back();
01347         if (!MRI.isReserved(Reg) &&
01348             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
01349              Reg == ARM::LR)) {
01350           Extras.push_back(Reg);
01351           NumExtras--;
01352         }
01353       }
01354       // For non-Thumb1 functions, also check for hi-reg CS registers
01355       if (!AFI->isThumb1OnlyFunction()) {
01356         while (NumExtras && !UnspilledCS2GPRs.empty()) {
01357           unsigned Reg = UnspilledCS2GPRs.back();
01358           UnspilledCS2GPRs.pop_back();
01359           if (!MRI.isReserved(Reg)) {
01360             Extras.push_back(Reg);
01361             NumExtras--;
01362           }
01363         }
01364       }
01365       if (Extras.size() && NumExtras == 0) {
01366         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
01367           MRI.setPhysRegUsed(Extras[i]);
01368         }
01369       } else if (!AFI->isThumb1OnlyFunction()) {
01370         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
01371         // closest to SP or frame pointer.
01372         const TargetRegisterClass *RC = &ARM::GPRRegClass;
01373         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01374                                                            RC->getAlignment(),
01375                                                            false));
01376       }
01377     }
01378   }
01379 
01380   if (ForceLRSpill) {
01381     MRI.setPhysRegUsed(ARM::LR);
01382     AFI->setLRIsSpilledForFarJump(true);
01383   }
01384 }
01385 
01386 
01387 void ARMFrameLowering::
01388 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01389                               MachineBasicBlock::iterator I) const {
01390   const ARMBaseInstrInfo &TII =
01391     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
01392   if (!hasReservedCallFrame(MF)) {
01393     // If we have alloca, convert as follows:
01394     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
01395     // ADJCALLSTACKUP   -> add, sp, sp, amount
01396     MachineInstr *Old = I;
01397     DebugLoc dl = Old->getDebugLoc();
01398     unsigned Amount = Old->getOperand(0).getImm();
01399     if (Amount != 0) {
01400       // We need to keep the stack aligned properly.  To do this, we round the
01401       // amount of space needed for the outgoing arguments up to the next
01402       // alignment boundary.
01403       unsigned Align = getStackAlignment();
01404       Amount = (Amount+Align-1)/Align*Align;
01405 
01406       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01407       assert(!AFI->isThumb1OnlyFunction() &&
01408              "This eliminateCallFramePseudoInstr does not support Thumb1!");
01409       bool isARM = !AFI->isThumbFunction();
01410 
01411       // Replace the pseudo instruction with a new instruction...
01412       unsigned Opc = Old->getOpcode();
01413       int PIdx = Old->findFirstPredOperandIdx();
01414       ARMCC::CondCodes Pred = (PIdx == -1)
01415         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
01416       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
01417         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
01418         unsigned PredReg = Old->getOperand(2).getReg();
01419         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
01420                      Pred, PredReg);
01421       } else {
01422         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
01423         unsigned PredReg = Old->getOperand(3).getReg();
01424         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
01425         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
01426                      Pred, PredReg);
01427       }
01428     }
01429   }
01430   MBB.erase(I);
01431 }
01432