1dff0c46cSDimitry Andric //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
22754fe60SDimitry Andric //
32754fe60SDimitry Andric //                     The LLVM Compiler Infrastructure
42754fe60SDimitry Andric //
52754fe60SDimitry Andric // This file is distributed under the University of Illinois Open Source
62754fe60SDimitry Andric // License. See LICENSE.TXT for details.
72754fe60SDimitry Andric //
82754fe60SDimitry Andric //===----------------------------------------------------------------------===//
92754fe60SDimitry Andric //
102754fe60SDimitry Andric // This file contains the ARM implementation of TargetFrameLowering class.
112754fe60SDimitry Andric //
122754fe60SDimitry Andric //===----------------------------------------------------------------------===//
132754fe60SDimitry Andric 
142754fe60SDimitry Andric #include "ARMFrameLowering.h"
152754fe60SDimitry Andric #include "ARMBaseInstrInfo.h"
162754fe60SDimitry Andric #include "ARMBaseRegisterInfo.h"
1791bc56edSDimitry Andric #include "ARMConstantPoolValue.h"
182754fe60SDimitry Andric #include "ARMMachineFunctionInfo.h"
196122f3e6SDimitry Andric #include "MCTargetDesc/ARMAddressingModes.h"
202754fe60SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
212754fe60SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
222754fe60SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
2391bc56edSDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
242754fe60SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
252754fe60SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
26139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
2891bc56edSDimitry Andric #include "llvm/MC/MCContext.h"
29dff0c46cSDimitry Andric #include "llvm/Support/CommandLine.h"
30139f7f9bSDimitry Andric #include "llvm/Target/TargetOptions.h"
312754fe60SDimitry Andric 
322754fe60SDimitry Andric using namespace llvm;
332754fe60SDimitry Andric 
34dff0c46cSDimitry Andric static cl::opt<bool>
35dff0c46cSDimitry Andric SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36dff0c46cSDimitry Andric                      cl::desc("Align ARM NEON spills in prolog and epilog"));
37dff0c46cSDimitry Andric 
38dff0c46cSDimitry Andric static MachineBasicBlock::iterator
39dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs);
41dff0c46cSDimitry Andric 
4291bc56edSDimitry Andric ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
4391bc56edSDimitry Andric     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
4491bc56edSDimitry Andric       STI(sti) {}
4591bc56edSDimitry Andric 
462754fe60SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
472754fe60SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
482754fe60SDimitry Andric /// or if frame pointer elimination is disabled.
492754fe60SDimitry Andric bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
502754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
512754fe60SDimitry Andric 
52dff0c46cSDimitry Andric   // iOS requires FP not to be clobbered for backtracing purpose.
53dff0c46cSDimitry Andric   if (STI.isTargetIOS())
542754fe60SDimitry Andric     return true;
552754fe60SDimitry Andric 
562754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
572754fe60SDimitry Andric   // Always eliminate non-leaf frame pointers.
58dff0c46cSDimitry Andric   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
59dff0c46cSDimitry Andric            MFI->hasCalls()) ||
602754fe60SDimitry Andric           RegInfo->needsStackRealignment(MF) ||
612754fe60SDimitry Andric           MFI->hasVarSizedObjects() ||
622754fe60SDimitry Andric           MFI->isFrameAddressTaken());
632754fe60SDimitry Andric }
642754fe60SDimitry Andric 
652754fe60SDimitry Andric /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
662754fe60SDimitry Andric /// not required, we reserve argument space for call sites in the function
672754fe60SDimitry Andric /// immediately on entry to the current function.  This eliminates the need for
682754fe60SDimitry Andric /// add/sub sp brackets around call sites.  Returns true if the call frame is
692754fe60SDimitry Andric /// included as part of the stack frame.
702754fe60SDimitry Andric bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
712754fe60SDimitry Andric   const MachineFrameInfo *FFI = MF.getFrameInfo();
722754fe60SDimitry Andric   unsigned CFSize = FFI->getMaxCallFrameSize();
732754fe60SDimitry Andric   // It's not always a good idea to include the call frame as part of the
742754fe60SDimitry Andric   // stack frame. ARM (especially Thumb) has small immediate offset to
752754fe60SDimitry Andric   // address the stack frame. So a large call frame can cause poor codegen
762754fe60SDimitry Andric   // and may even makes it impossible to scavenge a register.
772754fe60SDimitry Andric   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
782754fe60SDimitry Andric     return false;
792754fe60SDimitry Andric 
802754fe60SDimitry Andric   return !MF.getFrameInfo()->hasVarSizedObjects();
812754fe60SDimitry Andric }
822754fe60SDimitry Andric 
832754fe60SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
842754fe60SDimitry Andric /// call frame pseudos can be simplified.  Unlike most targets, having a FP
852754fe60SDimitry Andric /// is not sufficient here since we still may reference some objects via SP
862754fe60SDimitry Andric /// even when FP is available in Thumb2 mode.
872754fe60SDimitry Andric bool
882754fe60SDimitry Andric ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
892754fe60SDimitry Andric   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
902754fe60SDimitry Andric }
912754fe60SDimitry Andric 
922754fe60SDimitry Andric static bool isCSRestore(MachineInstr *MI,
932754fe60SDimitry Andric                         const ARMBaseInstrInfo &TII,
9491bc56edSDimitry Andric                         const MCPhysReg *CSRegs) {
952754fe60SDimitry Andric   // Integer spill area is handled with "pop".
96f785676fSDimitry Andric   if (isPopOpcode(MI->getOpcode())) {
972754fe60SDimitry Andric     // The first two operands are predicates. The last two are
982754fe60SDimitry Andric     // imp-def and imp-use of SP. Check everything in between.
992754fe60SDimitry Andric     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
1002754fe60SDimitry Andric       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
1012754fe60SDimitry Andric         return false;
1022754fe60SDimitry Andric     return true;
1032754fe60SDimitry Andric   }
1046122f3e6SDimitry Andric   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
1056122f3e6SDimitry Andric        MI->getOpcode() == ARM::LDR_POST_REG ||
1062754fe60SDimitry Andric        MI->getOpcode() == ARM::t2LDR_POST) &&
1072754fe60SDimitry Andric       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
1082754fe60SDimitry Andric       MI->getOperand(1).getReg() == ARM::SP)
1092754fe60SDimitry Andric     return true;
1102754fe60SDimitry Andric 
1112754fe60SDimitry Andric   return false;
1122754fe60SDimitry Andric }
1132754fe60SDimitry Andric 
114f785676fSDimitry Andric static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115f785676fSDimitry Andric                                  MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116f785676fSDimitry Andric                                  const ARMBaseInstrInfo &TII, unsigned DestReg,
117f785676fSDimitry Andric                                  unsigned SrcReg, int NumBytes,
118f785676fSDimitry Andric                                  unsigned MIFlags = MachineInstr::NoFlags,
119f785676fSDimitry Andric                                  ARMCC::CondCodes Pred = ARMCC::AL,
120f785676fSDimitry Andric                                  unsigned PredReg = 0) {
1212754fe60SDimitry Andric   if (isARM)
122f785676fSDimitry Andric     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123139f7f9bSDimitry Andric                             Pred, PredReg, TII, MIFlags);
1242754fe60SDimitry Andric   else
125f785676fSDimitry Andric     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126139f7f9bSDimitry Andric                            Pred, PredReg, TII, MIFlags);
1272754fe60SDimitry Andric }
1282754fe60SDimitry Andric 
129f785676fSDimitry Andric static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130f785676fSDimitry Andric                          MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131f785676fSDimitry Andric                          const ARMBaseInstrInfo &TII, int NumBytes,
132f785676fSDimitry Andric                          unsigned MIFlags = MachineInstr::NoFlags,
133f785676fSDimitry Andric                          ARMCC::CondCodes Pred = ARMCC::AL,
134f785676fSDimitry Andric                          unsigned PredReg = 0) {
135f785676fSDimitry Andric   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136f785676fSDimitry Andric                        MIFlags, Pred, PredReg);
137f785676fSDimitry Andric }
138f785676fSDimitry Andric 
13991bc56edSDimitry Andric static int sizeOfSPAdjustment(const MachineInstr *MI) {
14091bc56edSDimitry Andric   assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
14191bc56edSDimitry Andric   int count = 0;
14291bc56edSDimitry Andric   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
14391bc56edSDimitry Andric   // pred) so the list starts at 4.
14491bc56edSDimitry Andric   for (int i = MI->getNumOperands() - 1; i >= 4; --i)
14591bc56edSDimitry Andric     count += 8;
14691bc56edSDimitry Andric   return count;
14791bc56edSDimitry Andric }
14891bc56edSDimitry Andric 
14991bc56edSDimitry Andric static bool WindowsRequiresStackProbe(const MachineFunction &MF,
15091bc56edSDimitry Andric                                       size_t StackSizeInBytes) {
15191bc56edSDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
15291bc56edSDimitry Andric   if (MFI->getStackProtectorIndex() > 0)
15391bc56edSDimitry Andric     return StackSizeInBytes >= 4080;
15491bc56edSDimitry Andric   return StackSizeInBytes >= 4096;
15591bc56edSDimitry Andric }
15691bc56edSDimitry Andric 
1572754fe60SDimitry Andric void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
1582754fe60SDimitry Andric   MachineBasicBlock &MBB = MF.front();
1592754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
1602754fe60SDimitry Andric   MachineFrameInfo  *MFI = MF.getFrameInfo();
1612754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
16291bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
16391bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
16491bc56edSDimitry Andric   const TargetMachine &TM = MF.getTarget();
16591bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
1662754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
16791bc56edSDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
1682754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
16991bc56edSDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
1702754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
1712754fe60SDimitry Andric          "This emitPrologue does not support Thumb1!");
1722754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
17391bc56edSDimitry Andric   unsigned Align = TM.getFrameLowering()->getStackAlignment();
174f785676fSDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
1752754fe60SDimitry Andric   unsigned NumBytes = MFI->getStackSize();
1762754fe60SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1772754fe60SDimitry Andric   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1782754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
17991bc56edSDimitry Andric   int CFAOffset = 0;
1802754fe60SDimitry Andric 
1812754fe60SDimitry Andric   // Determine the sizes of each callee-save spill areas and record which frame
1822754fe60SDimitry Andric   // belongs to which callee-save spill areas.
1832754fe60SDimitry Andric   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1842754fe60SDimitry Andric   int FramePtrSpillFI = 0;
185dff0c46cSDimitry Andric   int D8SpillFI = 0;
186f8254f43SDimitry Andric 
1873861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
1883861d79fSDimitry Andric   // prologue/epilogue.
1897ae0e2c9SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
1907ae0e2c9SDimitry Andric     return;
1917ae0e2c9SDimitry Andric 
19291bc56edSDimitry Andric   // Allocate the vararg register save area.
19391bc56edSDimitry Andric   if (ArgRegsSaveSize) {
194284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
1953b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
19691bc56edSDimitry Andric     CFAOffset -= ArgRegsSaveSize;
19791bc56edSDimitry Andric     unsigned CFIIndex = MMI.addFrameInst(
19891bc56edSDimitry Andric         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
19991bc56edSDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
20091bc56edSDimitry Andric         .addCFIIndex(CFIIndex);
20191bc56edSDimitry Andric   }
2022754fe60SDimitry Andric 
20391bc56edSDimitry Andric   if (!AFI->hasStackFrame() &&
20491bc56edSDimitry Andric       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
20591bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0) {
20691bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
2073b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
20891bc56edSDimitry Andric       CFAOffset -= NumBytes - ArgRegsSaveSize;
20991bc56edSDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(
21091bc56edSDimitry Andric           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
21191bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
21291bc56edSDimitry Andric           .addCFIIndex(CFIIndex);
21391bc56edSDimitry Andric     }
2142754fe60SDimitry Andric     return;
2152754fe60SDimitry Andric   }
2162754fe60SDimitry Andric 
21791bc56edSDimitry Andric   // Determine spill area sizes.
2182754fe60SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2192754fe60SDimitry Andric     unsigned Reg = CSI[i].getReg();
2202754fe60SDimitry Andric     int FI = CSI[i].getFrameIdx();
2212754fe60SDimitry Andric     switch (Reg) {
22291bc56edSDimitry Andric     case ARM::R8:
22391bc56edSDimitry Andric     case ARM::R9:
22491bc56edSDimitry Andric     case ARM::R10:
22591bc56edSDimitry Andric     case ARM::R11:
22691bc56edSDimitry Andric     case ARM::R12:
22791bc56edSDimitry Andric       if (STI.isTargetDarwin()) {
22891bc56edSDimitry Andric         GPRCS2Size += 4;
22991bc56edSDimitry Andric         break;
23091bc56edSDimitry Andric       }
23191bc56edSDimitry Andric       // fallthrough
232f785676fSDimitry Andric     case ARM::R0:
233f785676fSDimitry Andric     case ARM::R1:
234f785676fSDimitry Andric     case ARM::R2:
235f785676fSDimitry Andric     case ARM::R3:
2362754fe60SDimitry Andric     case ARM::R4:
2372754fe60SDimitry Andric     case ARM::R5:
2382754fe60SDimitry Andric     case ARM::R6:
2392754fe60SDimitry Andric     case ARM::R7:
2402754fe60SDimitry Andric     case ARM::LR:
2412754fe60SDimitry Andric       if (Reg == FramePtr)
2422754fe60SDimitry Andric         FramePtrSpillFI = FI;
2432754fe60SDimitry Andric       GPRCS1Size += 4;
2442754fe60SDimitry Andric       break;
2452754fe60SDimitry Andric     default:
246dff0c46cSDimitry Andric       // This is a DPR. Exclude the aligned DPRCS2 spills.
247dff0c46cSDimitry Andric       if (Reg == ARM::D8)
248dff0c46cSDimitry Andric         D8SpillFI = FI;
249f785676fSDimitry Andric       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
2502754fe60SDimitry Andric         DPRCSSize += 8;
2512754fe60SDimitry Andric     }
2522754fe60SDimitry Andric   }
2532754fe60SDimitry Andric 
2542754fe60SDimitry Andric   // Move past area 1.
25591bc56edSDimitry Andric   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
25691bc56edSDimitry Andric       DPRCSPush;
257f785676fSDimitry Andric   if (GPRCS1Size > 0)
25891bc56edSDimitry Andric     GPRCS1Push = LastPush = MBBI++;
2592754fe60SDimitry Andric 
2602754fe60SDimitry Andric   // Determine starting offsets of spill areas.
261f785676fSDimitry Andric   bool HasFP = hasFP(MF);
26291bc56edSDimitry Andric   unsigned DPRCSOffset  = NumBytes - (ArgRegsSaveSize + GPRCS1Size
26391bc56edSDimitry Andric                                       + GPRCS2Size + DPRCSSize);
2642754fe60SDimitry Andric   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
2652754fe60SDimitry Andric   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
266f785676fSDimitry Andric   int FramePtrOffsetInPush = 0;
267f785676fSDimitry Andric   if (HasFP) {
26891bc56edSDimitry Andric     FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
26991bc56edSDimitry Andric                            + GPRCS1Size + ArgRegsSaveSize;
2702754fe60SDimitry Andric     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
2712754fe60SDimitry Andric                                 NumBytes);
272f785676fSDimitry Andric   }
2732754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
2742754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
2752754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
2762754fe60SDimitry Andric 
277f785676fSDimitry Andric   // Move past area 2.
27891bc56edSDimitry Andric   if (GPRCS2Size > 0)
27991bc56edSDimitry Andric     GPRCS2Push = LastPush = MBBI++;
280f785676fSDimitry Andric 
2812754fe60SDimitry Andric   // Move past area 3.
282dd6029ffSDimitry Andric   if (DPRCSSize > 0) {
28391bc56edSDimitry Andric     DPRCSPush = MBBI;
284dd6029ffSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
285dd6029ffSDimitry Andric     // instructions in the prologue.
286dd6029ffSDimitry Andric     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
287f785676fSDimitry Andric       LastPush = MBBI++;
288dd6029ffSDimitry Andric   }
2892754fe60SDimitry Andric 
290dff0c46cSDimitry Andric   // Move past the aligned DPRCS2 area.
291dff0c46cSDimitry Andric   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
292dff0c46cSDimitry Andric     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
293dff0c46cSDimitry Andric     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
294dff0c46cSDimitry Andric     // leaves the stack pointer pointing to the DPRCS2 area.
295dff0c46cSDimitry Andric     //
296dff0c46cSDimitry Andric     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
297dff0c46cSDimitry Andric     NumBytes += MFI->getObjectOffset(D8SpillFI);
298dff0c46cSDimitry Andric   } else
2992754fe60SDimitry Andric     NumBytes = DPRCSOffset;
300dff0c46cSDimitry Andric 
30191bc56edSDimitry Andric   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
30291bc56edSDimitry Andric     uint32_t NumWords = NumBytes >> 2;
30391bc56edSDimitry Andric 
30491bc56edSDimitry Andric     if (NumWords < 65536)
30591bc56edSDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
30691bc56edSDimitry Andric                      .addImm(NumWords)
30791bc56edSDimitry Andric                      .setMIFlags(MachineInstr::FrameSetup));
30891bc56edSDimitry Andric     else
30991bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
31091bc56edSDimitry Andric         .addImm(NumWords)
31191bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
31291bc56edSDimitry Andric 
31391bc56edSDimitry Andric     switch (TM.getCodeModel()) {
31491bc56edSDimitry Andric     case CodeModel::Small:
31591bc56edSDimitry Andric     case CodeModel::Medium:
31691bc56edSDimitry Andric     case CodeModel::Default:
31791bc56edSDimitry Andric     case CodeModel::Kernel:
31891bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
31991bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
32091bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
32191bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
32291bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
32391bc56edSDimitry Andric       break;
32491bc56edSDimitry Andric     case CodeModel::Large:
32591bc56edSDimitry Andric     case CodeModel::JITDefault:
32691bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
32791bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
32891bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
32991bc56edSDimitry Andric 
33091bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
33191bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
33291bc56edSDimitry Andric         .addReg(ARM::R12, RegState::Kill)
33391bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
33491bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
33591bc56edSDimitry Andric       break;
33691bc56edSDimitry Andric     }
33791bc56edSDimitry Andric 
33891bc56edSDimitry Andric     AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
33991bc56edSDimitry Andric                                         ARM::SP)
34091bc56edSDimitry Andric                                 .addReg(ARM::SP, RegState::Define)
34191bc56edSDimitry Andric                                 .addReg(ARM::R4, RegState::Kill)
34291bc56edSDimitry Andric                                 .setMIFlags(MachineInstr::FrameSetup)));
34391bc56edSDimitry Andric     NumBytes = 0;
34491bc56edSDimitry Andric   }
34591bc56edSDimitry Andric 
34691bc56edSDimitry Andric   unsigned adjustedGPRCS1Size = GPRCS1Size;
3472754fe60SDimitry Andric   if (NumBytes) {
3482754fe60SDimitry Andric     // Adjust SP after all the callee-save spills.
34991bc56edSDimitry Andric     if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
35091bc56edSDimitry Andric       if (LastPush == GPRCS1Push) {
351f785676fSDimitry Andric         FramePtrOffsetInPush += NumBytes;
35291bc56edSDimitry Andric         adjustedGPRCS1Size += NumBytes;
35391bc56edSDimitry Andric         NumBytes = 0;
35491bc56edSDimitry Andric       }
355f785676fSDimitry Andric     } else
3563b0f4066SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
3573b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
358f785676fSDimitry Andric 
3592754fe60SDimitry Andric     if (HasFP && isARM)
3602754fe60SDimitry Andric       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
3612754fe60SDimitry Andric       // Note it's not safe to do this in Thumb2 mode because it would have
3622754fe60SDimitry Andric       // taken two instructions:
3632754fe60SDimitry Andric       // mov sp, r7
3642754fe60SDimitry Andric       // sub sp, #24
3652754fe60SDimitry Andric       // If an interrupt is taken between the two instructions, then sp is in
3662754fe60SDimitry Andric       // an inconsistent state (pointing to the middle of callee-saved area).
3672754fe60SDimitry Andric       // The interrupt handler can end up clobbering the registers.
3682754fe60SDimitry Andric       AFI->setShouldRestoreSPFromFP(true);
3692754fe60SDimitry Andric   }
3702754fe60SDimitry Andric 
37191bc56edSDimitry Andric   if (adjustedGPRCS1Size > 0) {
37291bc56edSDimitry Andric     CFAOffset -= adjustedGPRCS1Size;
37391bc56edSDimitry Andric     unsigned CFIIndex = MMI.addFrameInst(
37491bc56edSDimitry Andric         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
37591bc56edSDimitry Andric     MachineBasicBlock::iterator Pos = ++GPRCS1Push;
37691bc56edSDimitry Andric     BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
37791bc56edSDimitry Andric         .addCFIIndex(CFIIndex);
37891bc56edSDimitry Andric     for (const auto &Entry : CSI) {
37991bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
38091bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
38191bc56edSDimitry Andric       switch (Reg) {
38291bc56edSDimitry Andric       case ARM::R8:
38391bc56edSDimitry Andric       case ARM::R9:
38491bc56edSDimitry Andric       case ARM::R10:
38591bc56edSDimitry Andric       case ARM::R11:
38691bc56edSDimitry Andric       case ARM::R12:
38791bc56edSDimitry Andric         if (STI.isTargetDarwin())
38891bc56edSDimitry Andric           break;
38991bc56edSDimitry Andric         // fallthrough
39091bc56edSDimitry Andric       case ARM::R0:
39191bc56edSDimitry Andric       case ARM::R1:
39291bc56edSDimitry Andric       case ARM::R2:
39391bc56edSDimitry Andric       case ARM::R3:
39491bc56edSDimitry Andric       case ARM::R4:
39591bc56edSDimitry Andric       case ARM::R5:
39691bc56edSDimitry Andric       case ARM::R6:
39791bc56edSDimitry Andric       case ARM::R7:
39891bc56edSDimitry Andric       case ARM::LR:
39991bc56edSDimitry Andric         CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
40091bc56edSDimitry Andric             nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
40191bc56edSDimitry Andric         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
40291bc56edSDimitry Andric             .addCFIIndex(CFIIndex);
40391bc56edSDimitry Andric         break;
40491bc56edSDimitry Andric       }
40591bc56edSDimitry Andric     }
40691bc56edSDimitry Andric   }
40791bc56edSDimitry Andric 
408f785676fSDimitry Andric   // Set FP to point to the stack slot that contains the previous FP.
409f785676fSDimitry Andric   // For iOS, FP is R7, which has now been stored in spill area 1.
410f785676fSDimitry Andric   // Otherwise, if this is not iOS, all the callee-saved registers go
411f785676fSDimitry Andric   // into spill area 1, including the FP in R11.  In either case, it
412f785676fSDimitry Andric   // is in area one and the adjustment needs to take place just after
413f785676fSDimitry Andric   // that push.
41491bc56edSDimitry Andric   if (HasFP) {
41591bc56edSDimitry Andric     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
416f785676fSDimitry Andric                          FramePtr, ARM::SP, FramePtrOffsetInPush,
417f785676fSDimitry Andric                          MachineInstr::FrameSetup);
41891bc56edSDimitry Andric     if (FramePtrOffsetInPush) {
41991bc56edSDimitry Andric       CFAOffset += FramePtrOffsetInPush;
42091bc56edSDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
42191bc56edSDimitry Andric           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
42291bc56edSDimitry Andric       BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
42391bc56edSDimitry Andric           .addCFIIndex(CFIIndex);
424f785676fSDimitry Andric 
42591bc56edSDimitry Andric     } else {
42691bc56edSDimitry Andric       unsigned CFIIndex =
42791bc56edSDimitry Andric           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
42891bc56edSDimitry Andric               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
42991bc56edSDimitry Andric       BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
43091bc56edSDimitry Andric           .addCFIIndex(CFIIndex);
43191bc56edSDimitry Andric     }
43291bc56edSDimitry Andric   }
43391bc56edSDimitry Andric 
43491bc56edSDimitry Andric   if (GPRCS2Size > 0) {
43591bc56edSDimitry Andric     MachineBasicBlock::iterator Pos = ++GPRCS2Push;
43691bc56edSDimitry Andric     if (!HasFP) {
43791bc56edSDimitry Andric       CFAOffset -= GPRCS2Size;
43891bc56edSDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(
43991bc56edSDimitry Andric           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
44091bc56edSDimitry Andric       BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
44191bc56edSDimitry Andric           .addCFIIndex(CFIIndex);
44291bc56edSDimitry Andric     }
44391bc56edSDimitry Andric     for (const auto &Entry : CSI) {
44491bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
44591bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
44691bc56edSDimitry Andric       switch (Reg) {
44791bc56edSDimitry Andric       case ARM::R8:
44891bc56edSDimitry Andric       case ARM::R9:
44991bc56edSDimitry Andric       case ARM::R10:
45091bc56edSDimitry Andric       case ARM::R11:
45191bc56edSDimitry Andric       case ARM::R12:
45291bc56edSDimitry Andric         if (STI.isTargetDarwin()) {
45391bc56edSDimitry Andric           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
45491bc56edSDimitry Andric           unsigned Offset = MFI->getObjectOffset(FI);
45591bc56edSDimitry Andric           unsigned CFIIndex = MMI.addFrameInst(
45691bc56edSDimitry Andric               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
45791bc56edSDimitry Andric           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
45891bc56edSDimitry Andric               .addCFIIndex(CFIIndex);
45991bc56edSDimitry Andric         }
46091bc56edSDimitry Andric         break;
46191bc56edSDimitry Andric       }
46291bc56edSDimitry Andric     }
46391bc56edSDimitry Andric   }
46491bc56edSDimitry Andric 
46591bc56edSDimitry Andric   if (DPRCSSize > 0) {
46691bc56edSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
46791bc56edSDimitry Andric     // instructions in the prologue.
46891bc56edSDimitry Andric     do {
46991bc56edSDimitry Andric       MachineBasicBlock::iterator Push = DPRCSPush++;
47091bc56edSDimitry Andric       if (!HasFP) {
47191bc56edSDimitry Andric         CFAOffset -= sizeOfSPAdjustment(Push);
47291bc56edSDimitry Andric         unsigned CFIIndex = MMI.addFrameInst(
47391bc56edSDimitry Andric             MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
47491bc56edSDimitry Andric         BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
47591bc56edSDimitry Andric             .addCFIIndex(CFIIndex);
47691bc56edSDimitry Andric       }
47791bc56edSDimitry Andric     } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
47891bc56edSDimitry Andric 
47991bc56edSDimitry Andric     for (const auto &Entry : CSI) {
48091bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
48191bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
48291bc56edSDimitry Andric       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
48391bc56edSDimitry Andric           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
48491bc56edSDimitry Andric         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
48591bc56edSDimitry Andric         unsigned Offset = MFI->getObjectOffset(FI);
48691bc56edSDimitry Andric         unsigned CFIIndex = MMI.addFrameInst(
48791bc56edSDimitry Andric             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
48891bc56edSDimitry Andric         BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
48991bc56edSDimitry Andric             .addCFIIndex(CFIIndex);
49091bc56edSDimitry Andric       }
49191bc56edSDimitry Andric     }
49291bc56edSDimitry Andric   }
49391bc56edSDimitry Andric 
49491bc56edSDimitry Andric   if (NumBytes) {
49591bc56edSDimitry Andric     if (!HasFP) {
49691bc56edSDimitry Andric       CFAOffset -= NumBytes;
49791bc56edSDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(
49891bc56edSDimitry Andric           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
49991bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
50091bc56edSDimitry Andric           .addCFIIndex(CFIIndex);
50191bc56edSDimitry Andric     }
50291bc56edSDimitry Andric   }
503f785676fSDimitry Andric 
5042754fe60SDimitry Andric   if (STI.isTargetELF() && hasFP(MF))
5052754fe60SDimitry Andric     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
5062754fe60SDimitry Andric                              AFI->getFramePtrSpillOffset());
5072754fe60SDimitry Andric 
5082754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
5092754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
5102754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
5112754fe60SDimitry Andric 
5122754fe60SDimitry Andric   // If we need dynamic stack realignment, do it here. Be paranoid and make
5132754fe60SDimitry Andric   // sure if we also have VLAs, we have a base pointer for frame access.
514dff0c46cSDimitry Andric   // If aligned NEON registers were spilled, the stack has already been
515dff0c46cSDimitry Andric   // realigned.
516dff0c46cSDimitry Andric   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
5172754fe60SDimitry Andric     unsigned MaxAlign = MFI->getMaxAlignment();
5182754fe60SDimitry Andric     assert (!AFI->isThumb1OnlyFunction());
5192754fe60SDimitry Andric     if (!AFI->isThumbFunction()) {
5202754fe60SDimitry Andric       // Emit bic sp, sp, MaxAlign
5212754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
5222754fe60SDimitry Andric                                           TII.get(ARM::BICri), ARM::SP)
5232754fe60SDimitry Andric                                   .addReg(ARM::SP, RegState::Kill)
5242754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
5252754fe60SDimitry Andric     } else {
5262754fe60SDimitry Andric       // We cannot use sp as source/dest register here, thus we're emitting the
5272754fe60SDimitry Andric       // following sequence:
5282754fe60SDimitry Andric       // mov r4, sp
5292754fe60SDimitry Andric       // bic r4, r4, MaxAlign
5302754fe60SDimitry Andric       // mov sp, r4
5312754fe60SDimitry Andric       // FIXME: It will be better just to find spare register here.
53217a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
53317a519f9SDimitry Andric         .addReg(ARM::SP, RegState::Kill));
5342754fe60SDimitry Andric       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
5352754fe60SDimitry Andric                                           TII.get(ARM::t2BICri), ARM::R4)
5362754fe60SDimitry Andric                                   .addReg(ARM::R4, RegState::Kill)
5372754fe60SDimitry Andric                                   .addImm(MaxAlign-1)));
53817a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
53917a519f9SDimitry Andric         .addReg(ARM::R4, RegState::Kill));
5402754fe60SDimitry Andric     }
5412754fe60SDimitry Andric 
5422754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
5432754fe60SDimitry Andric   }
5442754fe60SDimitry Andric 
5452754fe60SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
5462754fe60SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
5472754fe60SDimitry Andric   // will be allocated after this, so we can still use the base pointer
5482754fe60SDimitry Andric   // to reference locals.
5493b0f4066SDimitry Andric   // FIXME: Clarify FrameSetup flags here.
5502754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
5512754fe60SDimitry Andric     if (isARM)
5522754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl,
5532754fe60SDimitry Andric               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
5542754fe60SDimitry Andric         .addReg(ARM::SP)
5552754fe60SDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
5562754fe60SDimitry Andric     else
55717a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
55817a519f9SDimitry Andric                              RegInfo->getBaseRegister())
55917a519f9SDimitry Andric         .addReg(ARM::SP));
5602754fe60SDimitry Andric   }
5612754fe60SDimitry Andric 
5622754fe60SDimitry Andric   // If the frame has variable sized objects then the epilogue must restore
5632754fe60SDimitry Andric   // the sp from fp. We can assume there's an FP here since hasFP already
5642754fe60SDimitry Andric   // checks for hasVarSizedObjects.
5652754fe60SDimitry Andric   if (MFI->hasVarSizedObjects())
5662754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
5672754fe60SDimitry Andric }
5682754fe60SDimitry Andric 
5699cac79b3SDimitry Andric // Resolve TCReturn pseudo-instruction
5709cac79b3SDimitry Andric void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
5712754fe60SDimitry Andric                                    MachineBasicBlock &MBB) const {
5722754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
573dff0c46cSDimitry Andric   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
5742754fe60SDimitry Andric   unsigned RetOpcode = MBBI->getOpcode();
5752754fe60SDimitry Andric   DebugLoc dl = MBBI->getDebugLoc();
5769cac79b3SDimitry Andric   const ARMBaseInstrInfo &TII =
5779cac79b3SDimitry Andric       *MF.getTarget().getSubtarget<ARMSubtarget>().getInstrInfo();
5789cac79b3SDimitry Andric 
5799cac79b3SDimitry Andric   if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
5809cac79b3SDimitry Andric     return;
5819cac79b3SDimitry Andric 
5829cac79b3SDimitry Andric   // Tail call return: adjust the stack pointer and jump to callee.
5839cac79b3SDimitry Andric   MBBI = MBB.getLastNonDebugInstr();
5849cac79b3SDimitry Andric   MachineOperand &JumpTarget = MBBI->getOperand(0);
5859cac79b3SDimitry Andric 
5869cac79b3SDimitry Andric   // Jump to label or value in register.
5879cac79b3SDimitry Andric   if (RetOpcode == ARM::TCRETURNdi) {
5889cac79b3SDimitry Andric     unsigned TCOpcode = STI.isThumb() ?
5899cac79b3SDimitry Andric              (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
5909cac79b3SDimitry Andric              ARM::TAILJMPd;
5919cac79b3SDimitry Andric     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
5929cac79b3SDimitry Andric     if (JumpTarget.isGlobal())
5939cac79b3SDimitry Andric       MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
5949cac79b3SDimitry Andric                            JumpTarget.getTargetFlags());
5959cac79b3SDimitry Andric     else {
5969cac79b3SDimitry Andric       assert(JumpTarget.isSymbol());
5979cac79b3SDimitry Andric       MIB.addExternalSymbol(JumpTarget.getSymbolName(),
5989cac79b3SDimitry Andric                             JumpTarget.getTargetFlags());
5999cac79b3SDimitry Andric     }
6009cac79b3SDimitry Andric 
6019cac79b3SDimitry Andric     // Add the default predicate in Thumb mode.
6029cac79b3SDimitry Andric     if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
6039cac79b3SDimitry Andric   } else if (RetOpcode == ARM::TCRETURNri) {
6049cac79b3SDimitry Andric     BuildMI(MBB, MBBI, dl,
6059cac79b3SDimitry Andric             TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
6069cac79b3SDimitry Andric       addReg(JumpTarget.getReg(), RegState::Kill);
6079cac79b3SDimitry Andric   }
6089cac79b3SDimitry Andric 
6099cac79b3SDimitry Andric   MachineInstr *NewMI = std::prev(MBBI);
6109cac79b3SDimitry Andric   for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
6119cac79b3SDimitry Andric     NewMI->addOperand(MBBI->getOperand(i));
6129cac79b3SDimitry Andric 
6139cac79b3SDimitry Andric   // Delete the pseudo instruction TCRETURN.
6149cac79b3SDimitry Andric   MBB.erase(MBBI);
6159cac79b3SDimitry Andric   MBBI = NewMI;
6169cac79b3SDimitry Andric }
6179cac79b3SDimitry Andric 
6189cac79b3SDimitry Andric void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
6199cac79b3SDimitry Andric                                     MachineBasicBlock &MBB) const {
6209cac79b3SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
6219cac79b3SDimitry Andric   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
6229cac79b3SDimitry Andric   DebugLoc dl = MBBI->getDebugLoc();
6232754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
6242754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
6252754fe60SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
6262754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
6272754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
6282754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
6292754fe60SDimitry Andric          "This emitEpilogue does not support Thumb1!");
6302754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
6312754fe60SDimitry Andric 
632f785676fSDimitry Andric   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
633f785676fSDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
6342754fe60SDimitry Andric   int NumBytes = (int)MFI->getStackSize();
6352754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
6362754fe60SDimitry Andric 
6373861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
6383861d79fSDimitry Andric   // prologue/epilogue.
6399cac79b3SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
6409cac79b3SDimitry Andric     fixTCReturn(MF, MBB);
6417ae0e2c9SDimitry Andric     return;
6429cac79b3SDimitry Andric   }
6437ae0e2c9SDimitry Andric 
6442754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
64591bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0)
64691bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
6472754fe60SDimitry Andric   } else {
6482754fe60SDimitry Andric     // Unwind MBBI to point to first LDR / VLDRD.
64991bc56edSDimitry Andric     const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
6502754fe60SDimitry Andric     if (MBBI != MBB.begin()) {
651f785676fSDimitry Andric       do {
6522754fe60SDimitry Andric         --MBBI;
653f785676fSDimitry Andric       } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
6542754fe60SDimitry Andric       if (!isCSRestore(MBBI, TII, CSRegs))
6552754fe60SDimitry Andric         ++MBBI;
6562754fe60SDimitry Andric     }
6572754fe60SDimitry Andric 
6582754fe60SDimitry Andric     // Move SP to start of FP callee save spill area.
65991bc56edSDimitry Andric     NumBytes -= (ArgRegsSaveSize +
66091bc56edSDimitry Andric                  AFI->getGPRCalleeSavedArea1Size() +
6612754fe60SDimitry Andric                  AFI->getGPRCalleeSavedArea2Size() +
6622754fe60SDimitry Andric                  AFI->getDPRCalleeSavedAreaSize());
6632754fe60SDimitry Andric 
6642754fe60SDimitry Andric     // Reset SP based on frame pointer only if the stack frame extends beyond
6652754fe60SDimitry Andric     // frame pointer stack slot or target is ELF and the function has FP.
6662754fe60SDimitry Andric     if (AFI->shouldRestoreSPFromFP()) {
6672754fe60SDimitry Andric       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
6682754fe60SDimitry Andric       if (NumBytes) {
6692754fe60SDimitry Andric         if (isARM)
6702754fe60SDimitry Andric           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
6712754fe60SDimitry Andric                                   ARMCC::AL, 0, TII);
6722754fe60SDimitry Andric         else {
6732754fe60SDimitry Andric           // It's not possible to restore SP from FP in a single instruction.
674dff0c46cSDimitry Andric           // For iOS, this looks like:
6752754fe60SDimitry Andric           // mov sp, r7
6762754fe60SDimitry Andric           // sub sp, #24
6772754fe60SDimitry Andric           // This is bad, if an interrupt is taken after the mov, sp is in an
6782754fe60SDimitry Andric           // inconsistent state.
6792754fe60SDimitry Andric           // Use the first callee-saved register as a scratch register.
6802754fe60SDimitry Andric           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
6812754fe60SDimitry Andric                  "No scratch register to restore SP from FP!");
6822754fe60SDimitry Andric           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
6832754fe60SDimitry Andric                                  ARMCC::AL, 0, TII);
68417a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
68517a519f9SDimitry Andric                                  ARM::SP)
68617a519f9SDimitry Andric             .addReg(ARM::R4));
6872754fe60SDimitry Andric         }
6882754fe60SDimitry Andric       } else {
6892754fe60SDimitry Andric         // Thumb2 or ARM.
6902754fe60SDimitry Andric         if (isARM)
6912754fe60SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
6922754fe60SDimitry Andric             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6932754fe60SDimitry Andric         else
69417a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
69517a519f9SDimitry Andric                                  ARM::SP)
69617a519f9SDimitry Andric             .addReg(FramePtr));
6972754fe60SDimitry Andric       }
69891bc56edSDimitry Andric     } else if (NumBytes &&
69991bc56edSDimitry Andric                !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
7002754fe60SDimitry Andric         emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
7012754fe60SDimitry Andric 
7022754fe60SDimitry Andric     // Increment past our save areas.
703dd6029ffSDimitry Andric     if (AFI->getDPRCalleeSavedAreaSize()) {
704dd6029ffSDimitry Andric       MBBI++;
705dd6029ffSDimitry Andric       // Since vpop register list cannot have gaps, there may be multiple vpop
706dd6029ffSDimitry Andric       // instructions in the epilogue.
707dd6029ffSDimitry Andric       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
708dd6029ffSDimitry Andric         MBBI++;
709dd6029ffSDimitry Andric     }
7102754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
7112754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
7122754fe60SDimitry Andric   }
7132754fe60SDimitry Andric 
7149cac79b3SDimitry Andric   fixTCReturn(MF, MBB);
7152754fe60SDimitry Andric 
716284c1978SDimitry Andric   if (ArgRegsSaveSize)
717284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
7182754fe60SDimitry Andric }
7192754fe60SDimitry Andric 
7202754fe60SDimitry Andric /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
7212754fe60SDimitry Andric /// debug info.  It's the same as what we use for resolving the code-gen
7222754fe60SDimitry Andric /// references for now.  FIXME: This can go wrong when references are
7232754fe60SDimitry Andric /// SP-relative and simple call frames aren't used.
7242754fe60SDimitry Andric int
7252754fe60SDimitry Andric ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
7262754fe60SDimitry Andric                                          unsigned &FrameReg) const {
7272754fe60SDimitry Andric   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
7282754fe60SDimitry Andric }
7292754fe60SDimitry Andric 
7302754fe60SDimitry Andric int
7312754fe60SDimitry Andric ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
7323b0f4066SDimitry Andric                                              int FI, unsigned &FrameReg,
7332754fe60SDimitry Andric                                              int SPAdj) const {
7342754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
7352754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
7362754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
7372754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
7382754fe60SDimitry Andric   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
7392754fe60SDimitry Andric   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
7402754fe60SDimitry Andric   bool isFixed = MFI->isFixedObjectIndex(FI);
7412754fe60SDimitry Andric 
7422754fe60SDimitry Andric   FrameReg = ARM::SP;
7432754fe60SDimitry Andric   Offset += SPAdj;
7442754fe60SDimitry Andric 
745dff0c46cSDimitry Andric   // SP can move around if there are allocas.  We may also lose track of SP
746dff0c46cSDimitry Andric   // when emergency spilling inside a non-reserved call frame setup.
747dff0c46cSDimitry Andric   bool hasMovingSP = !hasReservedCallFrame(MF);
748dff0c46cSDimitry Andric 
7492754fe60SDimitry Andric   // When dynamically realigning the stack, use the frame pointer for
7502754fe60SDimitry Andric   // parameters, and the stack/base pointer for locals.
7512754fe60SDimitry Andric   if (RegInfo->needsStackRealignment(MF)) {
7522754fe60SDimitry Andric     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
7532754fe60SDimitry Andric     if (isFixed) {
7542754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
7552754fe60SDimitry Andric       Offset = FPOffset;
756dff0c46cSDimitry Andric     } else if (hasMovingSP) {
7572754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) &&
7582754fe60SDimitry Andric              "VLAs and dynamic stack alignment, but missing base pointer!");
7592754fe60SDimitry Andric       FrameReg = RegInfo->getBaseRegister();
7602754fe60SDimitry Andric     }
7612754fe60SDimitry Andric     return Offset;
7622754fe60SDimitry Andric   }
7632754fe60SDimitry Andric 
7642754fe60SDimitry Andric   // If there is a frame pointer, use it when we can.
7652754fe60SDimitry Andric   if (hasFP(MF) && AFI->hasStackFrame()) {
7662754fe60SDimitry Andric     // Use frame pointer to reference fixed objects. Use it for locals if
7672754fe60SDimitry Andric     // there are VLAs (and thus the SP isn't reliable as a base).
768dff0c46cSDimitry Andric     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
7692754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
7702754fe60SDimitry Andric       return FPOffset;
771dff0c46cSDimitry Andric     } else if (hasMovingSP) {
7722754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
7733b0f4066SDimitry Andric       if (AFI->isThumb2Function()) {
7742754fe60SDimitry Andric         // Try to use the frame pointer if we can, else use the base pointer
7752754fe60SDimitry Andric         // since it's available. This is handy for the emergency spill slot, in
7762754fe60SDimitry Andric         // particular.
7772754fe60SDimitry Andric         if (FPOffset >= -255 && FPOffset < 0) {
7782754fe60SDimitry Andric           FrameReg = RegInfo->getFrameRegister(MF);
7792754fe60SDimitry Andric           return FPOffset;
7802754fe60SDimitry Andric         }
7813b0f4066SDimitry Andric       }
7822754fe60SDimitry Andric     } else if (AFI->isThumb2Function()) {
7833b0f4066SDimitry Andric       // Use  add <rd>, sp, #<imm8>
7843b0f4066SDimitry Andric       //      ldr <rd>, [sp, #<imm8>]
7853b0f4066SDimitry Andric       // if at all possible to save space.
7863b0f4066SDimitry Andric       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
7873b0f4066SDimitry Andric         return Offset;
7882754fe60SDimitry Andric       // In Thumb2 mode, the negative offset is very limited. Try to avoid
7893b0f4066SDimitry Andric       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
7902754fe60SDimitry Andric       if (FPOffset >= -255 && FPOffset < 0) {
7912754fe60SDimitry Andric         FrameReg = RegInfo->getFrameRegister(MF);
7922754fe60SDimitry Andric         return FPOffset;
7932754fe60SDimitry Andric       }
7942754fe60SDimitry Andric     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
7952754fe60SDimitry Andric       // Otherwise, use SP or FP, whichever is closer to the stack slot.
7962754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
7972754fe60SDimitry Andric       return FPOffset;
7982754fe60SDimitry Andric     }
7992754fe60SDimitry Andric   }
8002754fe60SDimitry Andric   // Use the base pointer if we have one.
8012754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
8022754fe60SDimitry Andric     FrameReg = RegInfo->getBaseRegister();
8032754fe60SDimitry Andric   return Offset;
8042754fe60SDimitry Andric }
8052754fe60SDimitry Andric 
8062754fe60SDimitry Andric int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
8072754fe60SDimitry Andric                                           int FI) const {
8082754fe60SDimitry Andric   unsigned FrameReg;
8092754fe60SDimitry Andric   return getFrameIndexReference(MF, FI, FrameReg);
8102754fe60SDimitry Andric }
8112754fe60SDimitry Andric 
8122754fe60SDimitry Andric void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
8132754fe60SDimitry Andric                                     MachineBasicBlock::iterator MI,
8142754fe60SDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
8152754fe60SDimitry Andric                                     unsigned StmOpc, unsigned StrOpc,
8162754fe60SDimitry Andric                                     bool NoGap,
8173b0f4066SDimitry Andric                                     bool(*Func)(unsigned, bool),
818dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
8193b0f4066SDimitry Andric                                     unsigned MIFlags) const {
8202754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
8212754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
8222754fe60SDimitry Andric 
8232754fe60SDimitry Andric   DebugLoc DL;
8242754fe60SDimitry Andric   if (MI != MBB.end()) DL = MI->getDebugLoc();
8252754fe60SDimitry Andric 
8262754fe60SDimitry Andric   SmallVector<std::pair<unsigned,bool>, 4> Regs;
8272754fe60SDimitry Andric   unsigned i = CSI.size();
8282754fe60SDimitry Andric   while (i != 0) {
8292754fe60SDimitry Andric     unsigned LastReg = 0;
8302754fe60SDimitry Andric     for (; i != 0; --i) {
8312754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
83291bc56edSDimitry Andric       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
833dff0c46cSDimitry Andric 
834dff0c46cSDimitry Andric       // D-registers in the aligned area DPRCS2 are NOT spilled here.
835dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
836dff0c46cSDimitry Andric         continue;
8372754fe60SDimitry Andric 
8382754fe60SDimitry Andric       // Add the callee-saved register as live-in unless it's LR and
8392754fe60SDimitry Andric       // @llvm.returnaddress is called. If LR is returned for
8402754fe60SDimitry Andric       // @llvm.returnaddress then it's already added to the function and
8412754fe60SDimitry Andric       // entry block live-in sets.
8422754fe60SDimitry Andric       bool isKill = true;
8432754fe60SDimitry Andric       if (Reg == ARM::LR) {
8442754fe60SDimitry Andric         if (MF.getFrameInfo()->isReturnAddressTaken() &&
8452754fe60SDimitry Andric             MF.getRegInfo().isLiveIn(Reg))
8462754fe60SDimitry Andric           isKill = false;
8472754fe60SDimitry Andric       }
8482754fe60SDimitry Andric 
8492754fe60SDimitry Andric       if (isKill)
8502754fe60SDimitry Andric         MBB.addLiveIn(Reg);
8512754fe60SDimitry Andric 
8522754fe60SDimitry Andric       // If NoGap is true, push consecutive registers and then leave the rest
8532754fe60SDimitry Andric       // for other instructions. e.g.
8542754fe60SDimitry Andric       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
8552754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
8562754fe60SDimitry Andric         break;
8572754fe60SDimitry Andric       LastReg = Reg;
8582754fe60SDimitry Andric       Regs.push_back(std::make_pair(Reg, isKill));
8592754fe60SDimitry Andric     }
8602754fe60SDimitry Andric 
8612754fe60SDimitry Andric     if (Regs.empty())
8622754fe60SDimitry Andric       continue;
8632754fe60SDimitry Andric     if (Regs.size() > 1 || StrOpc== 0) {
8642754fe60SDimitry Andric       MachineInstrBuilder MIB =
8652754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
8663b0f4066SDimitry Andric                        .addReg(ARM::SP).setMIFlags(MIFlags));
8672754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
8682754fe60SDimitry Andric         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
8692754fe60SDimitry Andric     } else if (Regs.size() == 1) {
8702754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
8712754fe60SDimitry Andric                                         ARM::SP)
8722754fe60SDimitry Andric         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
8736122f3e6SDimitry Andric         .addReg(ARM::SP).setMIFlags(MIFlags)
8746122f3e6SDimitry Andric         .addImm(-4);
8752754fe60SDimitry Andric       AddDefaultPred(MIB);
8762754fe60SDimitry Andric     }
8772754fe60SDimitry Andric     Regs.clear();
87891bc56edSDimitry Andric 
87991bc56edSDimitry Andric     // Put any subsequent vpush instructions before this one: they will refer to
88091bc56edSDimitry Andric     // higher register numbers so need to be pushed first in order to preserve
88191bc56edSDimitry Andric     // monotonicity.
88291bc56edSDimitry Andric     --MI;
8832754fe60SDimitry Andric   }
8842754fe60SDimitry Andric }
8852754fe60SDimitry Andric 
8862754fe60SDimitry Andric void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
8872754fe60SDimitry Andric                                    MachineBasicBlock::iterator MI,
8882754fe60SDimitry Andric                                    const std::vector<CalleeSavedInfo> &CSI,
8892754fe60SDimitry Andric                                    unsigned LdmOpc, unsigned LdrOpc,
8902754fe60SDimitry Andric                                    bool isVarArg, bool NoGap,
891dff0c46cSDimitry Andric                                    bool(*Func)(unsigned, bool),
892dff0c46cSDimitry Andric                                    unsigned NumAlignedDPRCS2Regs) const {
8932754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
8942754fe60SDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
8952754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
8962754fe60SDimitry Andric   DebugLoc DL = MI->getDebugLoc();
8972754fe60SDimitry Andric   unsigned RetOpcode = MI->getOpcode();
8982754fe60SDimitry Andric   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
899dff0c46cSDimitry Andric                      RetOpcode == ARM::TCRETURNri);
900f785676fSDimitry Andric   bool isInterrupt =
901f785676fSDimitry Andric       RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
9022754fe60SDimitry Andric 
9032754fe60SDimitry Andric   SmallVector<unsigned, 4> Regs;
9042754fe60SDimitry Andric   unsigned i = CSI.size();
9052754fe60SDimitry Andric   while (i != 0) {
9062754fe60SDimitry Andric     unsigned LastReg = 0;
9072754fe60SDimitry Andric     bool DeleteRet = false;
9082754fe60SDimitry Andric     for (; i != 0; --i) {
9092754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
91091bc56edSDimitry Andric       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
911dff0c46cSDimitry Andric 
912dff0c46cSDimitry Andric       // The aligned reloads from area DPRCS2 are not inserted here.
913dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
914dff0c46cSDimitry Andric         continue;
9152754fe60SDimitry Andric 
916f785676fSDimitry Andric       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
917f785676fSDimitry Andric           STI.hasV5TOps()) {
9182754fe60SDimitry Andric         Reg = ARM::PC;
9192754fe60SDimitry Andric         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
9202754fe60SDimitry Andric         // Fold the return instruction into the LDM.
9212754fe60SDimitry Andric         DeleteRet = true;
9222754fe60SDimitry Andric       }
9232754fe60SDimitry Andric 
9242754fe60SDimitry Andric       // If NoGap is true, pop consecutive registers and then leave the rest
9252754fe60SDimitry Andric       // for other instructions. e.g.
9262754fe60SDimitry Andric       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
9272754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
9282754fe60SDimitry Andric         break;
9292754fe60SDimitry Andric 
9302754fe60SDimitry Andric       LastReg = Reg;
9312754fe60SDimitry Andric       Regs.push_back(Reg);
9322754fe60SDimitry Andric     }
9332754fe60SDimitry Andric 
9342754fe60SDimitry Andric     if (Regs.empty())
9352754fe60SDimitry Andric       continue;
9362754fe60SDimitry Andric     if (Regs.size() > 1 || LdrOpc == 0) {
9372754fe60SDimitry Andric       MachineInstrBuilder MIB =
9382754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
9392754fe60SDimitry Andric                        .addReg(ARM::SP));
9402754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
9412754fe60SDimitry Andric         MIB.addReg(Regs[i], getDefRegState(true));
9426122f3e6SDimitry Andric       if (DeleteRet) {
943139f7f9bSDimitry Andric         MIB.copyImplicitOps(&*MI);
9442754fe60SDimitry Andric         MI->eraseFromParent();
9456122f3e6SDimitry Andric       }
9462754fe60SDimitry Andric       MI = MIB;
9472754fe60SDimitry Andric     } else if (Regs.size() == 1) {
9482754fe60SDimitry Andric       // If we adjusted the reg to PC from LR above, switch it back here. We
9492754fe60SDimitry Andric       // only do that for LDM.
9502754fe60SDimitry Andric       if (Regs[0] == ARM::PC)
9512754fe60SDimitry Andric         Regs[0] = ARM::LR;
9522754fe60SDimitry Andric       MachineInstrBuilder MIB =
9532754fe60SDimitry Andric         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
9542754fe60SDimitry Andric           .addReg(ARM::SP, RegState::Define)
9552754fe60SDimitry Andric           .addReg(ARM::SP);
9562754fe60SDimitry Andric       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
9572754fe60SDimitry Andric       // that refactoring is complete (eventually).
9586122f3e6SDimitry Andric       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
9592754fe60SDimitry Andric         MIB.addReg(0);
9602754fe60SDimitry Andric         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
9612754fe60SDimitry Andric       } else
9622754fe60SDimitry Andric         MIB.addImm(4);
9632754fe60SDimitry Andric       AddDefaultPred(MIB);
9642754fe60SDimitry Andric     }
9652754fe60SDimitry Andric     Regs.clear();
96691bc56edSDimitry Andric 
96791bc56edSDimitry Andric     // Put any subsequent vpop instructions after this one: they will refer to
96891bc56edSDimitry Andric     // higher register numbers so need to be popped afterwards.
96991bc56edSDimitry Andric     ++MI;
9702754fe60SDimitry Andric   }
9712754fe60SDimitry Andric }
9722754fe60SDimitry Andric 
973dff0c46cSDimitry Andric /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
974dff0c46cSDimitry Andric /// starting from d8.  Also insert stack realignment code and leave the stack
975dff0c46cSDimitry Andric /// pointer pointing to the d8 spill slot.
976dff0c46cSDimitry Andric static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
977dff0c46cSDimitry Andric                                     MachineBasicBlock::iterator MI,
978dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
979dff0c46cSDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
980dff0c46cSDimitry Andric                                     const TargetRegisterInfo *TRI) {
981dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
982dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
983dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
984dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
985dff0c46cSDimitry Andric   MachineFrameInfo &MFI = *MF.getFrameInfo();
986dff0c46cSDimitry Andric 
987dff0c46cSDimitry Andric   // Mark the D-register spill slots as properly aligned.  Since MFI computes
988dff0c46cSDimitry Andric   // stack slot layout backwards, this can actually mean that the d-reg stack
989dff0c46cSDimitry Andric   // slot offsets can be wrong. The offset for d8 will always be correct.
990dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
991dff0c46cSDimitry Andric     unsigned DNum = CSI[i].getReg() - ARM::D8;
992dff0c46cSDimitry Andric     if (DNum >= 8)
993dff0c46cSDimitry Andric       continue;
994dff0c46cSDimitry Andric     int FI = CSI[i].getFrameIdx();
995dff0c46cSDimitry Andric     // The even-numbered registers will be 16-byte aligned, the odd-numbered
996dff0c46cSDimitry Andric     // registers will be 8-byte aligned.
997dff0c46cSDimitry Andric     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
998dff0c46cSDimitry Andric 
999dff0c46cSDimitry Andric     // The stack slot for D8 needs to be maximally aligned because this is
1000dff0c46cSDimitry Andric     // actually the point where we align the stack pointer.  MachineFrameInfo
1001dff0c46cSDimitry Andric     // computes all offsets relative to the incoming stack pointer which is a
1002dff0c46cSDimitry Andric     // bit weird when realigning the stack.  Any extra padding for this
1003dff0c46cSDimitry Andric     // over-alignment is not realized because the code inserted below adjusts
1004dff0c46cSDimitry Andric     // the stack pointer by numregs * 8 before aligning the stack pointer.
1005dff0c46cSDimitry Andric     if (DNum == 0)
1006dff0c46cSDimitry Andric       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1007dff0c46cSDimitry Andric   }
1008dff0c46cSDimitry Andric 
1009dff0c46cSDimitry Andric   // Move the stack pointer to the d8 spill slot, and align it at the same
1010dff0c46cSDimitry Andric   // time. Leave the stack slot address in the scratch register r4.
1011dff0c46cSDimitry Andric   //
1012dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1013dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1014dff0c46cSDimitry Andric   //   mov sp, r4
1015dff0c46cSDimitry Andric   //
1016dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1017dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1018dff0c46cSDimitry Andric   AFI->setShouldRestoreSPFromFP(true);
1019dff0c46cSDimitry Andric 
1020dff0c46cSDimitry Andric   // sub r4, sp, #numregs * 8
1021dff0c46cSDimitry Andric   // The immediate is <= 64, so it doesn't need any special encoding.
1022dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1023dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1024dff0c46cSDimitry Andric                               .addReg(ARM::SP)
1025dff0c46cSDimitry Andric                               .addImm(8 * NumAlignedDPRCS2Regs)));
1026dff0c46cSDimitry Andric 
1027dff0c46cSDimitry Andric   // bic r4, r4, #align-1
1028dff0c46cSDimitry Andric   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1029dff0c46cSDimitry Andric   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1030dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1031dff0c46cSDimitry Andric                               .addReg(ARM::R4, RegState::Kill)
1032dff0c46cSDimitry Andric                               .addImm(MaxAlign - 1)));
1033dff0c46cSDimitry Andric 
1034dff0c46cSDimitry Andric   // mov sp, r4
1035dff0c46cSDimitry Andric   // The stack pointer must be adjusted before spilling anything, otherwise
1036dff0c46cSDimitry Andric   // the stack slots could be clobbered by an interrupt handler.
1037dff0c46cSDimitry Andric   // Leave r4 live, it is used below.
1038dff0c46cSDimitry Andric   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1039dff0c46cSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1040dff0c46cSDimitry Andric                             .addReg(ARM::R4);
1041dff0c46cSDimitry Andric   MIB = AddDefaultPred(MIB);
1042dff0c46cSDimitry Andric   if (!isThumb)
1043dff0c46cSDimitry Andric     AddDefaultCC(MIB);
1044dff0c46cSDimitry Andric 
1045dff0c46cSDimitry Andric   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1046dff0c46cSDimitry Andric   // r4 holds the stack slot address.
1047dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1048dff0c46cSDimitry Andric 
1049dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1050dff0c46cSDimitry Andric   // The writeback is only needed when emitting two vst1.64 instructions.
1051dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1052dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
10537ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1054dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1055dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1056dff0c46cSDimitry Andric                            ARM::R4)
1057dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1058dff0c46cSDimitry Andric                    .addReg(NextReg)
1059dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1060dff0c46cSDimitry Andric     NextReg += 4;
1061dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1062dff0c46cSDimitry Andric   }
1063dff0c46cSDimitry Andric 
1064dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1065dff0c46cSDimitry Andric   // register to be spilled.
1066dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1067dff0c46cSDimitry Andric 
1068dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1069dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1070dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
10717ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1072dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1073dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1074dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
1075dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1076dff0c46cSDimitry Andric     NextReg += 4;
1077dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1078dff0c46cSDimitry Andric   }
1079dff0c46cSDimitry Andric 
1080dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 2 d-regs.
1081dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1082dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
10837ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1084dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1085dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1086dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
1087dff0c46cSDimitry Andric     NextReg += 2;
1088dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1089dff0c46cSDimitry Andric   }
1090dff0c46cSDimitry Andric 
1091dff0c46cSDimitry Andric   // Finally, use a vanilla vstr.64 for the odd last register.
1092dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs) {
1093dff0c46cSDimitry Andric     MBB.addLiveIn(NextReg);
1094dff0c46cSDimitry Andric     // vstr.64 uses addrmode5 which has an offset scale of 4.
1095dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1096dff0c46cSDimitry Andric                    .addReg(NextReg)
1097dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1098dff0c46cSDimitry Andric   }
1099dff0c46cSDimitry Andric 
1100dff0c46cSDimitry Andric   // The last spill instruction inserted should kill the scratch register r4.
110191bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1102dff0c46cSDimitry Andric }
1103dff0c46cSDimitry Andric 
1104dff0c46cSDimitry Andric /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1105dff0c46cSDimitry Andric /// iterator to the following instruction.
1106dff0c46cSDimitry Andric static MachineBasicBlock::iterator
1107dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1108dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs) {
1109dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1110dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1111dff0c46cSDimitry Andric   //   mov sp, r4
1112dff0c46cSDimitry Andric   ++MI; ++MI; ++MI;
1113dff0c46cSDimitry Andric   assert(MI->mayStore() && "Expecting spill instruction");
1114dff0c46cSDimitry Andric 
1115dff0c46cSDimitry Andric   // These switches all fall through.
1116dff0c46cSDimitry Andric   switch(NumAlignedDPRCS2Regs) {
1117dff0c46cSDimitry Andric   case 7:
1118dff0c46cSDimitry Andric     ++MI;
1119dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1120dff0c46cSDimitry Andric   default:
1121dff0c46cSDimitry Andric     ++MI;
1122dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1123dff0c46cSDimitry Andric   case 1:
1124dff0c46cSDimitry Andric   case 2:
1125dff0c46cSDimitry Andric   case 4:
1126dff0c46cSDimitry Andric     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1127dff0c46cSDimitry Andric     ++MI;
1128dff0c46cSDimitry Andric   }
1129dff0c46cSDimitry Andric   return MI;
1130dff0c46cSDimitry Andric }
1131dff0c46cSDimitry Andric 
1132dff0c46cSDimitry Andric /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1133dff0c46cSDimitry Andric /// starting from d8.  These instructions are assumed to execute while the
1134dff0c46cSDimitry Andric /// stack is still aligned, unlike the code inserted by emitPopInst.
1135dff0c46cSDimitry Andric static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1136dff0c46cSDimitry Andric                                       MachineBasicBlock::iterator MI,
1137dff0c46cSDimitry Andric                                       unsigned NumAlignedDPRCS2Regs,
1138dff0c46cSDimitry Andric                                       const std::vector<CalleeSavedInfo> &CSI,
1139dff0c46cSDimitry Andric                                       const TargetRegisterInfo *TRI) {
1140dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1141dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1142dff0c46cSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
1143dff0c46cSDimitry Andric   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1144dff0c46cSDimitry Andric 
1145dff0c46cSDimitry Andric   // Find the frame index assigned to d8.
1146dff0c46cSDimitry Andric   int D8SpillFI = 0;
1147dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1148dff0c46cSDimitry Andric     if (CSI[i].getReg() == ARM::D8) {
1149dff0c46cSDimitry Andric       D8SpillFI = CSI[i].getFrameIdx();
1150dff0c46cSDimitry Andric       break;
1151dff0c46cSDimitry Andric     }
1152dff0c46cSDimitry Andric 
1153dff0c46cSDimitry Andric   // Materialize the address of the d8 spill slot into the scratch register r4.
1154dff0c46cSDimitry Andric   // This can be fairly complicated if the stack frame is large, so just use
1155dff0c46cSDimitry Andric   // the normal frame index elimination mechanism to do it.  This code runs as
1156dff0c46cSDimitry Andric   // the initial part of the epilog where the stack and base pointers haven't
1157dff0c46cSDimitry Andric   // been changed yet.
1158dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1159dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1160dff0c46cSDimitry Andric 
1161dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1162dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1163dff0c46cSDimitry Andric                               .addFrameIndex(D8SpillFI).addImm(0)));
1164dff0c46cSDimitry Andric 
1165dff0c46cSDimitry Andric   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1166dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1167dff0c46cSDimitry Andric 
1168dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1169dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1170dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11717ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1172dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1173dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Define)
1174dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1175dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1176dff0c46cSDimitry Andric     NextReg += 4;
1177dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1178dff0c46cSDimitry Andric   }
1179dff0c46cSDimitry Andric 
1180dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1181dff0c46cSDimitry Andric   // register to be spilled.
1182dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1183dff0c46cSDimitry Andric 
1184dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1185dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1186dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11877ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1188dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1189dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16)
1190dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1191dff0c46cSDimitry Andric     NextReg += 4;
1192dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1193dff0c46cSDimitry Andric   }
1194dff0c46cSDimitry Andric 
1195dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 2 d-regs.
1196dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1197dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11987ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1199dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1200dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16));
1201dff0c46cSDimitry Andric     NextReg += 2;
1202dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1203dff0c46cSDimitry Andric   }
1204dff0c46cSDimitry Andric 
1205dff0c46cSDimitry Andric   // Finally, use a vanilla vldr.64 for the remaining odd register.
1206dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1207dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1208dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1209dff0c46cSDimitry Andric 
1210dff0c46cSDimitry Andric   // Last store kills r4.
121191bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1212dff0c46cSDimitry Andric }
1213dff0c46cSDimitry Andric 
12142754fe60SDimitry Andric bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
12152754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
12162754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
12172754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
12182754fe60SDimitry Andric   if (CSI.empty())
12192754fe60SDimitry Andric     return false;
12202754fe60SDimitry Andric 
12212754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
12222754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12232754fe60SDimitry Andric 
12242754fe60SDimitry Andric   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
12256122f3e6SDimitry Andric   unsigned PushOneOpc = AFI->isThumbFunction() ?
12266122f3e6SDimitry Andric     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
12272754fe60SDimitry Andric   unsigned FltOpc = ARM::VSTMDDB_UPD;
1228dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1229dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
12303b0f4066SDimitry Andric                MachineInstr::FrameSetup);
1231dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
12323b0f4066SDimitry Andric                MachineInstr::FrameSetup);
12333b0f4066SDimitry Andric   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1234dff0c46cSDimitry Andric                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1235dff0c46cSDimitry Andric 
1236dff0c46cSDimitry Andric   // The code above does not insert spill code for the aligned DPRCS2 registers.
1237dff0c46cSDimitry Andric   // The stack realignment code will be inserted between the push instructions
1238dff0c46cSDimitry Andric   // and these spills.
1239dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1240dff0c46cSDimitry Andric     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
12412754fe60SDimitry Andric 
12422754fe60SDimitry Andric   return true;
12432754fe60SDimitry Andric }
12442754fe60SDimitry Andric 
12452754fe60SDimitry Andric bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
12462754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
12472754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
12482754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
12492754fe60SDimitry Andric   if (CSI.empty())
12502754fe60SDimitry Andric     return false;
12512754fe60SDimitry Andric 
12522754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
12532754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1254284c1978SDimitry Andric   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1255dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1256dff0c46cSDimitry Andric 
1257dff0c46cSDimitry Andric   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1258dff0c46cSDimitry Andric   // registers. Do that here instead.
1259dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1260dff0c46cSDimitry Andric     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
12612754fe60SDimitry Andric 
12622754fe60SDimitry Andric   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
12636122f3e6SDimitry Andric   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
12642754fe60SDimitry Andric   unsigned FltOpc = ARM::VLDMDIA_UPD;
1265dff0c46cSDimitry Andric   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1266dff0c46cSDimitry Andric               NumAlignedDPRCS2Regs);
12672754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1268dff0c46cSDimitry Andric               &isARMArea2Register, 0);
12692754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1270dff0c46cSDimitry Andric               &isARMArea1Register, 0);
12712754fe60SDimitry Andric 
12722754fe60SDimitry Andric   return true;
12732754fe60SDimitry Andric }
12742754fe60SDimitry Andric 
12752754fe60SDimitry Andric // FIXME: Make generic?
12762754fe60SDimitry Andric static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
12772754fe60SDimitry Andric                                        const ARMBaseInstrInfo &TII) {
12782754fe60SDimitry Andric   unsigned FnSize = 0;
127991bc56edSDimitry Andric   for (auto &MBB : MF) {
128091bc56edSDimitry Andric     for (auto &MI : MBB)
128191bc56edSDimitry Andric       FnSize += TII.GetInstSizeInBytes(&MI);
12822754fe60SDimitry Andric   }
12832754fe60SDimitry Andric   return FnSize;
12842754fe60SDimitry Andric }
12852754fe60SDimitry Andric 
12862754fe60SDimitry Andric /// estimateRSStackSizeLimit - Look at each instruction that references stack
12872754fe60SDimitry Andric /// frames and return the stack size limit beyond which some of these
12882754fe60SDimitry Andric /// instructions will require a scratch register during their expansion later.
12892754fe60SDimitry Andric // FIXME: Move to TII?
12902754fe60SDimitry Andric static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
12912754fe60SDimitry Andric                                          const TargetFrameLowering *TFI) {
12922754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12932754fe60SDimitry Andric   unsigned Limit = (1 << 12) - 1;
129491bc56edSDimitry Andric   for (auto &MBB : MF) {
129591bc56edSDimitry Andric     for (auto &MI : MBB) {
129691bc56edSDimitry Andric       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
129791bc56edSDimitry Andric         if (!MI.getOperand(i).isFI())
129891bc56edSDimitry Andric           continue;
12992754fe60SDimitry Andric 
13002754fe60SDimitry Andric         // When using ADDri to get the address of a stack object, 255 is the
13012754fe60SDimitry Andric         // largest offset guaranteed to fit in the immediate offset.
130291bc56edSDimitry Andric         if (MI.getOpcode() == ARM::ADDri) {
13032754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
13042754fe60SDimitry Andric           break;
13052754fe60SDimitry Andric         }
13062754fe60SDimitry Andric 
13072754fe60SDimitry Andric         // Otherwise check the addressing mode.
130891bc56edSDimitry Andric         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
13092754fe60SDimitry Andric         case ARMII::AddrMode3:
13102754fe60SDimitry Andric         case ARMII::AddrModeT2_i8:
13112754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
13122754fe60SDimitry Andric           break;
13132754fe60SDimitry Andric         case ARMII::AddrMode5:
13142754fe60SDimitry Andric         case ARMII::AddrModeT2_i8s4:
13152754fe60SDimitry Andric           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
13162754fe60SDimitry Andric           break;
13172754fe60SDimitry Andric         case ARMII::AddrModeT2_i12:
13182754fe60SDimitry Andric           // i12 supports only positive offset so these will be converted to
13192754fe60SDimitry Andric           // i8 opcodes. See llvm::rewriteT2FrameIndex.
13202754fe60SDimitry Andric           if (TFI->hasFP(MF) && AFI->hasStackFrame())
13212754fe60SDimitry Andric             Limit = std::min(Limit, (1U << 8) - 1);
13222754fe60SDimitry Andric           break;
13232754fe60SDimitry Andric         case ARMII::AddrMode4:
13242754fe60SDimitry Andric         case ARMII::AddrMode6:
13252754fe60SDimitry Andric           // Addressing modes 4 & 6 (load/store) instructions can't encode an
13262754fe60SDimitry Andric           // immediate offset for stack references.
13272754fe60SDimitry Andric           return 0;
13282754fe60SDimitry Andric         default:
13292754fe60SDimitry Andric           break;
13302754fe60SDimitry Andric         }
13312754fe60SDimitry Andric         break; // At most one FI per instruction
13322754fe60SDimitry Andric       }
13332754fe60SDimitry Andric     }
13342754fe60SDimitry Andric   }
13352754fe60SDimitry Andric 
13362754fe60SDimitry Andric   return Limit;
13372754fe60SDimitry Andric }
13382754fe60SDimitry Andric 
1339dff0c46cSDimitry Andric // In functions that realign the stack, it can be an advantage to spill the
1340dff0c46cSDimitry Andric // callee-saved vector registers after realigning the stack. The vst1 and vld1
1341dff0c46cSDimitry Andric // instructions take alignment hints that can improve performance.
1342dff0c46cSDimitry Andric //
1343dff0c46cSDimitry Andric static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1344dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1345dff0c46cSDimitry Andric   if (!SpillAlignedNEONRegs)
1346dff0c46cSDimitry Andric     return;
1347dff0c46cSDimitry Andric 
1348dff0c46cSDimitry Andric   // Naked functions don't spill callee-saved registers.
1349139f7f9bSDimitry Andric   if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1350139f7f9bSDimitry Andric                                                      Attribute::Naked))
1351dff0c46cSDimitry Andric     return;
1352dff0c46cSDimitry Andric 
1353dff0c46cSDimitry Andric   // We are planning to use NEON instructions vst1 / vld1.
1354dff0c46cSDimitry Andric   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1355dff0c46cSDimitry Andric     return;
1356dff0c46cSDimitry Andric 
1357dff0c46cSDimitry Andric   // Don't bother if the default stack alignment is sufficiently high.
1358dff0c46cSDimitry Andric   if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1359dff0c46cSDimitry Andric     return;
1360dff0c46cSDimitry Andric 
1361dff0c46cSDimitry Andric   // Aligned spills require stack realignment.
1362dff0c46cSDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
1363dff0c46cSDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1364dff0c46cSDimitry Andric   if (!RegInfo->canRealignStack(MF))
1365dff0c46cSDimitry Andric     return;
1366dff0c46cSDimitry Andric 
1367dff0c46cSDimitry Andric   // We always spill contiguous d-registers starting from d8. Count how many
1368dff0c46cSDimitry Andric   // needs spilling.  The register allocator will almost always use the
1369dff0c46cSDimitry Andric   // callee-saved registers in order, but it can happen that there are holes in
1370dff0c46cSDimitry Andric   // the range.  Registers above the hole will be spilled to the standard DPRCS
1371dff0c46cSDimitry Andric   // area.
1372dff0c46cSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
1373dff0c46cSDimitry Andric   unsigned NumSpills = 0;
1374dff0c46cSDimitry Andric   for (; NumSpills < 8; ++NumSpills)
13753861d79fSDimitry Andric     if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1376dff0c46cSDimitry Andric       break;
1377dff0c46cSDimitry Andric 
1378dff0c46cSDimitry Andric   // Don't do this for just one d-register. It's not worth it.
1379dff0c46cSDimitry Andric   if (NumSpills < 2)
1380dff0c46cSDimitry Andric     return;
1381dff0c46cSDimitry Andric 
1382dff0c46cSDimitry Andric   // Spill the first NumSpills D-registers after realigning the stack.
1383dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1384dff0c46cSDimitry Andric 
1385dff0c46cSDimitry Andric   // A scratch register is required for the vst1 / vld1 instructions.
1386dff0c46cSDimitry Andric   MF.getRegInfo().setPhysRegUsed(ARM::R4);
1387dff0c46cSDimitry Andric }
1388dff0c46cSDimitry Andric 
13892754fe60SDimitry Andric void
13902754fe60SDimitry Andric ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
13912754fe60SDimitry Andric                                                        RegScavenger *RS) const {
13922754fe60SDimitry Andric   // This tells PEI to spill the FP as if it is any other callee-save register
13932754fe60SDimitry Andric   // to take advantage the eliminateFrameIndex machinery. This also ensures it
13942754fe60SDimitry Andric   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
13952754fe60SDimitry Andric   // to combine multiple loads / stores.
13962754fe60SDimitry Andric   bool CanEliminateFrame = true;
13972754fe60SDimitry Andric   bool CS1Spilled = false;
13982754fe60SDimitry Andric   bool LRSpilled = false;
13992754fe60SDimitry Andric   unsigned NumGPRSpills = 0;
14002754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS1GPRs;
14012754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS2GPRs;
14022754fe60SDimitry Andric   const ARMBaseRegisterInfo *RegInfo =
14032754fe60SDimitry Andric     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
14042754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
14052754fe60SDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
14062754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
14072754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
14083861d79fSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
14092754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
14102754fe60SDimitry Andric 
14112754fe60SDimitry Andric   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
14122754fe60SDimitry Andric   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
14132754fe60SDimitry Andric   // since it's not always possible to restore sp from fp in a single
14142754fe60SDimitry Andric   // instruction.
14152754fe60SDimitry Andric   // FIXME: It will be better just to find spare register here.
14162754fe60SDimitry Andric   if (AFI->isThumb2Function() &&
14172754fe60SDimitry Andric       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
14183861d79fSDimitry Andric     MRI.setPhysRegUsed(ARM::R4);
14192754fe60SDimitry Andric 
14202754fe60SDimitry Andric   if (AFI->isThumb1OnlyFunction()) {
14212754fe60SDimitry Andric     // Spill LR if Thumb1 function uses variable length argument lists.
1422284c1978SDimitry Andric     if (AFI->getArgRegsSaveSize() > 0)
14233861d79fSDimitry Andric       MRI.setPhysRegUsed(ARM::LR);
14242754fe60SDimitry Andric 
142517a519f9SDimitry Andric     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
142617a519f9SDimitry Andric     // for sure what the stack size will be, but for this, an estimate is good
142717a519f9SDimitry Andric     // enough. If there anything changes it, it'll be a spill, which implies
142817a519f9SDimitry Andric     // we've used all the registers and so R4 is already used, so not marking
142917a519f9SDimitry Andric     // it here will be OK.
14302754fe60SDimitry Andric     // FIXME: It will be better just to find spare register here.
1431139f7f9bSDimitry Andric     unsigned StackSize = MFI->estimateStackSize(MF);
143217a519f9SDimitry Andric     if (MFI->hasVarSizedObjects() || StackSize > 508)
14333861d79fSDimitry Andric       MRI.setPhysRegUsed(ARM::R4);
14342754fe60SDimitry Andric   }
14352754fe60SDimitry Andric 
1436dff0c46cSDimitry Andric   // See if we can spill vector registers to aligned stack.
1437dff0c46cSDimitry Andric   checkNumAlignedDPRCS2Regs(MF);
1438dff0c46cSDimitry Andric 
14392754fe60SDimitry Andric   // Spill the BasePtr if it's used.
14402754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
14413861d79fSDimitry Andric     MRI.setPhysRegUsed(RegInfo->getBaseRegister());
14422754fe60SDimitry Andric 
14432754fe60SDimitry Andric   // Don't spill FP if the frame can be eliminated. This is determined
14442754fe60SDimitry Andric   // by scanning the callee-save registers to see if any is used.
144591bc56edSDimitry Andric   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
14462754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i) {
14472754fe60SDimitry Andric     unsigned Reg = CSRegs[i];
14482754fe60SDimitry Andric     bool Spilled = false;
14493861d79fSDimitry Andric     if (MRI.isPhysRegUsed(Reg)) {
14502754fe60SDimitry Andric       Spilled = true;
14512754fe60SDimitry Andric       CanEliminateFrame = false;
14522754fe60SDimitry Andric     }
14532754fe60SDimitry Andric 
14547ae0e2c9SDimitry Andric     if (!ARM::GPRRegClass.contains(Reg))
14552754fe60SDimitry Andric       continue;
14562754fe60SDimitry Andric 
14572754fe60SDimitry Andric     if (Spilled) {
14582754fe60SDimitry Andric       NumGPRSpills++;
14592754fe60SDimitry Andric 
146091bc56edSDimitry Andric       if (!STI.isTargetDarwin()) {
14612754fe60SDimitry Andric         if (Reg == ARM::LR)
14622754fe60SDimitry Andric           LRSpilled = true;
14632754fe60SDimitry Andric         CS1Spilled = true;
14642754fe60SDimitry Andric         continue;
14652754fe60SDimitry Andric       }
14662754fe60SDimitry Andric 
14672754fe60SDimitry Andric       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
14682754fe60SDimitry Andric       switch (Reg) {
14692754fe60SDimitry Andric       case ARM::LR:
14702754fe60SDimitry Andric         LRSpilled = true;
14712754fe60SDimitry Andric         // Fallthrough
1472f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1473f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
14742754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
14752754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
14762754fe60SDimitry Andric         CS1Spilled = true;
14772754fe60SDimitry Andric         break;
14782754fe60SDimitry Andric       default:
14792754fe60SDimitry Andric         break;
14802754fe60SDimitry Andric       }
14812754fe60SDimitry Andric     } else {
148291bc56edSDimitry Andric       if (!STI.isTargetDarwin()) {
14832754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
14842754fe60SDimitry Andric         continue;
14852754fe60SDimitry Andric       }
14862754fe60SDimitry Andric 
14872754fe60SDimitry Andric       switch (Reg) {
1488f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1489f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
14902754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
14912754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
14922754fe60SDimitry Andric       case ARM::LR:
14932754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
14942754fe60SDimitry Andric         break;
14952754fe60SDimitry Andric       default:
14962754fe60SDimitry Andric         UnspilledCS2GPRs.push_back(Reg);
14972754fe60SDimitry Andric         break;
14982754fe60SDimitry Andric       }
14992754fe60SDimitry Andric     }
15002754fe60SDimitry Andric   }
15012754fe60SDimitry Andric 
15022754fe60SDimitry Andric   bool ForceLRSpill = false;
15032754fe60SDimitry Andric   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
15042754fe60SDimitry Andric     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
15052754fe60SDimitry Andric     // Force LR to be spilled if the Thumb function size is > 2048. This enables
15062754fe60SDimitry Andric     // use of BL to implement far jump. If it turns out that it's not needed
15072754fe60SDimitry Andric     // then the branch fix up path will undo it.
15082754fe60SDimitry Andric     if (FnSize >= (1 << 11)) {
15092754fe60SDimitry Andric       CanEliminateFrame = false;
15102754fe60SDimitry Andric       ForceLRSpill = true;
15112754fe60SDimitry Andric     }
15122754fe60SDimitry Andric   }
15132754fe60SDimitry Andric 
15142754fe60SDimitry Andric   // If any of the stack slot references may be out of range of an immediate
15152754fe60SDimitry Andric   // offset, make sure a register (or a spill slot) is available for the
15162754fe60SDimitry Andric   // register scavenger. Note that if we're indexing off the frame pointer, the
15172754fe60SDimitry Andric   // effective stack size is 4 bytes larger since the FP points to the stack
15182754fe60SDimitry Andric   // slot of the previous FP. Also, if we have variable sized objects in the
15192754fe60SDimitry Andric   // function, stack slot references will often be negative, and some of
15202754fe60SDimitry Andric   // our instructions are positive-offset only, so conservatively consider
15212754fe60SDimitry Andric   // that case to want a spill slot (or register) as well. Similarly, if
15222754fe60SDimitry Andric   // the function adjusts the stack pointer during execution and the
15232754fe60SDimitry Andric   // adjustments aren't already part of our stack size estimate, our offset
15242754fe60SDimitry Andric   // calculations may be off, so be conservative.
15252754fe60SDimitry Andric   // FIXME: We could add logic to be more precise about negative offsets
15262754fe60SDimitry Andric   //        and which instructions will need a scratch register for them. Is it
15272754fe60SDimitry Andric   //        worth the effort and added fragility?
15282754fe60SDimitry Andric   bool BigStack =
15292754fe60SDimitry Andric     (RS &&
1530139f7f9bSDimitry Andric      (MFI->estimateStackSize(MF) +
1531139f7f9bSDimitry Andric       ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
15322754fe60SDimitry Andric       estimateRSStackSizeLimit(MF, this)))
15332754fe60SDimitry Andric     || MFI->hasVarSizedObjects()
15342754fe60SDimitry Andric     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
15352754fe60SDimitry Andric 
15362754fe60SDimitry Andric   bool ExtraCSSpill = false;
15372754fe60SDimitry Andric   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
15382754fe60SDimitry Andric     AFI->setHasStackFrame(true);
15392754fe60SDimitry Andric 
15402754fe60SDimitry Andric     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
15412754fe60SDimitry Andric     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
15422754fe60SDimitry Andric     if (!LRSpilled && CS1Spilled) {
15433861d79fSDimitry Andric       MRI.setPhysRegUsed(ARM::LR);
15442754fe60SDimitry Andric       NumGPRSpills++;
1545f785676fSDimitry Andric       SmallVectorImpl<unsigned>::iterator LRPos;
1546f785676fSDimitry Andric       LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1547f785676fSDimitry Andric                         (unsigned)ARM::LR);
1548f785676fSDimitry Andric       if (LRPos != UnspilledCS1GPRs.end())
1549f785676fSDimitry Andric         UnspilledCS1GPRs.erase(LRPos);
1550f785676fSDimitry Andric 
15512754fe60SDimitry Andric       ForceLRSpill = false;
15522754fe60SDimitry Andric       ExtraCSSpill = true;
15532754fe60SDimitry Andric     }
15542754fe60SDimitry Andric 
15552754fe60SDimitry Andric     if (hasFP(MF)) {
15563861d79fSDimitry Andric       MRI.setPhysRegUsed(FramePtr);
155791bc56edSDimitry Andric       auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
155891bc56edSDimitry Andric                              FramePtr);
155991bc56edSDimitry Andric       if (FPPos != UnspilledCS1GPRs.end())
156091bc56edSDimitry Andric         UnspilledCS1GPRs.erase(FPPos);
15612754fe60SDimitry Andric       NumGPRSpills++;
15622754fe60SDimitry Andric     }
15632754fe60SDimitry Andric 
15642754fe60SDimitry Andric     // If stack and double are 8-byte aligned and we are spilling an odd number
15652754fe60SDimitry Andric     // of GPRs, spill one extra callee save GPR so we won't have to pad between
15662754fe60SDimitry Andric     // the integer and double callee save areas.
15672754fe60SDimitry Andric     unsigned TargetAlign = getStackAlignment();
15682754fe60SDimitry Andric     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
15692754fe60SDimitry Andric       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
15702754fe60SDimitry Andric         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
15712754fe60SDimitry Andric           unsigned Reg = UnspilledCS1GPRs[i];
15722754fe60SDimitry Andric           // Don't spill high register if the function is thumb1
15732754fe60SDimitry Andric           if (!AFI->isThumb1OnlyFunction() ||
15742754fe60SDimitry Andric               isARMLowRegister(Reg) || Reg == ARM::LR) {
15753861d79fSDimitry Andric             MRI.setPhysRegUsed(Reg);
15763861d79fSDimitry Andric             if (!MRI.isReserved(Reg))
15772754fe60SDimitry Andric               ExtraCSSpill = true;
15782754fe60SDimitry Andric             break;
15792754fe60SDimitry Andric           }
15802754fe60SDimitry Andric         }
15812754fe60SDimitry Andric       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
15822754fe60SDimitry Andric         unsigned Reg = UnspilledCS2GPRs.front();
15833861d79fSDimitry Andric         MRI.setPhysRegUsed(Reg);
15843861d79fSDimitry Andric         if (!MRI.isReserved(Reg))
15852754fe60SDimitry Andric           ExtraCSSpill = true;
15862754fe60SDimitry Andric       }
15872754fe60SDimitry Andric     }
15882754fe60SDimitry Andric 
15892754fe60SDimitry Andric     // Estimate if we might need to scavenge a register at some point in order
15902754fe60SDimitry Andric     // to materialize a stack offset. If so, either spill one additional
15912754fe60SDimitry Andric     // callee-saved register or reserve a special spill slot to facilitate
15922754fe60SDimitry Andric     // register scavenging. Thumb1 needs a spill slot for stack pointer
15932754fe60SDimitry Andric     // adjustments also, even when the frame itself is small.
15942754fe60SDimitry Andric     if (BigStack && !ExtraCSSpill) {
15952754fe60SDimitry Andric       // If any non-reserved CS register isn't spilled, just spill one or two
15962754fe60SDimitry Andric       // extra. That should take care of it!
15972754fe60SDimitry Andric       unsigned NumExtras = TargetAlign / 4;
15982754fe60SDimitry Andric       SmallVector<unsigned, 2> Extras;
15992754fe60SDimitry Andric       while (NumExtras && !UnspilledCS1GPRs.empty()) {
16002754fe60SDimitry Andric         unsigned Reg = UnspilledCS1GPRs.back();
16012754fe60SDimitry Andric         UnspilledCS1GPRs.pop_back();
16023861d79fSDimitry Andric         if (!MRI.isReserved(Reg) &&
16032754fe60SDimitry Andric             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
16042754fe60SDimitry Andric              Reg == ARM::LR)) {
16052754fe60SDimitry Andric           Extras.push_back(Reg);
16062754fe60SDimitry Andric           NumExtras--;
16072754fe60SDimitry Andric         }
16082754fe60SDimitry Andric       }
16092754fe60SDimitry Andric       // For non-Thumb1 functions, also check for hi-reg CS registers
16102754fe60SDimitry Andric       if (!AFI->isThumb1OnlyFunction()) {
16112754fe60SDimitry Andric         while (NumExtras && !UnspilledCS2GPRs.empty()) {
16122754fe60SDimitry Andric           unsigned Reg = UnspilledCS2GPRs.back();
16132754fe60SDimitry Andric           UnspilledCS2GPRs.pop_back();
16143861d79fSDimitry Andric           if (!MRI.isReserved(Reg)) {
16152754fe60SDimitry Andric             Extras.push_back(Reg);
16162754fe60SDimitry Andric             NumExtras--;
16172754fe60SDimitry Andric           }
16182754fe60SDimitry Andric         }
16192754fe60SDimitry Andric       }
16202754fe60SDimitry Andric       if (Extras.size() && NumExtras == 0) {
16212754fe60SDimitry Andric         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
16223861d79fSDimitry Andric           MRI.setPhysRegUsed(Extras[i]);
16232754fe60SDimitry Andric         }
16242754fe60SDimitry Andric       } else if (!AFI->isThumb1OnlyFunction()) {
16252754fe60SDimitry Andric         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
16262754fe60SDimitry Andric         // closest to SP or frame pointer.
16277ae0e2c9SDimitry Andric         const TargetRegisterClass *RC = &ARM::GPRRegClass;
1628139f7f9bSDimitry Andric         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
16292754fe60SDimitry Andric                                                            RC->getAlignment(),
16302754fe60SDimitry Andric                                                            false));
16312754fe60SDimitry Andric       }
16322754fe60SDimitry Andric     }
16332754fe60SDimitry Andric   }
16342754fe60SDimitry Andric 
16352754fe60SDimitry Andric   if (ForceLRSpill) {
16363861d79fSDimitry Andric     MRI.setPhysRegUsed(ARM::LR);
16372754fe60SDimitry Andric     AFI->setLRIsSpilledForFarJump(true);
16382754fe60SDimitry Andric   }
16392754fe60SDimitry Andric }
1640139f7f9bSDimitry Andric 
1641139f7f9bSDimitry Andric 
1642139f7f9bSDimitry Andric void ARMFrameLowering::
1643139f7f9bSDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1644139f7f9bSDimitry Andric                               MachineBasicBlock::iterator I) const {
1645139f7f9bSDimitry Andric   const ARMBaseInstrInfo &TII =
1646139f7f9bSDimitry Andric     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1647139f7f9bSDimitry Andric   if (!hasReservedCallFrame(MF)) {
1648139f7f9bSDimitry Andric     // If we have alloca, convert as follows:
1649139f7f9bSDimitry Andric     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1650139f7f9bSDimitry Andric     // ADJCALLSTACKUP   -> add, sp, sp, amount
1651139f7f9bSDimitry Andric     MachineInstr *Old = I;
1652139f7f9bSDimitry Andric     DebugLoc dl = Old->getDebugLoc();
1653139f7f9bSDimitry Andric     unsigned Amount = Old->getOperand(0).getImm();
1654139f7f9bSDimitry Andric     if (Amount != 0) {
1655139f7f9bSDimitry Andric       // We need to keep the stack aligned properly.  To do this, we round the
1656139f7f9bSDimitry Andric       // amount of space needed for the outgoing arguments up to the next
1657139f7f9bSDimitry Andric       // alignment boundary.
1658139f7f9bSDimitry Andric       unsigned Align = getStackAlignment();
1659139f7f9bSDimitry Andric       Amount = (Amount+Align-1)/Align*Align;
1660139f7f9bSDimitry Andric 
1661139f7f9bSDimitry Andric       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1662139f7f9bSDimitry Andric       assert(!AFI->isThumb1OnlyFunction() &&
1663139f7f9bSDimitry Andric              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1664139f7f9bSDimitry Andric       bool isARM = !AFI->isThumbFunction();
1665139f7f9bSDimitry Andric 
1666139f7f9bSDimitry Andric       // Replace the pseudo instruction with a new instruction...
1667139f7f9bSDimitry Andric       unsigned Opc = Old->getOpcode();
1668139f7f9bSDimitry Andric       int PIdx = Old->findFirstPredOperandIdx();
1669139f7f9bSDimitry Andric       ARMCC::CondCodes Pred = (PIdx == -1)
1670139f7f9bSDimitry Andric         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1671139f7f9bSDimitry Andric       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1672139f7f9bSDimitry Andric         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1673139f7f9bSDimitry Andric         unsigned PredReg = Old->getOperand(2).getReg();
1674139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1675139f7f9bSDimitry Andric                      Pred, PredReg);
1676139f7f9bSDimitry Andric       } else {
1677139f7f9bSDimitry Andric         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1678139f7f9bSDimitry Andric         unsigned PredReg = Old->getOperand(3).getReg();
1679139f7f9bSDimitry Andric         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1680139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1681139f7f9bSDimitry Andric                      Pred, PredReg);
1682139f7f9bSDimitry Andric       }
1683139f7f9bSDimitry Andric     }
1684139f7f9bSDimitry Andric   }
1685139f7f9bSDimitry Andric   MBB.erase(I);
1686139f7f9bSDimitry Andric }
1687139f7f9bSDimitry Andric 
168891bc56edSDimitry Andric /// Get the minimum constant for ARM that is greater than or equal to the
168991bc56edSDimitry Andric /// argument. In ARM, constants can have any value that can be produced by
169091bc56edSDimitry Andric /// rotating an 8-bit value to the right by an even number of bits within a
169191bc56edSDimitry Andric /// 32-bit word.
169291bc56edSDimitry Andric static uint32_t alignToARMConstant(uint32_t Value) {
169391bc56edSDimitry Andric   unsigned Shifted = 0;
169491bc56edSDimitry Andric 
169591bc56edSDimitry Andric   if (Value == 0)
169691bc56edSDimitry Andric       return 0;
169791bc56edSDimitry Andric 
169891bc56edSDimitry Andric   while (!(Value & 0xC0000000)) {
169991bc56edSDimitry Andric       Value = Value << 2;
170091bc56edSDimitry Andric       Shifted += 2;
170191bc56edSDimitry Andric   }
170291bc56edSDimitry Andric 
170391bc56edSDimitry Andric   bool Carry = (Value & 0x00FFFFFF);
170491bc56edSDimitry Andric   Value = ((Value & 0xFF000000) >> 24) + Carry;
170591bc56edSDimitry Andric 
170691bc56edSDimitry Andric   if (Value & 0x0000100)
170791bc56edSDimitry Andric       Value = Value & 0x000001FC;
170891bc56edSDimitry Andric 
170991bc56edSDimitry Andric   if (Shifted > 24)
171091bc56edSDimitry Andric       Value = Value >> (Shifted - 24);
171191bc56edSDimitry Andric   else
171291bc56edSDimitry Andric       Value = Value << (24 - Shifted);
171391bc56edSDimitry Andric 
171491bc56edSDimitry Andric   return Value;
171591bc56edSDimitry Andric }
171691bc56edSDimitry Andric 
171791bc56edSDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual
171891bc56edSDimitry Andric // stack limit.
171991bc56edSDimitry Andric static const uint64_t kSplitStackAvailable = 256;
172091bc56edSDimitry Andric 
172191bc56edSDimitry Andric // Adjust the function prologue to enable split stacks. This currently only
172291bc56edSDimitry Andric // supports android and linux.
172391bc56edSDimitry Andric //
172491bc56edSDimitry Andric // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
172591bc56edSDimitry Andric // must be well defined in order to allow for consistent implementations of the
172691bc56edSDimitry Andric // __morestack helper function. The ABI is also not a normal ABI in that it
172791bc56edSDimitry Andric // doesn't follow the normal calling conventions because this allows the
172891bc56edSDimitry Andric // prologue of each function to be optimized further.
172991bc56edSDimitry Andric //
173091bc56edSDimitry Andric // Currently, the ABI looks like (when calling __morestack)
173191bc56edSDimitry Andric //
173291bc56edSDimitry Andric //  * r4 holds the minimum stack size requested for this function call
173391bc56edSDimitry Andric //  * r5 holds the stack size of the arguments to the function
173491bc56edSDimitry Andric //  * the beginning of the function is 3 instructions after the call to
173591bc56edSDimitry Andric //    __morestack
173691bc56edSDimitry Andric //
173791bc56edSDimitry Andric // Implementations of __morestack should use r4 to allocate a new stack, r5 to
173891bc56edSDimitry Andric // place the arguments on to the new stack, and the 3-instruction knowledge to
173991bc56edSDimitry Andric // jump directly to the body of the function when working on the new stack.
174091bc56edSDimitry Andric //
174191bc56edSDimitry Andric // An old (and possibly no longer compatible) implementation of __morestack for
174291bc56edSDimitry Andric // ARM can be found at [1].
174391bc56edSDimitry Andric //
174491bc56edSDimitry Andric // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
174591bc56edSDimitry Andric void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
174691bc56edSDimitry Andric   unsigned Opcode;
174791bc56edSDimitry Andric   unsigned CFIIndex;
174891bc56edSDimitry Andric   const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
174991bc56edSDimitry Andric   bool Thumb = ST->isThumb();
175091bc56edSDimitry Andric 
175191bc56edSDimitry Andric   // Sadly, this currently doesn't support varargs, platforms other than
175291bc56edSDimitry Andric   // android/linux. Note that thumb1/thumb2 are support for android/linux.
175391bc56edSDimitry Andric   if (MF.getFunction()->isVarArg())
175491bc56edSDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
175591bc56edSDimitry Andric   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
175691bc56edSDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
175791bc56edSDimitry Andric 
175891bc56edSDimitry Andric   MachineBasicBlock &prologueMBB = MF.front();
175991bc56edSDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
176091bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
176191bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
176291bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
176391bc56edSDimitry Andric   const ARMBaseInstrInfo &TII =
176491bc56edSDimitry Andric       *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
176591bc56edSDimitry Andric   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
176691bc56edSDimitry Andric   DebugLoc DL;
176791bc56edSDimitry Andric 
176891bc56edSDimitry Andric   uint64_t StackSize = MFI->getStackSize();
176991bc56edSDimitry Andric 
177091bc56edSDimitry Andric   // Do not generate a prologue for functions with a stack of size zero
177191bc56edSDimitry Andric   if (StackSize == 0)
177291bc56edSDimitry Andric     return;
177391bc56edSDimitry Andric 
177491bc56edSDimitry Andric   // Use R4 and R5 as scratch registers.
177591bc56edSDimitry Andric   // We save R4 and R5 before use and restore them before leaving the function.
177691bc56edSDimitry Andric   unsigned ScratchReg0 = ARM::R4;
177791bc56edSDimitry Andric   unsigned ScratchReg1 = ARM::R5;
177891bc56edSDimitry Andric   uint64_t AlignedStackSize;
177991bc56edSDimitry Andric 
178091bc56edSDimitry Andric   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
178191bc56edSDimitry Andric   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
178291bc56edSDimitry Andric   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
178391bc56edSDimitry Andric   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
178491bc56edSDimitry Andric   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
178591bc56edSDimitry Andric 
178691bc56edSDimitry Andric   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
178791bc56edSDimitry Andric                                           e = prologueMBB.livein_end();
178891bc56edSDimitry Andric        i != e; ++i) {
178991bc56edSDimitry Andric     AllocMBB->addLiveIn(*i);
179091bc56edSDimitry Andric     GetMBB->addLiveIn(*i);
179191bc56edSDimitry Andric     McrMBB->addLiveIn(*i);
179291bc56edSDimitry Andric     PrevStackMBB->addLiveIn(*i);
179391bc56edSDimitry Andric     PostStackMBB->addLiveIn(*i);
179491bc56edSDimitry Andric   }
179591bc56edSDimitry Andric 
179691bc56edSDimitry Andric   MF.push_front(PostStackMBB);
179791bc56edSDimitry Andric   MF.push_front(AllocMBB);
179891bc56edSDimitry Andric   MF.push_front(GetMBB);
179991bc56edSDimitry Andric   MF.push_front(McrMBB);
180091bc56edSDimitry Andric   MF.push_front(PrevStackMBB);
180191bc56edSDimitry Andric 
180291bc56edSDimitry Andric   // The required stack size that is aligned to ARM constant criterion.
180391bc56edSDimitry Andric   AlignedStackSize = alignToARMConstant(StackSize);
180491bc56edSDimitry Andric 
180591bc56edSDimitry Andric   // When the frame size is less than 256 we just compare the stack
180691bc56edSDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
180791bc56edSDimitry Andric   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
180891bc56edSDimitry Andric 
180991bc56edSDimitry Andric   // We will use two of the callee save registers as scratch registers so we
181091bc56edSDimitry Andric   // need to save those registers onto the stack.
181191bc56edSDimitry Andric   // We will use SR0 to hold stack limit and SR1 to hold the stack size
181291bc56edSDimitry Andric   // requested and arguments for __morestack().
181391bc56edSDimitry Andric   // SR0: Scratch Register #0
181491bc56edSDimitry Andric   // SR1: Scratch Register #1
181591bc56edSDimitry Andric   // push {SR0, SR1}
181691bc56edSDimitry Andric   if (Thumb) {
181791bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
181891bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
181991bc56edSDimitry Andric   } else {
182091bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
182191bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
182291bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
182391bc56edSDimitry Andric   }
182491bc56edSDimitry Andric 
182591bc56edSDimitry Andric   // Emit the relevant DWARF information about the change in stack pointer as
182691bc56edSDimitry Andric   // well as where to find both r4 and r5 (the callee-save registers)
182791bc56edSDimitry Andric   CFIIndex =
182891bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
182991bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
183091bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
183191bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
183291bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
183391bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
183491bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
183591bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
183691bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
183791bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
183891bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
183991bc56edSDimitry Andric 
184091bc56edSDimitry Andric   // mov SR1, sp
184191bc56edSDimitry Andric   if (Thumb) {
184291bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
184391bc56edSDimitry Andric                       .addReg(ARM::SP));
184491bc56edSDimitry Andric   } else if (CompareStackPointer) {
184591bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
184691bc56edSDimitry Andric                       .addReg(ARM::SP)).addReg(0);
184791bc56edSDimitry Andric   }
184891bc56edSDimitry Andric 
184991bc56edSDimitry Andric   // sub SR1, sp, #StackSize
185091bc56edSDimitry Andric   if (!CompareStackPointer && Thumb) {
185191bc56edSDimitry Andric     AddDefaultPred(
185291bc56edSDimitry Andric         AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
185391bc56edSDimitry Andric             .addReg(ScratchReg1).addImm(AlignedStackSize));
185491bc56edSDimitry Andric   } else if (!CompareStackPointer) {
185591bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
185691bc56edSDimitry Andric                       .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
185791bc56edSDimitry Andric   }
185891bc56edSDimitry Andric 
185991bc56edSDimitry Andric   if (Thumb && ST->isThumb1Only()) {
186091bc56edSDimitry Andric     unsigned PCLabelId = ARMFI->createPICLabelUId();
186191bc56edSDimitry Andric     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
186291bc56edSDimitry Andric         MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
186391bc56edSDimitry Andric     MachineConstantPool *MCP = MF.getConstantPool();
186491bc56edSDimitry Andric     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
186591bc56edSDimitry Andric 
186691bc56edSDimitry Andric     // ldr SR0, [pc, offset(STACK_LIMIT)]
186791bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
186891bc56edSDimitry Andric                       .addConstantPoolIndex(CPI));
186991bc56edSDimitry Andric 
187091bc56edSDimitry Andric     // ldr SR0, [SR0]
187191bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
187291bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(0));
187391bc56edSDimitry Andric   } else {
187491bc56edSDimitry Andric     // Get TLS base address from the coprocessor
187591bc56edSDimitry Andric     // mrc p15, #0, SR0, c13, c0, #3
187691bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
187791bc56edSDimitry Andric                      .addImm(15)
187891bc56edSDimitry Andric                      .addImm(0)
187991bc56edSDimitry Andric                      .addImm(13)
188091bc56edSDimitry Andric                      .addImm(0)
188191bc56edSDimitry Andric                      .addImm(3));
188291bc56edSDimitry Andric 
188391bc56edSDimitry Andric     // Use the last tls slot on android and a private field of the TCP on linux.
188491bc56edSDimitry Andric     assert(ST->isTargetAndroid() || ST->isTargetLinux());
188591bc56edSDimitry Andric     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
188691bc56edSDimitry Andric 
188791bc56edSDimitry Andric     // Get the stack limit from the right offset
188891bc56edSDimitry Andric     // ldr SR0, [sr0, #4 * TlsOffset]
188991bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
189091bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(4 * TlsOffset));
189191bc56edSDimitry Andric   }
189291bc56edSDimitry Andric 
189391bc56edSDimitry Andric   // Compare stack limit with stack size requested.
189491bc56edSDimitry Andric   // cmp SR0, SR1
189591bc56edSDimitry Andric   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
189691bc56edSDimitry Andric   AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
189791bc56edSDimitry Andric                     .addReg(ScratchReg0)
189891bc56edSDimitry Andric                     .addReg(ScratchReg1));
189991bc56edSDimitry Andric 
190091bc56edSDimitry Andric   // This jump is taken if StackLimit < SP - stack required.
190191bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
190291bc56edSDimitry Andric   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
190391bc56edSDimitry Andric        .addImm(ARMCC::LO)
190491bc56edSDimitry Andric        .addReg(ARM::CPSR);
190591bc56edSDimitry Andric 
190691bc56edSDimitry Andric 
190791bc56edSDimitry Andric   // Calling __morestack(StackSize, Size of stack arguments).
190891bc56edSDimitry Andric   // __morestack knows that the stack size requested is in SR0(r4)
190991bc56edSDimitry Andric   // and amount size of stack arguments is in SR1(r5).
191091bc56edSDimitry Andric 
191191bc56edSDimitry Andric   // Pass first argument for the __morestack by Scratch Register #0.
191291bc56edSDimitry Andric   //   The amount size of stack required
191391bc56edSDimitry Andric   if (Thumb) {
191491bc56edSDimitry Andric     AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
191591bc56edSDimitry Andric                                         ScratchReg0)).addImm(AlignedStackSize));
191691bc56edSDimitry Andric   } else {
191791bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
191891bc56edSDimitry Andric                       .addImm(AlignedStackSize)).addReg(0);
191991bc56edSDimitry Andric   }
192091bc56edSDimitry Andric   // Pass second argument for the __morestack by Scratch Register #1.
192191bc56edSDimitry Andric   //   The amount size of stack consumed to save function arguments.
192291bc56edSDimitry Andric   if (Thumb) {
192391bc56edSDimitry Andric     AddDefaultPred(
192491bc56edSDimitry Andric         AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
192591bc56edSDimitry Andric             .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
192691bc56edSDimitry Andric   } else {
192791bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
192891bc56edSDimitry Andric                    .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
192991bc56edSDimitry Andric                    .addReg(0);
193091bc56edSDimitry Andric   }
193191bc56edSDimitry Andric 
193291bc56edSDimitry Andric   // push {lr} - Save return address of this function.
193391bc56edSDimitry Andric   if (Thumb) {
193491bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
193591bc56edSDimitry Andric         .addReg(ARM::LR);
193691bc56edSDimitry Andric   } else {
193791bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
193891bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
193991bc56edSDimitry Andric                    .addReg(ARM::SP))
194091bc56edSDimitry Andric         .addReg(ARM::LR);
194191bc56edSDimitry Andric   }
194291bc56edSDimitry Andric 
194391bc56edSDimitry Andric   // Emit the DWARF info about the change in stack as well as where to find the
194491bc56edSDimitry Andric   // previous link register
194591bc56edSDimitry Andric   CFIIndex =
194691bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
194791bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
194891bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
194991bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
195091bc56edSDimitry Andric         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
195191bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
195291bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
195391bc56edSDimitry Andric 
195491bc56edSDimitry Andric   // Call __morestack().
195591bc56edSDimitry Andric   if (Thumb) {
195691bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
195791bc56edSDimitry Andric         .addExternalSymbol("__morestack");
195891bc56edSDimitry Andric   } else {
195991bc56edSDimitry Andric     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
196091bc56edSDimitry Andric         .addExternalSymbol("__morestack");
196191bc56edSDimitry Andric   }
196291bc56edSDimitry Andric 
196391bc56edSDimitry Andric   // pop {lr} - Restore return address of this original function.
196491bc56edSDimitry Andric   if (Thumb) {
196591bc56edSDimitry Andric     if (ST->isThumb1Only()) {
196691bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
196791bc56edSDimitry Andric                      .addReg(ScratchReg0);
196891bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
196991bc56edSDimitry Andric                      .addReg(ScratchReg0));
197091bc56edSDimitry Andric     } else {
197191bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
197291bc56edSDimitry Andric                      .addReg(ARM::LR, RegState::Define)
197391bc56edSDimitry Andric                      .addReg(ARM::SP, RegState::Define)
197491bc56edSDimitry Andric                      .addReg(ARM::SP)
197591bc56edSDimitry Andric                      .addImm(4));
197691bc56edSDimitry Andric     }
197791bc56edSDimitry Andric   } else {
197891bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
197991bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
198091bc56edSDimitry Andric                    .addReg(ARM::SP))
198191bc56edSDimitry Andric       .addReg(ARM::LR);
198291bc56edSDimitry Andric   }
198391bc56edSDimitry Andric 
198491bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was called.
198591bc56edSDimitry Andric   // __morestack() will skip PostStackMBB block so we need to restore
198691bc56edSDimitry Andric   // scratch registers from here.
198791bc56edSDimitry Andric   // pop {SR0, SR1}
198891bc56edSDimitry Andric   if (Thumb) {
198991bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
199091bc56edSDimitry Andric       .addReg(ScratchReg0)
199191bc56edSDimitry Andric       .addReg(ScratchReg1);
199291bc56edSDimitry Andric   } else {
199391bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
199491bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
199591bc56edSDimitry Andric                    .addReg(ARM::SP))
199691bc56edSDimitry Andric       .addReg(ScratchReg0)
199791bc56edSDimitry Andric       .addReg(ScratchReg1);
199891bc56edSDimitry Andric   }
199991bc56edSDimitry Andric 
200091bc56edSDimitry Andric   // Update the CFA offset now that we've popped
200191bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
200291bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
200391bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
200491bc56edSDimitry Andric 
200591bc56edSDimitry Andric   // bx lr - Return from this function.
200691bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
200791bc56edSDimitry Andric   AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
200891bc56edSDimitry Andric 
200991bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was not called.
201091bc56edSDimitry Andric   // pop {SR0, SR1}
201191bc56edSDimitry Andric   if (Thumb) {
201291bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
201391bc56edSDimitry Andric       .addReg(ScratchReg0)
201491bc56edSDimitry Andric       .addReg(ScratchReg1);
201591bc56edSDimitry Andric   } else {
201691bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
201791bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
201891bc56edSDimitry Andric                    .addReg(ARM::SP))
201991bc56edSDimitry Andric       .addReg(ScratchReg0)
202091bc56edSDimitry Andric       .addReg(ScratchReg1);
202191bc56edSDimitry Andric   }
202291bc56edSDimitry Andric 
202391bc56edSDimitry Andric   // Update the CFA offset now that we've popped
202491bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
202591bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
202691bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
202791bc56edSDimitry Andric 
202891bc56edSDimitry Andric   // Tell debuggers that r4 and r5 are now the same as they were in the
202991bc56edSDimitry Andric   // previous function, that they're the "Same Value".
203091bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
203191bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
203291bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
203391bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
203491bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
203591bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
203691bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
203791bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
203891bc56edSDimitry Andric 
203991bc56edSDimitry Andric   // Organizing MBB lists
204091bc56edSDimitry Andric   PostStackMBB->addSuccessor(&prologueMBB);
204191bc56edSDimitry Andric 
204291bc56edSDimitry Andric   AllocMBB->addSuccessor(PostStackMBB);
204391bc56edSDimitry Andric 
204491bc56edSDimitry Andric   GetMBB->addSuccessor(PostStackMBB);
204591bc56edSDimitry Andric   GetMBB->addSuccessor(AllocMBB);
204691bc56edSDimitry Andric 
204791bc56edSDimitry Andric   McrMBB->addSuccessor(GetMBB);
204891bc56edSDimitry Andric 
204991bc56edSDimitry Andric   PrevStackMBB->addSuccessor(McrMBB);
205091bc56edSDimitry Andric 
205191bc56edSDimitry Andric #ifdef XDEBUG
205291bc56edSDimitry Andric   MF.verify();
205391bc56edSDimitry Andric #endif
205491bc56edSDimitry Andric }
2055