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"
267d523365SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
27139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
28139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
2991bc56edSDimitry Andric #include "llvm/MC/MCContext.h"
30dff0c46cSDimitry Andric #include "llvm/Support/CommandLine.h"
31139f7f9bSDimitry Andric #include "llvm/Target/TargetOptions.h"
322754fe60SDimitry Andric 
332754fe60SDimitry Andric using namespace llvm;
342754fe60SDimitry Andric 
35dff0c46cSDimitry Andric static cl::opt<bool>
36dff0c46cSDimitry Andric SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
37dff0c46cSDimitry Andric                      cl::desc("Align ARM NEON spills in prolog and epilog"));
38dff0c46cSDimitry Andric 
39dff0c46cSDimitry Andric static MachineBasicBlock::iterator
40dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
41dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs);
42dff0c46cSDimitry Andric 
4391bc56edSDimitry Andric ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
4491bc56edSDimitry Andric     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
4591bc56edSDimitry Andric       STI(sti) {}
4691bc56edSDimitry Andric 
47ff0cc061SDimitry Andric bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
48ff0cc061SDimitry Andric   // iOS always has a FP for backtracking, force other targets to keep their FP
49ff0cc061SDimitry Andric   // when doing FastISel. The emitted code is currently superior, and in cases
50ff0cc061SDimitry Andric   // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
51ff0cc061SDimitry Andric   return TargetFrameLowering::noFramePointerElim(MF) ||
52ff0cc061SDimitry Andric          MF.getSubtarget<ARMSubtarget>().useFastISel();
53ff0cc061SDimitry Andric }
54ff0cc061SDimitry Andric 
552754fe60SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
562754fe60SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
572754fe60SDimitry Andric /// or if frame pointer elimination is disabled.
582754fe60SDimitry Andric bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
5939d628a0SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
602754fe60SDimitry Andric 
61dff0c46cSDimitry Andric   // iOS requires FP not to be clobbered for backtracing purpose.
627d523365SDimitry Andric   if (STI.isTargetIOS() || STI.isTargetWatchOS())
632754fe60SDimitry Andric     return true;
642754fe60SDimitry Andric 
652754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
662754fe60SDimitry Andric   // Always eliminate non-leaf frame pointers.
67dff0c46cSDimitry Andric   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
68dff0c46cSDimitry Andric            MFI->hasCalls()) ||
692754fe60SDimitry Andric           RegInfo->needsStackRealignment(MF) ||
702754fe60SDimitry Andric           MFI->hasVarSizedObjects() ||
712754fe60SDimitry Andric           MFI->isFrameAddressTaken());
722754fe60SDimitry Andric }
732754fe60SDimitry Andric 
742754fe60SDimitry Andric /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
752754fe60SDimitry Andric /// not required, we reserve argument space for call sites in the function
762754fe60SDimitry Andric /// immediately on entry to the current function.  This eliminates the need for
772754fe60SDimitry Andric /// add/sub sp brackets around call sites.  Returns true if the call frame is
782754fe60SDimitry Andric /// included as part of the stack frame.
792754fe60SDimitry Andric bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
802754fe60SDimitry Andric   const MachineFrameInfo *FFI = MF.getFrameInfo();
812754fe60SDimitry Andric   unsigned CFSize = FFI->getMaxCallFrameSize();
822754fe60SDimitry Andric   // It's not always a good idea to include the call frame as part of the
832754fe60SDimitry Andric   // stack frame. ARM (especially Thumb) has small immediate offset to
842754fe60SDimitry Andric   // address the stack frame. So a large call frame can cause poor codegen
852754fe60SDimitry Andric   // and may even makes it impossible to scavenge a register.
862754fe60SDimitry Andric   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
872754fe60SDimitry Andric     return false;
882754fe60SDimitry Andric 
892754fe60SDimitry Andric   return !MF.getFrameInfo()->hasVarSizedObjects();
902754fe60SDimitry Andric }
912754fe60SDimitry Andric 
922754fe60SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
932754fe60SDimitry Andric /// call frame pseudos can be simplified.  Unlike most targets, having a FP
942754fe60SDimitry Andric /// is not sufficient here since we still may reference some objects via SP
952754fe60SDimitry Andric /// even when FP is available in Thumb2 mode.
962754fe60SDimitry Andric bool
972754fe60SDimitry Andric ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
982754fe60SDimitry Andric   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
992754fe60SDimitry Andric }
1002754fe60SDimitry Andric 
1013ca95b02SDimitry Andric static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
10291bc56edSDimitry Andric                         const MCPhysReg *CSRegs) {
1032754fe60SDimitry Andric   // Integer spill area is handled with "pop".
1043ca95b02SDimitry Andric   if (isPopOpcode(MI.getOpcode())) {
1052754fe60SDimitry Andric     // The first two operands are predicates. The last two are
1062754fe60SDimitry Andric     // imp-def and imp-use of SP. Check everything in between.
1073ca95b02SDimitry Andric     for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
1083ca95b02SDimitry Andric       if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
1092754fe60SDimitry Andric         return false;
1102754fe60SDimitry Andric     return true;
1112754fe60SDimitry Andric   }
1123ca95b02SDimitry Andric   if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
1133ca95b02SDimitry Andric        MI.getOpcode() == ARM::LDR_POST_REG ||
1143ca95b02SDimitry Andric        MI.getOpcode() == ARM::t2LDR_POST) &&
1153ca95b02SDimitry Andric       isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
1163ca95b02SDimitry Andric       MI.getOperand(1).getReg() == ARM::SP)
1172754fe60SDimitry Andric     return true;
1182754fe60SDimitry Andric 
1192754fe60SDimitry Andric   return false;
1202754fe60SDimitry Andric }
1212754fe60SDimitry Andric 
1223ca95b02SDimitry Andric static void emitRegPlusImmediate(
1233ca95b02SDimitry Andric     bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1243ca95b02SDimitry Andric     const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
1253ca95b02SDimitry Andric     unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
1263ca95b02SDimitry Andric     ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1272754fe60SDimitry Andric   if (isARM)
128f785676fSDimitry Andric     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
129139f7f9bSDimitry Andric                             Pred, PredReg, TII, MIFlags);
1302754fe60SDimitry Andric   else
131f785676fSDimitry Andric     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
132139f7f9bSDimitry Andric                            Pred, PredReg, TII, MIFlags);
1332754fe60SDimitry Andric }
1342754fe60SDimitry Andric 
135f785676fSDimitry Andric static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
1363ca95b02SDimitry Andric                          MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
137f785676fSDimitry Andric                          const ARMBaseInstrInfo &TII, int NumBytes,
138f785676fSDimitry Andric                          unsigned MIFlags = MachineInstr::NoFlags,
139f785676fSDimitry Andric                          ARMCC::CondCodes Pred = ARMCC::AL,
140f785676fSDimitry Andric                          unsigned PredReg = 0) {
141f785676fSDimitry Andric   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
142f785676fSDimitry Andric                        MIFlags, Pred, PredReg);
143f785676fSDimitry Andric }
144f785676fSDimitry Andric 
1453ca95b02SDimitry Andric static int sizeOfSPAdjustment(const MachineInstr &MI) {
14639d628a0SDimitry Andric   int RegSize;
1473ca95b02SDimitry Andric   switch (MI.getOpcode()) {
14839d628a0SDimitry Andric   case ARM::VSTMDDB_UPD:
14939d628a0SDimitry Andric     RegSize = 8;
15039d628a0SDimitry Andric     break;
15139d628a0SDimitry Andric   case ARM::STMDB_UPD:
15239d628a0SDimitry Andric   case ARM::t2STMDB_UPD:
15339d628a0SDimitry Andric     RegSize = 4;
15439d628a0SDimitry Andric     break;
15539d628a0SDimitry Andric   case ARM::t2STR_PRE:
15639d628a0SDimitry Andric   case ARM::STR_PRE_IMM:
15739d628a0SDimitry Andric     return 4;
15839d628a0SDimitry Andric   default:
15939d628a0SDimitry Andric     llvm_unreachable("Unknown push or pop like instruction");
16039d628a0SDimitry Andric   }
16139d628a0SDimitry Andric 
16291bc56edSDimitry Andric   int count = 0;
16391bc56edSDimitry Andric   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
16491bc56edSDimitry Andric   // pred) so the list starts at 4.
1653ca95b02SDimitry Andric   for (int i = MI.getNumOperands() - 1; i >= 4; --i)
16639d628a0SDimitry Andric     count += RegSize;
16791bc56edSDimitry Andric   return count;
16891bc56edSDimitry Andric }
16991bc56edSDimitry Andric 
17091bc56edSDimitry Andric static bool WindowsRequiresStackProbe(const MachineFunction &MF,
17191bc56edSDimitry Andric                                       size_t StackSizeInBytes) {
17291bc56edSDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
173ff0cc061SDimitry Andric   const Function *F = MF.getFunction();
174ff0cc061SDimitry Andric   unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
175ff0cc061SDimitry Andric   if (F->hasFnAttribute("stack-probe-size"))
176ff0cc061SDimitry Andric     F->getFnAttribute("stack-probe-size")
177ff0cc061SDimitry Andric         .getValueAsString()
178ff0cc061SDimitry Andric         .getAsInteger(0, StackProbeSize);
179ff0cc061SDimitry Andric   return StackSizeInBytes >= StackProbeSize;
18091bc56edSDimitry Andric }
18191bc56edSDimitry Andric 
18239d628a0SDimitry Andric namespace {
18339d628a0SDimitry Andric struct StackAdjustingInsts {
18439d628a0SDimitry Andric   struct InstInfo {
18539d628a0SDimitry Andric     MachineBasicBlock::iterator I;
18639d628a0SDimitry Andric     unsigned SPAdjust;
18739d628a0SDimitry Andric     bool BeforeFPSet;
18839d628a0SDimitry Andric   };
18939d628a0SDimitry Andric 
19039d628a0SDimitry Andric   SmallVector<InstInfo, 4> Insts;
19139d628a0SDimitry Andric 
19239d628a0SDimitry Andric   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
19339d628a0SDimitry Andric                bool BeforeFPSet = false) {
19439d628a0SDimitry Andric     InstInfo Info = {I, SPAdjust, BeforeFPSet};
19539d628a0SDimitry Andric     Insts.push_back(Info);
19639d628a0SDimitry Andric   }
19739d628a0SDimitry Andric 
19839d628a0SDimitry Andric   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
19939d628a0SDimitry Andric     auto Info = std::find_if(Insts.begin(), Insts.end(),
20039d628a0SDimitry Andric                              [&](InstInfo &Info) { return Info.I == I; });
20139d628a0SDimitry Andric     assert(Info != Insts.end() && "invalid sp adjusting instruction");
20239d628a0SDimitry Andric     Info->SPAdjust += ExtraBytes;
20339d628a0SDimitry Andric   }
20439d628a0SDimitry Andric 
20539d628a0SDimitry Andric   void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
2063ca95b02SDimitry Andric                          const DebugLoc &dl, const ARMBaseInstrInfo &TII,
2073ca95b02SDimitry Andric                          bool HasFP) {
20839d628a0SDimitry Andric     unsigned CFAOffset = 0;
20939d628a0SDimitry Andric     for (auto &Info : Insts) {
21039d628a0SDimitry Andric       if (HasFP && !Info.BeforeFPSet)
21139d628a0SDimitry Andric         return;
21239d628a0SDimitry Andric 
21339d628a0SDimitry Andric       CFAOffset -= Info.SPAdjust;
21439d628a0SDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(
21539d628a0SDimitry Andric           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
21639d628a0SDimitry Andric       BuildMI(MBB, std::next(Info.I), dl,
21739d628a0SDimitry Andric               TII.get(TargetOpcode::CFI_INSTRUCTION))
21839d628a0SDimitry Andric               .addCFIIndex(CFIIndex)
21939d628a0SDimitry Andric               .setMIFlags(MachineInstr::FrameSetup);
22039d628a0SDimitry Andric     }
22139d628a0SDimitry Andric   }
22239d628a0SDimitry Andric };
2233dac3a9bSDimitry Andric }
22439d628a0SDimitry Andric 
22539d628a0SDimitry Andric /// Emit an instruction sequence that will align the address in
22639d628a0SDimitry Andric /// register Reg by zero-ing out the lower bits.  For versions of the
22739d628a0SDimitry Andric /// architecture that support Neon, this must be done in a single
22839d628a0SDimitry Andric /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
22939d628a0SDimitry Andric /// single instruction. That function only gets called when optimizing
23039d628a0SDimitry Andric /// spilling of D registers on a core with the Neon instruction set
23139d628a0SDimitry Andric /// present.
23239d628a0SDimitry Andric static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
23339d628a0SDimitry Andric                                      const TargetInstrInfo &TII,
23439d628a0SDimitry Andric                                      MachineBasicBlock &MBB,
23539d628a0SDimitry Andric                                      MachineBasicBlock::iterator MBBI,
2363ca95b02SDimitry Andric                                      const DebugLoc &DL, const unsigned Reg,
23739d628a0SDimitry Andric                                      const unsigned Alignment,
23839d628a0SDimitry Andric                                      const bool MustBeSingleInstruction) {
239ff0cc061SDimitry Andric   const ARMSubtarget &AST =
240ff0cc061SDimitry Andric       static_cast<const ARMSubtarget &>(MF.getSubtarget());
24139d628a0SDimitry Andric   const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
24239d628a0SDimitry Andric   const unsigned AlignMask = Alignment - 1;
24339d628a0SDimitry Andric   const unsigned NrBitsToZero = countTrailingZeros(Alignment);
24439d628a0SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
24539d628a0SDimitry Andric   if (!AFI->isThumbFunction()) {
24639d628a0SDimitry Andric     // if the BFC instruction is available, use that to zero the lower
24739d628a0SDimitry Andric     // bits:
24839d628a0SDimitry Andric     //   bfc Reg, #0, log2(Alignment)
24939d628a0SDimitry Andric     // otherwise use BIC, if the mask to zero the required number of bits
25039d628a0SDimitry Andric     // can be encoded in the bic immediate field
25139d628a0SDimitry Andric     //   bic Reg, Reg, Alignment-1
25239d628a0SDimitry Andric     // otherwise, emit
25339d628a0SDimitry Andric     //   lsr Reg, Reg, log2(Alignment)
25439d628a0SDimitry Andric     //   lsl Reg, Reg, log2(Alignment)
25539d628a0SDimitry Andric     if (CanUseBFC) {
25639d628a0SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
25739d628a0SDimitry Andric                          .addReg(Reg, RegState::Kill)
25839d628a0SDimitry Andric                          .addImm(~AlignMask));
25939d628a0SDimitry Andric     } else if (AlignMask <= 255) {
26039d628a0SDimitry Andric       AddDefaultCC(
26139d628a0SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
26239d628a0SDimitry Andric                              .addReg(Reg, RegState::Kill)
26339d628a0SDimitry Andric                              .addImm(AlignMask)));
26439d628a0SDimitry Andric     } else {
26539d628a0SDimitry Andric       assert(!MustBeSingleInstruction &&
26639d628a0SDimitry Andric              "Shouldn't call emitAligningInstructions demanding a single "
26739d628a0SDimitry Andric              "instruction to be emitted for large stack alignment for a target "
26839d628a0SDimitry Andric              "without BFC.");
26939d628a0SDimitry Andric       AddDefaultCC(AddDefaultPred(
27039d628a0SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
27139d628a0SDimitry Andric               .addReg(Reg, RegState::Kill)
27239d628a0SDimitry Andric               .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
27339d628a0SDimitry Andric       AddDefaultCC(AddDefaultPred(
27439d628a0SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
27539d628a0SDimitry Andric               .addReg(Reg, RegState::Kill)
27639d628a0SDimitry Andric               .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
27739d628a0SDimitry Andric     }
27839d628a0SDimitry Andric   } else {
27939d628a0SDimitry Andric     // Since this is only reached for Thumb-2 targets, the BFC instruction
28039d628a0SDimitry Andric     // should always be available.
28139d628a0SDimitry Andric     assert(CanUseBFC);
28239d628a0SDimitry Andric     AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
28339d628a0SDimitry Andric                        .addReg(Reg, RegState::Kill)
28439d628a0SDimitry Andric                        .addImm(~AlignMask));
28539d628a0SDimitry Andric   }
28639d628a0SDimitry Andric }
28739d628a0SDimitry Andric 
288ff0cc061SDimitry Andric void ARMFrameLowering::emitPrologue(MachineFunction &MF,
289ff0cc061SDimitry Andric                                     MachineBasicBlock &MBB) const {
2902754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
2912754fe60SDimitry Andric   MachineFrameInfo  *MFI = MF.getFrameInfo();
2922754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
29391bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
29491bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
29591bc56edSDimitry Andric   const TargetMachine &TM = MF.getTarget();
29691bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
297ff0cc061SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
298ff0cc061SDimitry Andric   const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
2992754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
3002754fe60SDimitry Andric          "This emitPrologue does not support Thumb1!");
3012754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
302ff0cc061SDimitry Andric   unsigned Align = STI.getFrameLowering()->getStackAlignment();
303ff0cc061SDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
3042754fe60SDimitry Andric   unsigned NumBytes = MFI->getStackSize();
3052754fe60SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
3067d523365SDimitry Andric 
3077d523365SDimitry Andric   // Debug location must be unknown since the first debug location is used
3087d523365SDimitry Andric   // to determine the end of the prologue.
3097d523365SDimitry Andric   DebugLoc dl;
3107d523365SDimitry Andric 
3112754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
3122754fe60SDimitry Andric 
3132754fe60SDimitry Andric   // Determine the sizes of each callee-save spill areas and record which frame
3142754fe60SDimitry Andric   // belongs to which callee-save spill areas.
3152754fe60SDimitry Andric   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
3162754fe60SDimitry Andric   int FramePtrSpillFI = 0;
317dff0c46cSDimitry Andric   int D8SpillFI = 0;
318f8254f43SDimitry Andric 
3193861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
3203861d79fSDimitry Andric   // prologue/epilogue.
3217ae0e2c9SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
3227ae0e2c9SDimitry Andric     return;
3237ae0e2c9SDimitry Andric 
32439d628a0SDimitry Andric   StackAdjustingInsts DefCFAOffsetCandidates;
325ff0cc061SDimitry Andric   bool HasFP = hasFP(MF);
32639d628a0SDimitry Andric 
32791bc56edSDimitry Andric   // Allocate the vararg register save area.
32891bc56edSDimitry Andric   if (ArgRegsSaveSize) {
329284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
3303b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
33139d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
33291bc56edSDimitry Andric   }
3332754fe60SDimitry Andric 
33491bc56edSDimitry Andric   if (!AFI->hasStackFrame() &&
33591bc56edSDimitry Andric       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
33691bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0) {
33791bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
3383b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
33939d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
34039d628a0SDimitry Andric                                      NumBytes - ArgRegsSaveSize, true);
34191bc56edSDimitry Andric     }
342ff0cc061SDimitry Andric     DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
3432754fe60SDimitry Andric     return;
3442754fe60SDimitry Andric   }
3452754fe60SDimitry Andric 
34691bc56edSDimitry Andric   // Determine spill area sizes.
3472754fe60SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
3482754fe60SDimitry Andric     unsigned Reg = CSI[i].getReg();
3492754fe60SDimitry Andric     int FI = CSI[i].getFrameIdx();
3502754fe60SDimitry Andric     switch (Reg) {
35191bc56edSDimitry Andric     case ARM::R8:
35291bc56edSDimitry Andric     case ARM::R9:
35391bc56edSDimitry Andric     case ARM::R10:
35491bc56edSDimitry Andric     case ARM::R11:
35591bc56edSDimitry Andric     case ARM::R12:
3563ca95b02SDimitry Andric       if (STI.splitFramePushPop()) {
35791bc56edSDimitry Andric         GPRCS2Size += 4;
35891bc56edSDimitry Andric         break;
35991bc56edSDimitry Andric       }
36091bc56edSDimitry Andric       // fallthrough
361f785676fSDimitry Andric     case ARM::R0:
362f785676fSDimitry Andric     case ARM::R1:
363f785676fSDimitry Andric     case ARM::R2:
364f785676fSDimitry Andric     case ARM::R3:
3652754fe60SDimitry Andric     case ARM::R4:
3662754fe60SDimitry Andric     case ARM::R5:
3672754fe60SDimitry Andric     case ARM::R6:
3682754fe60SDimitry Andric     case ARM::R7:
3692754fe60SDimitry Andric     case ARM::LR:
3702754fe60SDimitry Andric       if (Reg == FramePtr)
3712754fe60SDimitry Andric         FramePtrSpillFI = FI;
3722754fe60SDimitry Andric       GPRCS1Size += 4;
3732754fe60SDimitry Andric       break;
3742754fe60SDimitry Andric     default:
375dff0c46cSDimitry Andric       // This is a DPR. Exclude the aligned DPRCS2 spills.
376dff0c46cSDimitry Andric       if (Reg == ARM::D8)
377dff0c46cSDimitry Andric         D8SpillFI = FI;
378f785676fSDimitry Andric       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
3792754fe60SDimitry Andric         DPRCSSize += 8;
3802754fe60SDimitry Andric     }
3812754fe60SDimitry Andric   }
3822754fe60SDimitry Andric 
3832754fe60SDimitry Andric   // Move past area 1.
38439d628a0SDimitry Andric   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
38539d628a0SDimitry Andric   if (GPRCS1Size > 0) {
38691bc56edSDimitry Andric     GPRCS1Push = LastPush = MBBI++;
38739d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
38839d628a0SDimitry Andric   }
3892754fe60SDimitry Andric 
3902754fe60SDimitry Andric   // Determine starting offsets of spill areas.
39139d628a0SDimitry Andric   unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
39239d628a0SDimitry Andric   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
39339d628a0SDimitry Andric   unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
39439d628a0SDimitry Andric   unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
39539d628a0SDimitry Andric   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
396f785676fSDimitry Andric   int FramePtrOffsetInPush = 0;
397f785676fSDimitry Andric   if (HasFP) {
39839d628a0SDimitry Andric     FramePtrOffsetInPush =
39939d628a0SDimitry Andric         MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
4002754fe60SDimitry Andric     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
4012754fe60SDimitry Andric                                 NumBytes);
402f785676fSDimitry Andric   }
4032754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
4042754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
4052754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
4062754fe60SDimitry Andric 
407f785676fSDimitry Andric   // Move past area 2.
40839d628a0SDimitry Andric   if (GPRCS2Size > 0) {
40991bc56edSDimitry Andric     GPRCS2Push = LastPush = MBBI++;
41039d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
41139d628a0SDimitry Andric   }
41239d628a0SDimitry Andric 
41339d628a0SDimitry Andric   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
41439d628a0SDimitry Andric   // .cfi_offset operations will reflect that.
41539d628a0SDimitry Andric   if (DPRGapSize) {
41639d628a0SDimitry Andric     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
4173ca95b02SDimitry Andric     if (tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
41839d628a0SDimitry Andric       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
41939d628a0SDimitry Andric     else {
42039d628a0SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
42139d628a0SDimitry Andric                    MachineInstr::FrameSetup);
42239d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
42339d628a0SDimitry Andric     }
42439d628a0SDimitry Andric   }
425f785676fSDimitry Andric 
4262754fe60SDimitry Andric   // Move past area 3.
427dd6029ffSDimitry Andric   if (DPRCSSize > 0) {
428dd6029ffSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
429dd6029ffSDimitry Andric     // instructions in the prologue.
43039d628a0SDimitry Andric     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
4313ca95b02SDimitry Andric       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
432f785676fSDimitry Andric       LastPush = MBBI++;
433dd6029ffSDimitry Andric     }
43439d628a0SDimitry Andric   }
4352754fe60SDimitry Andric 
436dff0c46cSDimitry Andric   // Move past the aligned DPRCS2 area.
437dff0c46cSDimitry Andric   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
438dff0c46cSDimitry Andric     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
439dff0c46cSDimitry Andric     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
440dff0c46cSDimitry Andric     // leaves the stack pointer pointing to the DPRCS2 area.
441dff0c46cSDimitry Andric     //
442dff0c46cSDimitry Andric     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
443dff0c46cSDimitry Andric     NumBytes += MFI->getObjectOffset(D8SpillFI);
444dff0c46cSDimitry Andric   } else
4452754fe60SDimitry Andric     NumBytes = DPRCSOffset;
446dff0c46cSDimitry Andric 
44791bc56edSDimitry Andric   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
44891bc56edSDimitry Andric     uint32_t NumWords = NumBytes >> 2;
44991bc56edSDimitry Andric 
45091bc56edSDimitry Andric     if (NumWords < 65536)
45191bc56edSDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
45291bc56edSDimitry Andric                      .addImm(NumWords)
45391bc56edSDimitry Andric                      .setMIFlags(MachineInstr::FrameSetup));
45491bc56edSDimitry Andric     else
45591bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
45691bc56edSDimitry Andric         .addImm(NumWords)
45791bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
45891bc56edSDimitry Andric 
45991bc56edSDimitry Andric     switch (TM.getCodeModel()) {
46091bc56edSDimitry Andric     case CodeModel::Small:
46191bc56edSDimitry Andric     case CodeModel::Medium:
46291bc56edSDimitry Andric     case CodeModel::Default:
46391bc56edSDimitry Andric     case CodeModel::Kernel:
46491bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
46591bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
46691bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
46791bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
46891bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
46991bc56edSDimitry Andric       break;
47091bc56edSDimitry Andric     case CodeModel::Large:
47191bc56edSDimitry Andric     case CodeModel::JITDefault:
47291bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
47391bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
47491bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
47591bc56edSDimitry Andric 
47691bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
47791bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
47891bc56edSDimitry Andric         .addReg(ARM::R12, RegState::Kill)
47991bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
48091bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
48191bc56edSDimitry Andric       break;
48291bc56edSDimitry Andric     }
48391bc56edSDimitry Andric 
48491bc56edSDimitry Andric     AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
48591bc56edSDimitry Andric                                         ARM::SP)
4863ca95b02SDimitry Andric                                 .addReg(ARM::SP, RegState::Kill)
48791bc56edSDimitry Andric                                 .addReg(ARM::R4, RegState::Kill)
48891bc56edSDimitry Andric                                 .setMIFlags(MachineInstr::FrameSetup)));
48991bc56edSDimitry Andric     NumBytes = 0;
49091bc56edSDimitry Andric   }
49191bc56edSDimitry Andric 
4922754fe60SDimitry Andric   if (NumBytes) {
4932754fe60SDimitry Andric     // Adjust SP after all the callee-save spills.
4947d523365SDimitry Andric     if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
4953ca95b02SDimitry Andric         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
49639d628a0SDimitry Andric       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
49739d628a0SDimitry Andric     else {
4983b0f4066SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
4993b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
50039d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
50139d628a0SDimitry Andric     }
502f785676fSDimitry Andric 
5032754fe60SDimitry Andric     if (HasFP && isARM)
5042754fe60SDimitry Andric       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
5052754fe60SDimitry Andric       // Note it's not safe to do this in Thumb2 mode because it would have
5062754fe60SDimitry Andric       // taken two instructions:
5072754fe60SDimitry Andric       // mov sp, r7
5082754fe60SDimitry Andric       // sub sp, #24
5092754fe60SDimitry Andric       // If an interrupt is taken between the two instructions, then sp is in
5102754fe60SDimitry Andric       // an inconsistent state (pointing to the middle of callee-saved area).
5112754fe60SDimitry Andric       // The interrupt handler can end up clobbering the registers.
5122754fe60SDimitry Andric       AFI->setShouldRestoreSPFromFP(true);
5132754fe60SDimitry Andric   }
5142754fe60SDimitry Andric 
51539d628a0SDimitry Andric   // Set FP to point to the stack slot that contains the previous FP.
51639d628a0SDimitry Andric   // For iOS, FP is R7, which has now been stored in spill area 1.
51739d628a0SDimitry Andric   // Otherwise, if this is not iOS, all the callee-saved registers go
51839d628a0SDimitry Andric   // into spill area 1, including the FP in R11.  In either case, it
51939d628a0SDimitry Andric   // is in area one and the adjustment needs to take place just after
52039d628a0SDimitry Andric   // that push.
52139d628a0SDimitry Andric   if (HasFP) {
52239d628a0SDimitry Andric     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
5233ca95b02SDimitry Andric     unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
52439d628a0SDimitry Andric     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
52539d628a0SDimitry Andric                          dl, TII, FramePtr, ARM::SP,
52639d628a0SDimitry Andric                          PushSize + FramePtrOffsetInPush,
52739d628a0SDimitry Andric                          MachineInstr::FrameSetup);
52839d628a0SDimitry Andric     if (FramePtrOffsetInPush + PushSize != 0) {
52939d628a0SDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
53039d628a0SDimitry Andric           nullptr, MRI->getDwarfRegNum(FramePtr, true),
53139d628a0SDimitry Andric           -(ArgRegsSaveSize - FramePtrOffsetInPush)));
53239d628a0SDimitry Andric       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
53339d628a0SDimitry Andric           .addCFIIndex(CFIIndex)
53439d628a0SDimitry Andric           .setMIFlags(MachineInstr::FrameSetup);
53539d628a0SDimitry Andric     } else {
53639d628a0SDimitry Andric       unsigned CFIIndex =
53739d628a0SDimitry Andric           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
53839d628a0SDimitry Andric               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
53939d628a0SDimitry Andric       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
54039d628a0SDimitry Andric           .addCFIIndex(CFIIndex)
54139d628a0SDimitry Andric           .setMIFlags(MachineInstr::FrameSetup);
54239d628a0SDimitry Andric     }
54339d628a0SDimitry Andric   }
54439d628a0SDimitry Andric 
54539d628a0SDimitry Andric   // Now that the prologue's actual instructions are finalised, we can insert
54639d628a0SDimitry Andric   // the necessary DWARF cf instructions to describe the situation. Start by
54739d628a0SDimitry Andric   // recording where each register ended up:
54839d628a0SDimitry Andric   if (GPRCS1Size > 0) {
54939d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
55039d628a0SDimitry Andric     int CFIIndex;
55191bc56edSDimitry Andric     for (const auto &Entry : CSI) {
55291bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
55391bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
55491bc56edSDimitry Andric       switch (Reg) {
55591bc56edSDimitry Andric       case ARM::R8:
55691bc56edSDimitry Andric       case ARM::R9:
55791bc56edSDimitry Andric       case ARM::R10:
55891bc56edSDimitry Andric       case ARM::R11:
55991bc56edSDimitry Andric       case ARM::R12:
5603ca95b02SDimitry Andric         if (STI.splitFramePushPop())
56191bc56edSDimitry Andric           break;
56291bc56edSDimitry Andric         // fallthrough
56391bc56edSDimitry Andric       case ARM::R0:
56491bc56edSDimitry Andric       case ARM::R1:
56591bc56edSDimitry Andric       case ARM::R2:
56691bc56edSDimitry Andric       case ARM::R3:
56791bc56edSDimitry Andric       case ARM::R4:
56891bc56edSDimitry Andric       case ARM::R5:
56991bc56edSDimitry Andric       case ARM::R6:
57091bc56edSDimitry Andric       case ARM::R7:
57191bc56edSDimitry Andric       case ARM::LR:
57291bc56edSDimitry Andric         CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
57391bc56edSDimitry Andric             nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
57491bc56edSDimitry Andric         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
57539d628a0SDimitry Andric             .addCFIIndex(CFIIndex)
57639d628a0SDimitry Andric             .setMIFlags(MachineInstr::FrameSetup);
57791bc56edSDimitry Andric         break;
57891bc56edSDimitry Andric       }
57991bc56edSDimitry Andric     }
58091bc56edSDimitry Andric   }
58191bc56edSDimitry Andric 
58291bc56edSDimitry Andric   if (GPRCS2Size > 0) {
58339d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
58491bc56edSDimitry Andric     for (const auto &Entry : CSI) {
58591bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
58691bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
58791bc56edSDimitry Andric       switch (Reg) {
58891bc56edSDimitry Andric       case ARM::R8:
58991bc56edSDimitry Andric       case ARM::R9:
59091bc56edSDimitry Andric       case ARM::R10:
59191bc56edSDimitry Andric       case ARM::R11:
59291bc56edSDimitry Andric       case ARM::R12:
5933ca95b02SDimitry Andric         if (STI.splitFramePushPop()) {
59491bc56edSDimitry Andric           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
59591bc56edSDimitry Andric           unsigned Offset = MFI->getObjectOffset(FI);
59691bc56edSDimitry Andric           unsigned CFIIndex = MMI.addFrameInst(
59791bc56edSDimitry Andric               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
59891bc56edSDimitry Andric           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
59939d628a0SDimitry Andric               .addCFIIndex(CFIIndex)
60039d628a0SDimitry Andric               .setMIFlags(MachineInstr::FrameSetup);
60191bc56edSDimitry Andric         }
60291bc56edSDimitry Andric         break;
60391bc56edSDimitry Andric       }
60491bc56edSDimitry Andric     }
60591bc56edSDimitry Andric   }
60691bc56edSDimitry Andric 
60791bc56edSDimitry Andric   if (DPRCSSize > 0) {
60891bc56edSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
60991bc56edSDimitry Andric     // instructions in the prologue.
61039d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(LastPush);
61191bc56edSDimitry Andric     for (const auto &Entry : CSI) {
61291bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
61391bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
61491bc56edSDimitry Andric       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
61591bc56edSDimitry Andric           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
61691bc56edSDimitry Andric         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
61791bc56edSDimitry Andric         unsigned Offset = MFI->getObjectOffset(FI);
61891bc56edSDimitry Andric         unsigned CFIIndex = MMI.addFrameInst(
61991bc56edSDimitry Andric             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
62039d628a0SDimitry Andric         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
62139d628a0SDimitry Andric             .addCFIIndex(CFIIndex)
62239d628a0SDimitry Andric             .setMIFlags(MachineInstr::FrameSetup);
62391bc56edSDimitry Andric       }
62491bc56edSDimitry Andric     }
62591bc56edSDimitry Andric   }
62691bc56edSDimitry Andric 
62739d628a0SDimitry Andric   // Now we can emit descriptions of where the canonical frame address was
62839d628a0SDimitry Andric   // throughout the process. If we have a frame pointer, it takes over the job
62939d628a0SDimitry Andric   // half-way through, so only the first few .cfi_def_cfa_offset instructions
63039d628a0SDimitry Andric   // actually get emitted.
63139d628a0SDimitry Andric   DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
632f785676fSDimitry Andric 
6332754fe60SDimitry Andric   if (STI.isTargetELF() && hasFP(MF))
6342754fe60SDimitry Andric     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
6352754fe60SDimitry Andric                              AFI->getFramePtrSpillOffset());
6362754fe60SDimitry Andric 
6372754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
6382754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
63939d628a0SDimitry Andric   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
6402754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
6412754fe60SDimitry Andric 
6422754fe60SDimitry Andric   // If we need dynamic stack realignment, do it here. Be paranoid and make
6432754fe60SDimitry Andric   // sure if we also have VLAs, we have a base pointer for frame access.
644dff0c46cSDimitry Andric   // If aligned NEON registers were spilled, the stack has already been
645dff0c46cSDimitry Andric   // realigned.
646dff0c46cSDimitry Andric   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
6472754fe60SDimitry Andric     unsigned MaxAlign = MFI->getMaxAlignment();
6482754fe60SDimitry Andric     assert(!AFI->isThumb1OnlyFunction());
6492754fe60SDimitry Andric     if (!AFI->isThumbFunction()) {
65039d628a0SDimitry Andric       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
65139d628a0SDimitry Andric                                false);
6522754fe60SDimitry Andric     } else {
65339d628a0SDimitry Andric       // We cannot use sp as source/dest register here, thus we're using r4 to
65439d628a0SDimitry Andric       // perform the calculations. We're emitting the following sequence:
6552754fe60SDimitry Andric       // mov r4, sp
65639d628a0SDimitry Andric       // -- use emitAligningInstructions to produce best sequence to zero
65739d628a0SDimitry Andric       // -- out lower bits in r4
6582754fe60SDimitry Andric       // mov sp, r4
6592754fe60SDimitry Andric       // FIXME: It will be better just to find spare register here.
66017a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
66117a519f9SDimitry Andric                          .addReg(ARM::SP, RegState::Kill));
66239d628a0SDimitry Andric       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
66339d628a0SDimitry Andric                                false);
66417a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
66517a519f9SDimitry Andric                          .addReg(ARM::R4, RegState::Kill));
6662754fe60SDimitry Andric     }
6672754fe60SDimitry Andric 
6682754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
6692754fe60SDimitry Andric   }
6702754fe60SDimitry Andric 
6712754fe60SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
6722754fe60SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
6732754fe60SDimitry Andric   // will be allocated after this, so we can still use the base pointer
6742754fe60SDimitry Andric   // to reference locals.
6753b0f4066SDimitry Andric   // FIXME: Clarify FrameSetup flags here.
6762754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
6772754fe60SDimitry Andric     if (isARM)
6782754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl,
6792754fe60SDimitry Andric               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
6802754fe60SDimitry Andric         .addReg(ARM::SP)
6812754fe60SDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6822754fe60SDimitry Andric     else
68317a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
68417a519f9SDimitry Andric                              RegInfo->getBaseRegister())
68517a519f9SDimitry Andric         .addReg(ARM::SP));
6862754fe60SDimitry Andric   }
6872754fe60SDimitry Andric 
6882754fe60SDimitry Andric   // If the frame has variable sized objects then the epilogue must restore
6892754fe60SDimitry Andric   // the sp from fp. We can assume there's an FP here since hasFP already
6902754fe60SDimitry Andric   // checks for hasVarSizedObjects.
6912754fe60SDimitry Andric   if (MFI->hasVarSizedObjects())
6922754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
6932754fe60SDimitry Andric }
6942754fe60SDimitry Andric 
6959cac79b3SDimitry Andric void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
6969cac79b3SDimitry Andric                                     MachineBasicBlock &MBB) const {
6972754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
6982754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
69939d628a0SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
7002754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
70139d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
7022754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
7032754fe60SDimitry Andric          "This emitEpilogue does not support Thumb1!");
7042754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
7052754fe60SDimitry Andric 
706ff0cc061SDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
7072754fe60SDimitry Andric   int NumBytes = (int)MFI->getStackSize();
7082754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
7092754fe60SDimitry Andric 
7103861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
7113861d79fSDimitry Andric   // prologue/epilogue.
7127d523365SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
7137ae0e2c9SDimitry Andric     return;
7147d523365SDimitry Andric 
7157d523365SDimitry Andric   // First put ourselves on the first (from top) terminator instructions.
7167d523365SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
7177d523365SDimitry Andric   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
7187ae0e2c9SDimitry Andric 
7192754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
72091bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0)
72191bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
7222754fe60SDimitry Andric   } else {
7232754fe60SDimitry Andric     // Unwind MBBI to point to first LDR / VLDRD.
72491bc56edSDimitry Andric     const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
7252754fe60SDimitry Andric     if (MBBI != MBB.begin()) {
726f785676fSDimitry Andric       do {
7272754fe60SDimitry Andric         --MBBI;
7283ca95b02SDimitry Andric       } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
7293ca95b02SDimitry Andric       if (!isCSRestore(*MBBI, TII, CSRegs))
7302754fe60SDimitry Andric         ++MBBI;
7312754fe60SDimitry Andric     }
7322754fe60SDimitry Andric 
7332754fe60SDimitry Andric     // Move SP to start of FP callee save spill area.
73491bc56edSDimitry Andric     NumBytes -= (ArgRegsSaveSize +
73591bc56edSDimitry Andric                  AFI->getGPRCalleeSavedArea1Size() +
7362754fe60SDimitry Andric                  AFI->getGPRCalleeSavedArea2Size() +
73739d628a0SDimitry Andric                  AFI->getDPRCalleeSavedGapSize() +
7382754fe60SDimitry Andric                  AFI->getDPRCalleeSavedAreaSize());
7392754fe60SDimitry Andric 
7402754fe60SDimitry Andric     // Reset SP based on frame pointer only if the stack frame extends beyond
7412754fe60SDimitry Andric     // frame pointer stack slot or target is ELF and the function has FP.
7422754fe60SDimitry Andric     if (AFI->shouldRestoreSPFromFP()) {
7432754fe60SDimitry Andric       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
7442754fe60SDimitry Andric       if (NumBytes) {
7452754fe60SDimitry Andric         if (isARM)
7462754fe60SDimitry Andric           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
7472754fe60SDimitry Andric                                   ARMCC::AL, 0, TII);
7482754fe60SDimitry Andric         else {
7492754fe60SDimitry Andric           // It's not possible to restore SP from FP in a single instruction.
750dff0c46cSDimitry Andric           // For iOS, this looks like:
7512754fe60SDimitry Andric           // mov sp, r7
7522754fe60SDimitry Andric           // sub sp, #24
7532754fe60SDimitry Andric           // This is bad, if an interrupt is taken after the mov, sp is in an
7542754fe60SDimitry Andric           // inconsistent state.
7552754fe60SDimitry Andric           // Use the first callee-saved register as a scratch register.
756875ed548SDimitry Andric           assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
7572754fe60SDimitry Andric                  "No scratch register to restore SP from FP!");
7582754fe60SDimitry Andric           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
7592754fe60SDimitry Andric                                  ARMCC::AL, 0, TII);
76017a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
76117a519f9SDimitry Andric                                  ARM::SP)
76217a519f9SDimitry Andric             .addReg(ARM::R4));
7632754fe60SDimitry Andric         }
7642754fe60SDimitry Andric       } else {
7652754fe60SDimitry Andric         // Thumb2 or ARM.
7662754fe60SDimitry Andric         if (isARM)
7672754fe60SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
7682754fe60SDimitry Andric             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7692754fe60SDimitry Andric         else
77017a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
77117a519f9SDimitry Andric                                  ARM::SP)
77217a519f9SDimitry Andric             .addReg(FramePtr));
7732754fe60SDimitry Andric       }
77491bc56edSDimitry Andric     } else if (NumBytes &&
7753ca95b02SDimitry Andric                !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
7762754fe60SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
7772754fe60SDimitry Andric 
7782754fe60SDimitry Andric     // Increment past our save areas.
779dd6029ffSDimitry Andric     if (AFI->getDPRCalleeSavedAreaSize()) {
780dd6029ffSDimitry Andric       MBBI++;
781dd6029ffSDimitry Andric       // Since vpop register list cannot have gaps, there may be multiple vpop
782dd6029ffSDimitry Andric       // instructions in the epilogue.
783dd6029ffSDimitry Andric       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
784dd6029ffSDimitry Andric         MBBI++;
785dd6029ffSDimitry Andric     }
78639d628a0SDimitry Andric     if (AFI->getDPRCalleeSavedGapSize()) {
78739d628a0SDimitry Andric       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
78839d628a0SDimitry Andric              "unexpected DPR alignment gap");
78939d628a0SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
79039d628a0SDimitry Andric     }
79139d628a0SDimitry Andric 
7922754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
7932754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
7942754fe60SDimitry Andric   }
7952754fe60SDimitry Andric 
796284c1978SDimitry Andric   if (ArgRegsSaveSize)
797284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
7982754fe60SDimitry Andric }
7992754fe60SDimitry Andric 
8002754fe60SDimitry Andric /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
8012754fe60SDimitry Andric /// debug info.  It's the same as what we use for resolving the code-gen
8022754fe60SDimitry Andric /// references for now.  FIXME: This can go wrong when references are
8032754fe60SDimitry Andric /// SP-relative and simple call frames aren't used.
8042754fe60SDimitry Andric int
8052754fe60SDimitry Andric ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
8062754fe60SDimitry Andric                                          unsigned &FrameReg) const {
8072754fe60SDimitry Andric   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
8082754fe60SDimitry Andric }
8092754fe60SDimitry Andric 
8102754fe60SDimitry Andric int
8112754fe60SDimitry Andric ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
8123b0f4066SDimitry Andric                                              int FI, unsigned &FrameReg,
8132754fe60SDimitry Andric                                              int SPAdj) const {
8142754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
81539d628a0SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
81639d628a0SDimitry Andric       MF.getSubtarget().getRegisterInfo());
8172754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
8182754fe60SDimitry Andric   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
8192754fe60SDimitry Andric   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
8202754fe60SDimitry Andric   bool isFixed = MFI->isFixedObjectIndex(FI);
8212754fe60SDimitry Andric 
8222754fe60SDimitry Andric   FrameReg = ARM::SP;
8232754fe60SDimitry Andric   Offset += SPAdj;
8242754fe60SDimitry Andric 
825dff0c46cSDimitry Andric   // SP can move around if there are allocas.  We may also lose track of SP
826dff0c46cSDimitry Andric   // when emergency spilling inside a non-reserved call frame setup.
827dff0c46cSDimitry Andric   bool hasMovingSP = !hasReservedCallFrame(MF);
828dff0c46cSDimitry Andric 
8292754fe60SDimitry Andric   // When dynamically realigning the stack, use the frame pointer for
8302754fe60SDimitry Andric   // parameters, and the stack/base pointer for locals.
8312754fe60SDimitry Andric   if (RegInfo->needsStackRealignment(MF)) {
8322754fe60SDimitry Andric     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
8332754fe60SDimitry Andric     if (isFixed) {
8342754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8352754fe60SDimitry Andric       Offset = FPOffset;
836dff0c46cSDimitry Andric     } else if (hasMovingSP) {
8372754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) &&
8382754fe60SDimitry Andric              "VLAs and dynamic stack alignment, but missing base pointer!");
8392754fe60SDimitry Andric       FrameReg = RegInfo->getBaseRegister();
8402754fe60SDimitry Andric     }
8412754fe60SDimitry Andric     return Offset;
8422754fe60SDimitry Andric   }
8432754fe60SDimitry Andric 
8442754fe60SDimitry Andric   // If there is a frame pointer, use it when we can.
8452754fe60SDimitry Andric   if (hasFP(MF) && AFI->hasStackFrame()) {
8462754fe60SDimitry Andric     // Use frame pointer to reference fixed objects. Use it for locals if
8472754fe60SDimitry Andric     // there are VLAs (and thus the SP isn't reliable as a base).
848dff0c46cSDimitry Andric     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
8492754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8502754fe60SDimitry Andric       return FPOffset;
851dff0c46cSDimitry Andric     } else if (hasMovingSP) {
8522754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
8533b0f4066SDimitry Andric       if (AFI->isThumb2Function()) {
8542754fe60SDimitry Andric         // Try to use the frame pointer if we can, else use the base pointer
8552754fe60SDimitry Andric         // since it's available. This is handy for the emergency spill slot, in
8562754fe60SDimitry Andric         // particular.
8572754fe60SDimitry Andric         if (FPOffset >= -255 && FPOffset < 0) {
8582754fe60SDimitry Andric           FrameReg = RegInfo->getFrameRegister(MF);
8592754fe60SDimitry Andric           return FPOffset;
8602754fe60SDimitry Andric         }
8613b0f4066SDimitry Andric       }
8622754fe60SDimitry Andric     } else if (AFI->isThumb2Function()) {
8633b0f4066SDimitry Andric       // Use  add <rd>, sp, #<imm8>
8643b0f4066SDimitry Andric       //      ldr <rd>, [sp, #<imm8>]
8653b0f4066SDimitry Andric       // if at all possible to save space.
8663b0f4066SDimitry Andric       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
8673b0f4066SDimitry Andric         return Offset;
8682754fe60SDimitry Andric       // In Thumb2 mode, the negative offset is very limited. Try to avoid
8693b0f4066SDimitry Andric       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
8702754fe60SDimitry Andric       if (FPOffset >= -255 && FPOffset < 0) {
8712754fe60SDimitry Andric         FrameReg = RegInfo->getFrameRegister(MF);
8722754fe60SDimitry Andric         return FPOffset;
8732754fe60SDimitry Andric       }
8742754fe60SDimitry Andric     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
8752754fe60SDimitry Andric       // Otherwise, use SP or FP, whichever is closer to the stack slot.
8762754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8772754fe60SDimitry Andric       return FPOffset;
8782754fe60SDimitry Andric     }
8792754fe60SDimitry Andric   }
8802754fe60SDimitry Andric   // Use the base pointer if we have one.
8812754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
8822754fe60SDimitry Andric     FrameReg = RegInfo->getBaseRegister();
8832754fe60SDimitry Andric   return Offset;
8842754fe60SDimitry Andric }
8852754fe60SDimitry Andric 
8862754fe60SDimitry Andric void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
8872754fe60SDimitry Andric                                     MachineBasicBlock::iterator MI,
8882754fe60SDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
8892754fe60SDimitry Andric                                     unsigned StmOpc, unsigned StrOpc,
8902754fe60SDimitry Andric                                     bool NoGap,
8913b0f4066SDimitry Andric                                     bool(*Func)(unsigned, bool),
892dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
8933b0f4066SDimitry Andric                                     unsigned MIFlags) const {
8942754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
89539d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8962754fe60SDimitry Andric 
8972754fe60SDimitry Andric   DebugLoc DL;
8982754fe60SDimitry Andric 
8992754fe60SDimitry Andric   SmallVector<std::pair<unsigned,bool>, 4> Regs;
9002754fe60SDimitry Andric   unsigned i = CSI.size();
9012754fe60SDimitry Andric   while (i != 0) {
9022754fe60SDimitry Andric     unsigned LastReg = 0;
9032754fe60SDimitry Andric     for (; i != 0; --i) {
9042754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
9053ca95b02SDimitry Andric       if (!(Func)(Reg, STI.splitFramePushPop())) continue;
906dff0c46cSDimitry Andric 
907dff0c46cSDimitry Andric       // D-registers in the aligned area DPRCS2 are NOT spilled here.
908dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
909dff0c46cSDimitry Andric         continue;
9102754fe60SDimitry Andric 
9113ca95b02SDimitry Andric       bool isLiveIn = MF.getRegInfo().isLiveIn(Reg);
9123ca95b02SDimitry Andric       if (!isLiveIn)
9132754fe60SDimitry Andric         MBB.addLiveIn(Reg);
9142754fe60SDimitry Andric       // If NoGap is true, push consecutive registers and then leave the rest
9152754fe60SDimitry Andric       // for other instructions. e.g.
9162754fe60SDimitry Andric       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
9172754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
9182754fe60SDimitry Andric         break;
9192754fe60SDimitry Andric       LastReg = Reg;
9203ca95b02SDimitry Andric       // Do not set a kill flag on values that are also marked as live-in. This
9213ca95b02SDimitry Andric       // happens with the @llvm-returnaddress intrinsic and with arguments
9223ca95b02SDimitry Andric       // passed in callee saved registers.
9233ca95b02SDimitry Andric       // Omitting the kill flags is conservatively correct even if the live-in
9243ca95b02SDimitry Andric       // is not used after all.
9253ca95b02SDimitry Andric       Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
9262754fe60SDimitry Andric     }
9272754fe60SDimitry Andric 
9282754fe60SDimitry Andric     if (Regs.empty())
9292754fe60SDimitry Andric       continue;
9302754fe60SDimitry Andric     if (Regs.size() > 1 || StrOpc== 0) {
9312754fe60SDimitry Andric       MachineInstrBuilder MIB =
9322754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
9333b0f4066SDimitry Andric                        .addReg(ARM::SP).setMIFlags(MIFlags));
9342754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
9352754fe60SDimitry Andric         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
9362754fe60SDimitry Andric     } else if (Regs.size() == 1) {
9372754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
9382754fe60SDimitry Andric                                         ARM::SP)
9392754fe60SDimitry Andric         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
9406122f3e6SDimitry Andric         .addReg(ARM::SP).setMIFlags(MIFlags)
9416122f3e6SDimitry Andric         .addImm(-4);
9422754fe60SDimitry Andric       AddDefaultPred(MIB);
9432754fe60SDimitry Andric     }
9442754fe60SDimitry Andric     Regs.clear();
94591bc56edSDimitry Andric 
94691bc56edSDimitry Andric     // Put any subsequent vpush instructions before this one: they will refer to
94791bc56edSDimitry Andric     // higher register numbers so need to be pushed first in order to preserve
94891bc56edSDimitry Andric     // monotonicity.
9497d523365SDimitry Andric     if (MI != MBB.begin())
95091bc56edSDimitry Andric       --MI;
9512754fe60SDimitry Andric   }
9522754fe60SDimitry Andric }
9532754fe60SDimitry Andric 
9542754fe60SDimitry Andric void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
9552754fe60SDimitry Andric                                    MachineBasicBlock::iterator MI,
9562754fe60SDimitry Andric                                    const std::vector<CalleeSavedInfo> &CSI,
9572754fe60SDimitry Andric                                    unsigned LdmOpc, unsigned LdrOpc,
9582754fe60SDimitry Andric                                    bool isVarArg, bool NoGap,
959dff0c46cSDimitry Andric                                    bool(*Func)(unsigned, bool),
960dff0c46cSDimitry Andric                                    unsigned NumAlignedDPRCS2Regs) const {
9612754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
96239d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9632754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
9647d523365SDimitry Andric   DebugLoc DL;
9657d523365SDimitry Andric   bool isTailCall = false;
9667d523365SDimitry Andric   bool isInterrupt = false;
9677d523365SDimitry Andric   bool isTrap = false;
9687d523365SDimitry Andric   if (MBB.end() != MI) {
9697d523365SDimitry Andric     DL = MI->getDebugLoc();
9702754fe60SDimitry Andric     unsigned RetOpcode = MI->getOpcode();
9717d523365SDimitry Andric     isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
9727d523365SDimitry Andric     isInterrupt =
973f785676fSDimitry Andric         RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
9747d523365SDimitry Andric     isTrap =
9757d523365SDimitry Andric         RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
9767d523365SDimitry Andric         RetOpcode == ARM::tTRAP;
9777d523365SDimitry Andric   }
9782754fe60SDimitry Andric 
9792754fe60SDimitry Andric   SmallVector<unsigned, 4> Regs;
9802754fe60SDimitry Andric   unsigned i = CSI.size();
9812754fe60SDimitry Andric   while (i != 0) {
9822754fe60SDimitry Andric     unsigned LastReg = 0;
9832754fe60SDimitry Andric     bool DeleteRet = false;
9842754fe60SDimitry Andric     for (; i != 0; --i) {
9852754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
9863ca95b02SDimitry Andric       if (!(Func)(Reg, STI.splitFramePushPop())) continue;
987dff0c46cSDimitry Andric 
988dff0c46cSDimitry Andric       // The aligned reloads from area DPRCS2 are not inserted here.
989dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
990dff0c46cSDimitry Andric         continue;
9912754fe60SDimitry Andric 
992f785676fSDimitry Andric       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
9937d523365SDimitry Andric           !isTrap && STI.hasV5TOps()) {
9947d523365SDimitry Andric         if (MBB.succ_empty()) {
9952754fe60SDimitry Andric           Reg = ARM::PC;
9962754fe60SDimitry Andric           DeleteRet = true;
9977d523365SDimitry Andric           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
9987d523365SDimitry Andric         } else
9997d523365SDimitry Andric           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
10007d523365SDimitry Andric         // Fold the return instruction into the LDM.
10012754fe60SDimitry Andric       }
10022754fe60SDimitry Andric 
10032754fe60SDimitry Andric       // If NoGap is true, pop consecutive registers and then leave the rest
10042754fe60SDimitry Andric       // for other instructions. e.g.
10052754fe60SDimitry Andric       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
10062754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
10072754fe60SDimitry Andric         break;
10082754fe60SDimitry Andric 
10092754fe60SDimitry Andric       LastReg = Reg;
10102754fe60SDimitry Andric       Regs.push_back(Reg);
10112754fe60SDimitry Andric     }
10122754fe60SDimitry Andric 
10132754fe60SDimitry Andric     if (Regs.empty())
10142754fe60SDimitry Andric       continue;
10152754fe60SDimitry Andric     if (Regs.size() > 1 || LdrOpc == 0) {
10162754fe60SDimitry Andric       MachineInstrBuilder MIB =
10172754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
10182754fe60SDimitry Andric                        .addReg(ARM::SP));
10192754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
10202754fe60SDimitry Andric         MIB.addReg(Regs[i], getDefRegState(true));
10217d523365SDimitry Andric       if (DeleteRet && MI != MBB.end()) {
10223ca95b02SDimitry Andric         MIB.copyImplicitOps(*MI);
10232754fe60SDimitry Andric         MI->eraseFromParent();
10246122f3e6SDimitry Andric       }
10252754fe60SDimitry Andric       MI = MIB;
10262754fe60SDimitry Andric     } else if (Regs.size() == 1) {
10272754fe60SDimitry Andric       // If we adjusted the reg to PC from LR above, switch it back here. We
10282754fe60SDimitry Andric       // only do that for LDM.
10292754fe60SDimitry Andric       if (Regs[0] == ARM::PC)
10302754fe60SDimitry Andric         Regs[0] = ARM::LR;
10312754fe60SDimitry Andric       MachineInstrBuilder MIB =
10322754fe60SDimitry Andric         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
10332754fe60SDimitry Andric           .addReg(ARM::SP, RegState::Define)
10342754fe60SDimitry Andric           .addReg(ARM::SP);
10352754fe60SDimitry Andric       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
10362754fe60SDimitry Andric       // that refactoring is complete (eventually).
10376122f3e6SDimitry Andric       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
10382754fe60SDimitry Andric         MIB.addReg(0);
10392754fe60SDimitry Andric         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
10402754fe60SDimitry Andric       } else
10412754fe60SDimitry Andric         MIB.addImm(4);
10422754fe60SDimitry Andric       AddDefaultPred(MIB);
10432754fe60SDimitry Andric     }
10442754fe60SDimitry Andric     Regs.clear();
104591bc56edSDimitry Andric 
104691bc56edSDimitry Andric     // Put any subsequent vpop instructions after this one: they will refer to
104791bc56edSDimitry Andric     // higher register numbers so need to be popped afterwards.
10487d523365SDimitry Andric     if (MI != MBB.end())
104991bc56edSDimitry Andric       ++MI;
10502754fe60SDimitry Andric   }
10512754fe60SDimitry Andric }
10522754fe60SDimitry Andric 
1053dff0c46cSDimitry Andric /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1054dff0c46cSDimitry Andric /// starting from d8.  Also insert stack realignment code and leave the stack
1055dff0c46cSDimitry Andric /// pointer pointing to the d8 spill slot.
1056dff0c46cSDimitry Andric static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1057dff0c46cSDimitry Andric                                     MachineBasicBlock::iterator MI,
1058dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
1059dff0c46cSDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
1060dff0c46cSDimitry Andric                                     const TargetRegisterInfo *TRI) {
1061dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1062dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
10637d523365SDimitry Andric   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
106439d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1065dff0c46cSDimitry Andric   MachineFrameInfo &MFI = *MF.getFrameInfo();
1066dff0c46cSDimitry Andric 
1067dff0c46cSDimitry Andric   // Mark the D-register spill slots as properly aligned.  Since MFI computes
1068dff0c46cSDimitry Andric   // stack slot layout backwards, this can actually mean that the d-reg stack
1069dff0c46cSDimitry Andric   // slot offsets can be wrong. The offset for d8 will always be correct.
1070dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1071dff0c46cSDimitry Andric     unsigned DNum = CSI[i].getReg() - ARM::D8;
10727d523365SDimitry Andric     if (DNum > NumAlignedDPRCS2Regs - 1)
1073dff0c46cSDimitry Andric       continue;
1074dff0c46cSDimitry Andric     int FI = CSI[i].getFrameIdx();
1075dff0c46cSDimitry Andric     // The even-numbered registers will be 16-byte aligned, the odd-numbered
1076dff0c46cSDimitry Andric     // registers will be 8-byte aligned.
1077dff0c46cSDimitry Andric     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1078dff0c46cSDimitry Andric 
1079dff0c46cSDimitry Andric     // The stack slot for D8 needs to be maximally aligned because this is
1080dff0c46cSDimitry Andric     // actually the point where we align the stack pointer.  MachineFrameInfo
1081dff0c46cSDimitry Andric     // computes all offsets relative to the incoming stack pointer which is a
1082dff0c46cSDimitry Andric     // bit weird when realigning the stack.  Any extra padding for this
1083dff0c46cSDimitry Andric     // over-alignment is not realized because the code inserted below adjusts
1084dff0c46cSDimitry Andric     // the stack pointer by numregs * 8 before aligning the stack pointer.
1085dff0c46cSDimitry Andric     if (DNum == 0)
1086dff0c46cSDimitry Andric       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1087dff0c46cSDimitry Andric   }
1088dff0c46cSDimitry Andric 
1089dff0c46cSDimitry Andric   // Move the stack pointer to the d8 spill slot, and align it at the same
1090dff0c46cSDimitry Andric   // time. Leave the stack slot address in the scratch register r4.
1091dff0c46cSDimitry Andric   //
1092dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1093dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1094dff0c46cSDimitry Andric   //   mov sp, r4
1095dff0c46cSDimitry Andric   //
1096dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1097dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1098dff0c46cSDimitry Andric   AFI->setShouldRestoreSPFromFP(true);
1099dff0c46cSDimitry Andric 
1100dff0c46cSDimitry Andric   // sub r4, sp, #numregs * 8
1101dff0c46cSDimitry Andric   // The immediate is <= 64, so it doesn't need any special encoding.
1102dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1103dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1104dff0c46cSDimitry Andric                                   .addReg(ARM::SP)
1105dff0c46cSDimitry Andric                                   .addImm(8 * NumAlignedDPRCS2Regs)));
1106dff0c46cSDimitry Andric 
1107dff0c46cSDimitry Andric   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
110839d628a0SDimitry Andric   // We must set parameter MustBeSingleInstruction to true, since
110939d628a0SDimitry Andric   // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
111039d628a0SDimitry Andric   // stack alignment.  Luckily, this can always be done since all ARM
111139d628a0SDimitry Andric   // architecture versions that support Neon also support the BFC
111239d628a0SDimitry Andric   // instruction.
111339d628a0SDimitry Andric   emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1114dff0c46cSDimitry Andric 
1115dff0c46cSDimitry Andric   // mov sp, r4
1116dff0c46cSDimitry Andric   // The stack pointer must be adjusted before spilling anything, otherwise
1117dff0c46cSDimitry Andric   // the stack slots could be clobbered by an interrupt handler.
1118dff0c46cSDimitry Andric   // Leave r4 live, it is used below.
1119dff0c46cSDimitry Andric   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1120dff0c46cSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1121dff0c46cSDimitry Andric                             .addReg(ARM::R4);
1122dff0c46cSDimitry Andric   MIB = AddDefaultPred(MIB);
1123dff0c46cSDimitry Andric   if (!isThumb)
1124dff0c46cSDimitry Andric     AddDefaultCC(MIB);
1125dff0c46cSDimitry Andric 
1126dff0c46cSDimitry Andric   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1127dff0c46cSDimitry Andric   // r4 holds the stack slot address.
1128dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1129dff0c46cSDimitry Andric 
1130dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1131dff0c46cSDimitry Andric   // The writeback is only needed when emitting two vst1.64 instructions.
1132dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1133dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11347ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1135dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1136dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1137dff0c46cSDimitry Andric                            ARM::R4)
1138dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1139dff0c46cSDimitry Andric                    .addReg(NextReg)
1140dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1141dff0c46cSDimitry Andric     NextReg += 4;
1142dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1143dff0c46cSDimitry Andric   }
1144dff0c46cSDimitry Andric 
1145dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1146dff0c46cSDimitry Andric   // register to be spilled.
1147dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1148dff0c46cSDimitry Andric 
1149dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1150dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1151dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11527ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1153dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1154dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1155dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
1156dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1157dff0c46cSDimitry Andric     NextReg += 4;
1158dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1159dff0c46cSDimitry Andric   }
1160dff0c46cSDimitry Andric 
1161dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 2 d-regs.
1162dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1163dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11647ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1165dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1166dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1167dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
1168dff0c46cSDimitry Andric     NextReg += 2;
1169dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1170dff0c46cSDimitry Andric   }
1171dff0c46cSDimitry Andric 
1172dff0c46cSDimitry Andric   // Finally, use a vanilla vstr.64 for the odd last register.
1173dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs) {
1174dff0c46cSDimitry Andric     MBB.addLiveIn(NextReg);
1175dff0c46cSDimitry Andric     // vstr.64 uses addrmode5 which has an offset scale of 4.
1176dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1177dff0c46cSDimitry Andric                    .addReg(NextReg)
1178dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1179dff0c46cSDimitry Andric   }
1180dff0c46cSDimitry Andric 
1181dff0c46cSDimitry Andric   // The last spill instruction inserted should kill the scratch register r4.
118291bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1183dff0c46cSDimitry Andric }
1184dff0c46cSDimitry Andric 
1185dff0c46cSDimitry Andric /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1186dff0c46cSDimitry Andric /// iterator to the following instruction.
1187dff0c46cSDimitry Andric static MachineBasicBlock::iterator
1188dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1189dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs) {
1190dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1191dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1192dff0c46cSDimitry Andric   //   mov sp, r4
1193dff0c46cSDimitry Andric   ++MI; ++MI; ++MI;
1194dff0c46cSDimitry Andric   assert(MI->mayStore() && "Expecting spill instruction");
1195dff0c46cSDimitry Andric 
1196dff0c46cSDimitry Andric   // These switches all fall through.
1197dff0c46cSDimitry Andric   switch(NumAlignedDPRCS2Regs) {
1198dff0c46cSDimitry Andric   case 7:
1199dff0c46cSDimitry Andric     ++MI;
1200dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1201dff0c46cSDimitry Andric   default:
1202dff0c46cSDimitry Andric     ++MI;
1203dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1204dff0c46cSDimitry Andric   case 1:
1205dff0c46cSDimitry Andric   case 2:
1206dff0c46cSDimitry Andric   case 4:
1207dff0c46cSDimitry Andric     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1208dff0c46cSDimitry Andric     ++MI;
1209dff0c46cSDimitry Andric   }
1210dff0c46cSDimitry Andric   return MI;
1211dff0c46cSDimitry Andric }
1212dff0c46cSDimitry Andric 
1213dff0c46cSDimitry Andric /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1214dff0c46cSDimitry Andric /// starting from d8.  These instructions are assumed to execute while the
1215dff0c46cSDimitry Andric /// stack is still aligned, unlike the code inserted by emitPopInst.
1216dff0c46cSDimitry Andric static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1217dff0c46cSDimitry Andric                                       MachineBasicBlock::iterator MI,
1218dff0c46cSDimitry Andric                                       unsigned NumAlignedDPRCS2Regs,
1219dff0c46cSDimitry Andric                                       const std::vector<CalleeSavedInfo> &CSI,
1220dff0c46cSDimitry Andric                                       const TargetRegisterInfo *TRI) {
1221dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1222dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12237d523365SDimitry Andric   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
122439d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1225dff0c46cSDimitry Andric 
1226dff0c46cSDimitry Andric   // Find the frame index assigned to d8.
1227dff0c46cSDimitry Andric   int D8SpillFI = 0;
1228dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1229dff0c46cSDimitry Andric     if (CSI[i].getReg() == ARM::D8) {
1230dff0c46cSDimitry Andric       D8SpillFI = CSI[i].getFrameIdx();
1231dff0c46cSDimitry Andric       break;
1232dff0c46cSDimitry Andric     }
1233dff0c46cSDimitry Andric 
1234dff0c46cSDimitry Andric   // Materialize the address of the d8 spill slot into the scratch register r4.
1235dff0c46cSDimitry Andric   // This can be fairly complicated if the stack frame is large, so just use
1236dff0c46cSDimitry Andric   // the normal frame index elimination mechanism to do it.  This code runs as
1237dff0c46cSDimitry Andric   // the initial part of the epilog where the stack and base pointers haven't
1238dff0c46cSDimitry Andric   // been changed yet.
1239dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1240dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1241dff0c46cSDimitry Andric 
1242dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1243dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1244dff0c46cSDimitry Andric                               .addFrameIndex(D8SpillFI).addImm(0)));
1245dff0c46cSDimitry Andric 
1246dff0c46cSDimitry Andric   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1247dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1248dff0c46cSDimitry Andric 
1249dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1250dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1251dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12527ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1253dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1254dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Define)
1255dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1256dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1257dff0c46cSDimitry Andric     NextReg += 4;
1258dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1259dff0c46cSDimitry Andric   }
1260dff0c46cSDimitry Andric 
1261dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1262dff0c46cSDimitry Andric   // register to be spilled.
1263dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1264dff0c46cSDimitry Andric 
1265dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1266dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1267dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12687ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1269dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1270dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16)
1271dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1272dff0c46cSDimitry Andric     NextReg += 4;
1273dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1274dff0c46cSDimitry Andric   }
1275dff0c46cSDimitry Andric 
1276dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 2 d-regs.
1277dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1278dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12797ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1280dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1281dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16));
1282dff0c46cSDimitry Andric     NextReg += 2;
1283dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1284dff0c46cSDimitry Andric   }
1285dff0c46cSDimitry Andric 
1286dff0c46cSDimitry Andric   // Finally, use a vanilla vldr.64 for the remaining odd register.
1287dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1288dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1289dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1290dff0c46cSDimitry Andric 
1291dff0c46cSDimitry Andric   // Last store kills r4.
129291bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1293dff0c46cSDimitry Andric }
1294dff0c46cSDimitry Andric 
12952754fe60SDimitry Andric bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
12962754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
12972754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
12982754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
12992754fe60SDimitry Andric   if (CSI.empty())
13002754fe60SDimitry Andric     return false;
13012754fe60SDimitry Andric 
13022754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
13032754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
13042754fe60SDimitry Andric 
13052754fe60SDimitry Andric   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
13066122f3e6SDimitry Andric   unsigned PushOneOpc = AFI->isThumbFunction() ?
13076122f3e6SDimitry Andric     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
13082754fe60SDimitry Andric   unsigned FltOpc = ARM::VSTMDDB_UPD;
1309dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1310dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
13113b0f4066SDimitry Andric                MachineInstr::FrameSetup);
1312dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
13133b0f4066SDimitry Andric                MachineInstr::FrameSetup);
13143b0f4066SDimitry Andric   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1315dff0c46cSDimitry Andric                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1316dff0c46cSDimitry Andric 
1317dff0c46cSDimitry Andric   // The code above does not insert spill code for the aligned DPRCS2 registers.
1318dff0c46cSDimitry Andric   // The stack realignment code will be inserted between the push instructions
1319dff0c46cSDimitry Andric   // and these spills.
1320dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1321dff0c46cSDimitry Andric     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
13222754fe60SDimitry Andric 
13232754fe60SDimitry Andric   return true;
13242754fe60SDimitry Andric }
13252754fe60SDimitry Andric 
13262754fe60SDimitry Andric bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
13272754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
13282754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
13292754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
13302754fe60SDimitry Andric   if (CSI.empty())
13312754fe60SDimitry Andric     return false;
13322754fe60SDimitry Andric 
13332754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
13342754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1335284c1978SDimitry Andric   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1336dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1337dff0c46cSDimitry Andric 
1338dff0c46cSDimitry Andric   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1339dff0c46cSDimitry Andric   // registers. Do that here instead.
1340dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1341dff0c46cSDimitry Andric     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
13422754fe60SDimitry Andric 
13432754fe60SDimitry Andric   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
13446122f3e6SDimitry Andric   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
13452754fe60SDimitry Andric   unsigned FltOpc = ARM::VLDMDIA_UPD;
1346dff0c46cSDimitry Andric   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1347dff0c46cSDimitry Andric               NumAlignedDPRCS2Regs);
13482754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1349dff0c46cSDimitry Andric               &isARMArea2Register, 0);
13502754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1351dff0c46cSDimitry Andric               &isARMArea1Register, 0);
13522754fe60SDimitry Andric 
13532754fe60SDimitry Andric   return true;
13542754fe60SDimitry Andric }
13552754fe60SDimitry Andric 
13562754fe60SDimitry Andric // FIXME: Make generic?
13572754fe60SDimitry Andric static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
13582754fe60SDimitry Andric                                        const ARMBaseInstrInfo &TII) {
13592754fe60SDimitry Andric   unsigned FnSize = 0;
136091bc56edSDimitry Andric   for (auto &MBB : MF) {
136191bc56edSDimitry Andric     for (auto &MI : MBB)
13623ca95b02SDimitry Andric       FnSize += TII.GetInstSizeInBytes(MI);
13632754fe60SDimitry Andric   }
13642754fe60SDimitry Andric   return FnSize;
13652754fe60SDimitry Andric }
13662754fe60SDimitry Andric 
13672754fe60SDimitry Andric /// estimateRSStackSizeLimit - Look at each instruction that references stack
13682754fe60SDimitry Andric /// frames and return the stack size limit beyond which some of these
13692754fe60SDimitry Andric /// instructions will require a scratch register during their expansion later.
13702754fe60SDimitry Andric // FIXME: Move to TII?
13712754fe60SDimitry Andric static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
13722754fe60SDimitry Andric                                          const TargetFrameLowering *TFI) {
13732754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
13742754fe60SDimitry Andric   unsigned Limit = (1 << 12) - 1;
137591bc56edSDimitry Andric   for (auto &MBB : MF) {
137691bc56edSDimitry Andric     for (auto &MI : MBB) {
137791bc56edSDimitry Andric       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
137891bc56edSDimitry Andric         if (!MI.getOperand(i).isFI())
137991bc56edSDimitry Andric           continue;
13802754fe60SDimitry Andric 
13812754fe60SDimitry Andric         // When using ADDri to get the address of a stack object, 255 is the
13822754fe60SDimitry Andric         // largest offset guaranteed to fit in the immediate offset.
138391bc56edSDimitry Andric         if (MI.getOpcode() == ARM::ADDri) {
13842754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
13852754fe60SDimitry Andric           break;
13862754fe60SDimitry Andric         }
13872754fe60SDimitry Andric 
13882754fe60SDimitry Andric         // Otherwise check the addressing mode.
138991bc56edSDimitry Andric         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
13902754fe60SDimitry Andric         case ARMII::AddrMode3:
13912754fe60SDimitry Andric         case ARMII::AddrModeT2_i8:
13922754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
13932754fe60SDimitry Andric           break;
13942754fe60SDimitry Andric         case ARMII::AddrMode5:
13952754fe60SDimitry Andric         case ARMII::AddrModeT2_i8s4:
13962754fe60SDimitry Andric           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
13972754fe60SDimitry Andric           break;
13982754fe60SDimitry Andric         case ARMII::AddrModeT2_i12:
13992754fe60SDimitry Andric           // i12 supports only positive offset so these will be converted to
14002754fe60SDimitry Andric           // i8 opcodes. See llvm::rewriteT2FrameIndex.
14012754fe60SDimitry Andric           if (TFI->hasFP(MF) && AFI->hasStackFrame())
14022754fe60SDimitry Andric             Limit = std::min(Limit, (1U << 8) - 1);
14032754fe60SDimitry Andric           break;
14042754fe60SDimitry Andric         case ARMII::AddrMode4:
14052754fe60SDimitry Andric         case ARMII::AddrMode6:
14062754fe60SDimitry Andric           // Addressing modes 4 & 6 (load/store) instructions can't encode an
14072754fe60SDimitry Andric           // immediate offset for stack references.
14082754fe60SDimitry Andric           return 0;
14092754fe60SDimitry Andric         default:
14102754fe60SDimitry Andric           break;
14112754fe60SDimitry Andric         }
14122754fe60SDimitry Andric         break; // At most one FI per instruction
14132754fe60SDimitry Andric       }
14142754fe60SDimitry Andric     }
14152754fe60SDimitry Andric   }
14162754fe60SDimitry Andric 
14172754fe60SDimitry Andric   return Limit;
14182754fe60SDimitry Andric }
14192754fe60SDimitry Andric 
1420dff0c46cSDimitry Andric // In functions that realign the stack, it can be an advantage to spill the
1421dff0c46cSDimitry Andric // callee-saved vector registers after realigning the stack. The vst1 and vld1
1422dff0c46cSDimitry Andric // instructions take alignment hints that can improve performance.
1423dff0c46cSDimitry Andric //
1424875ed548SDimitry Andric static void
1425875ed548SDimitry Andric checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1426dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1427dff0c46cSDimitry Andric   if (!SpillAlignedNEONRegs)
1428dff0c46cSDimitry Andric     return;
1429dff0c46cSDimitry Andric 
1430dff0c46cSDimitry Andric   // Naked functions don't spill callee-saved registers.
1431ff0cc061SDimitry Andric   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1432dff0c46cSDimitry Andric     return;
1433dff0c46cSDimitry Andric 
1434dff0c46cSDimitry Andric   // We are planning to use NEON instructions vst1 / vld1.
1435ff0cc061SDimitry Andric   if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1436dff0c46cSDimitry Andric     return;
1437dff0c46cSDimitry Andric 
1438dff0c46cSDimitry Andric   // Don't bother if the default stack alignment is sufficiently high.
1439ff0cc061SDimitry Andric   if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1440dff0c46cSDimitry Andric     return;
1441dff0c46cSDimitry Andric 
1442dff0c46cSDimitry Andric   // Aligned spills require stack realignment.
1443ff0cc061SDimitry Andric   if (!static_cast<const ARMBaseRegisterInfo *>(
1444ff0cc061SDimitry Andric            MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1445dff0c46cSDimitry Andric     return;
1446dff0c46cSDimitry Andric 
1447dff0c46cSDimitry Andric   // We always spill contiguous d-registers starting from d8. Count how many
1448dff0c46cSDimitry Andric   // needs spilling.  The register allocator will almost always use the
1449dff0c46cSDimitry Andric   // callee-saved registers in order, but it can happen that there are holes in
1450dff0c46cSDimitry Andric   // the range.  Registers above the hole will be spilled to the standard DPRCS
1451dff0c46cSDimitry Andric   // area.
1452dff0c46cSDimitry Andric   unsigned NumSpills = 0;
1453dff0c46cSDimitry Andric   for (; NumSpills < 8; ++NumSpills)
1454875ed548SDimitry Andric     if (!SavedRegs.test(ARM::D8 + NumSpills))
1455dff0c46cSDimitry Andric       break;
1456dff0c46cSDimitry Andric 
1457dff0c46cSDimitry Andric   // Don't do this for just one d-register. It's not worth it.
1458dff0c46cSDimitry Andric   if (NumSpills < 2)
1459dff0c46cSDimitry Andric     return;
1460dff0c46cSDimitry Andric 
1461dff0c46cSDimitry Andric   // Spill the first NumSpills D-registers after realigning the stack.
1462dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1463dff0c46cSDimitry Andric 
1464dff0c46cSDimitry Andric   // A scratch register is required for the vst1 / vld1 instructions.
1465875ed548SDimitry Andric   SavedRegs.set(ARM::R4);
1466dff0c46cSDimitry Andric }
1467dff0c46cSDimitry Andric 
1468875ed548SDimitry Andric void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1469875ed548SDimitry Andric                                             BitVector &SavedRegs,
14702754fe60SDimitry Andric                                             RegScavenger *RS) const {
1471875ed548SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
14722754fe60SDimitry Andric   // This tells PEI to spill the FP as if it is any other callee-save register
14732754fe60SDimitry Andric   // to take advantage the eliminateFrameIndex machinery. This also ensures it
14742754fe60SDimitry Andric   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
14752754fe60SDimitry Andric   // to combine multiple loads / stores.
14762754fe60SDimitry Andric   bool CanEliminateFrame = true;
14772754fe60SDimitry Andric   bool CS1Spilled = false;
14782754fe60SDimitry Andric   bool LRSpilled = false;
14792754fe60SDimitry Andric   unsigned NumGPRSpills = 0;
14803ca95b02SDimitry Andric   unsigned NumFPRSpills = 0;
14812754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS1GPRs;
14822754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS2GPRs;
148339d628a0SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
148439d628a0SDimitry Andric       MF.getSubtarget().getRegisterInfo());
14852754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
148639d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
14872754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
14882754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
14893861d79fSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
14902754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
14912754fe60SDimitry Andric 
14922754fe60SDimitry Andric   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
14932754fe60SDimitry Andric   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
14942754fe60SDimitry Andric   // since it's not always possible to restore sp from fp in a single
14952754fe60SDimitry Andric   // instruction.
14962754fe60SDimitry Andric   // FIXME: It will be better just to find spare register here.
14972754fe60SDimitry Andric   if (AFI->isThumb2Function() &&
14982754fe60SDimitry Andric       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1499875ed548SDimitry Andric     SavedRegs.set(ARM::R4);
15002754fe60SDimitry Andric 
15012754fe60SDimitry Andric   if (AFI->isThumb1OnlyFunction()) {
15022754fe60SDimitry Andric     // Spill LR if Thumb1 function uses variable length argument lists.
1503284c1978SDimitry Andric     if (AFI->getArgRegsSaveSize() > 0)
1504875ed548SDimitry Andric       SavedRegs.set(ARM::LR);
15052754fe60SDimitry Andric 
150617a519f9SDimitry Andric     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
150717a519f9SDimitry Andric     // for sure what the stack size will be, but for this, an estimate is good
150817a519f9SDimitry Andric     // enough. If there anything changes it, it'll be a spill, which implies
150917a519f9SDimitry Andric     // we've used all the registers and so R4 is already used, so not marking
151017a519f9SDimitry Andric     // it here will be OK.
15112754fe60SDimitry Andric     // FIXME: It will be better just to find spare register here.
1512139f7f9bSDimitry Andric     unsigned StackSize = MFI->estimateStackSize(MF);
151317a519f9SDimitry Andric     if (MFI->hasVarSizedObjects() || StackSize > 508)
1514875ed548SDimitry Andric       SavedRegs.set(ARM::R4);
15152754fe60SDimitry Andric   }
15162754fe60SDimitry Andric 
1517dff0c46cSDimitry Andric   // See if we can spill vector registers to aligned stack.
1518875ed548SDimitry Andric   checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1519dff0c46cSDimitry Andric 
15202754fe60SDimitry Andric   // Spill the BasePtr if it's used.
15212754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
1522875ed548SDimitry Andric     SavedRegs.set(RegInfo->getBaseRegister());
15232754fe60SDimitry Andric 
15242754fe60SDimitry Andric   // Don't spill FP if the frame can be eliminated. This is determined
1525875ed548SDimitry Andric   // by scanning the callee-save registers to see if any is modified.
152691bc56edSDimitry Andric   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
15272754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i) {
15282754fe60SDimitry Andric     unsigned Reg = CSRegs[i];
15292754fe60SDimitry Andric     bool Spilled = false;
1530875ed548SDimitry Andric     if (SavedRegs.test(Reg)) {
15312754fe60SDimitry Andric       Spilled = true;
15322754fe60SDimitry Andric       CanEliminateFrame = false;
15332754fe60SDimitry Andric     }
15342754fe60SDimitry Andric 
15353ca95b02SDimitry Andric     if (!ARM::GPRRegClass.contains(Reg)) {
15363ca95b02SDimitry Andric       if (Spilled) {
15373ca95b02SDimitry Andric         if (ARM::SPRRegClass.contains(Reg))
15383ca95b02SDimitry Andric           NumFPRSpills++;
15393ca95b02SDimitry Andric         else if (ARM::DPRRegClass.contains(Reg))
15403ca95b02SDimitry Andric           NumFPRSpills += 2;
15413ca95b02SDimitry Andric         else if (ARM::QPRRegClass.contains(Reg))
15423ca95b02SDimitry Andric           NumFPRSpills += 4;
15433ca95b02SDimitry Andric       }
15442754fe60SDimitry Andric       continue;
15453ca95b02SDimitry Andric     }
15462754fe60SDimitry Andric 
15472754fe60SDimitry Andric     if (Spilled) {
15482754fe60SDimitry Andric       NumGPRSpills++;
15492754fe60SDimitry Andric 
15503ca95b02SDimitry Andric       if (!STI.splitFramePushPop()) {
15512754fe60SDimitry Andric         if (Reg == ARM::LR)
15522754fe60SDimitry Andric           LRSpilled = true;
15532754fe60SDimitry Andric         CS1Spilled = true;
15542754fe60SDimitry Andric         continue;
15552754fe60SDimitry Andric       }
15562754fe60SDimitry Andric 
15572754fe60SDimitry Andric       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
15582754fe60SDimitry Andric       switch (Reg) {
15592754fe60SDimitry Andric       case ARM::LR:
15602754fe60SDimitry Andric         LRSpilled = true;
15612754fe60SDimitry Andric         // Fallthrough
1562f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1563f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
15642754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
15652754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
15662754fe60SDimitry Andric         CS1Spilled = true;
15672754fe60SDimitry Andric         break;
15682754fe60SDimitry Andric       default:
15692754fe60SDimitry Andric         break;
15702754fe60SDimitry Andric       }
15712754fe60SDimitry Andric     } else {
15723ca95b02SDimitry Andric       if (!STI.splitFramePushPop()) {
15732754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
15742754fe60SDimitry Andric         continue;
15752754fe60SDimitry Andric       }
15762754fe60SDimitry Andric 
15772754fe60SDimitry Andric       switch (Reg) {
1578f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1579f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
15802754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
15812754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
15822754fe60SDimitry Andric       case ARM::LR:
15832754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
15842754fe60SDimitry Andric         break;
15852754fe60SDimitry Andric       default:
15862754fe60SDimitry Andric         UnspilledCS2GPRs.push_back(Reg);
15872754fe60SDimitry Andric         break;
15882754fe60SDimitry Andric       }
15892754fe60SDimitry Andric     }
15902754fe60SDimitry Andric   }
15912754fe60SDimitry Andric 
15922754fe60SDimitry Andric   bool ForceLRSpill = false;
15932754fe60SDimitry Andric   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
15942754fe60SDimitry Andric     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
15952754fe60SDimitry Andric     // Force LR to be spilled if the Thumb function size is > 2048. This enables
15962754fe60SDimitry Andric     // use of BL to implement far jump. If it turns out that it's not needed
15972754fe60SDimitry Andric     // then the branch fix up path will undo it.
15982754fe60SDimitry Andric     if (FnSize >= (1 << 11)) {
15992754fe60SDimitry Andric       CanEliminateFrame = false;
16002754fe60SDimitry Andric       ForceLRSpill = true;
16012754fe60SDimitry Andric     }
16022754fe60SDimitry Andric   }
16032754fe60SDimitry Andric 
16042754fe60SDimitry Andric   // If any of the stack slot references may be out of range of an immediate
16052754fe60SDimitry Andric   // offset, make sure a register (or a spill slot) is available for the
16062754fe60SDimitry Andric   // register scavenger. Note that if we're indexing off the frame pointer, the
16072754fe60SDimitry Andric   // effective stack size is 4 bytes larger since the FP points to the stack
16082754fe60SDimitry Andric   // slot of the previous FP. Also, if we have variable sized objects in the
16092754fe60SDimitry Andric   // function, stack slot references will often be negative, and some of
16102754fe60SDimitry Andric   // our instructions are positive-offset only, so conservatively consider
16112754fe60SDimitry Andric   // that case to want a spill slot (or register) as well. Similarly, if
16122754fe60SDimitry Andric   // the function adjusts the stack pointer during execution and the
16132754fe60SDimitry Andric   // adjustments aren't already part of our stack size estimate, our offset
16142754fe60SDimitry Andric   // calculations may be off, so be conservative.
16152754fe60SDimitry Andric   // FIXME: We could add logic to be more precise about negative offsets
16162754fe60SDimitry Andric   //        and which instructions will need a scratch register for them. Is it
16172754fe60SDimitry Andric   //        worth the effort and added fragility?
16183ca95b02SDimitry Andric   unsigned EstimatedStackSize =
16193ca95b02SDimitry Andric       MFI->estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
16203ca95b02SDimitry Andric   if (hasFP(MF)) {
16213ca95b02SDimitry Andric     if (AFI->hasStackFrame())
16223ca95b02SDimitry Andric       EstimatedStackSize += 4;
16233ca95b02SDimitry Andric   } else {
16243ca95b02SDimitry Andric     // If FP is not used, SP will be used to access arguments, so count the
16253ca95b02SDimitry Andric     // size of arguments into the estimation.
16263ca95b02SDimitry Andric     EstimatedStackSize += MF.getInfo<ARMFunctionInfo>()->getArgumentStackSize();
16273ca95b02SDimitry Andric   }
16283ca95b02SDimitry Andric   EstimatedStackSize += 16; // For possible paddings.
16293ca95b02SDimitry Andric 
16303ca95b02SDimitry Andric   bool BigStack = EstimatedStackSize >= estimateRSStackSizeLimit(MF, this) ||
16317d523365SDimitry Andric                   MFI->hasVarSizedObjects() ||
16327d523365SDimitry Andric                   (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
16332754fe60SDimitry Andric   bool ExtraCSSpill = false;
16342754fe60SDimitry Andric   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
16352754fe60SDimitry Andric     AFI->setHasStackFrame(true);
16362754fe60SDimitry Andric 
16372754fe60SDimitry Andric     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
16382754fe60SDimitry Andric     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
16392754fe60SDimitry Andric     if (!LRSpilled && CS1Spilled) {
1640875ed548SDimitry Andric       SavedRegs.set(ARM::LR);
16412754fe60SDimitry Andric       NumGPRSpills++;
1642f785676fSDimitry Andric       SmallVectorImpl<unsigned>::iterator LRPos;
1643f785676fSDimitry Andric       LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1644f785676fSDimitry Andric                         (unsigned)ARM::LR);
1645f785676fSDimitry Andric       if (LRPos != UnspilledCS1GPRs.end())
1646f785676fSDimitry Andric         UnspilledCS1GPRs.erase(LRPos);
1647f785676fSDimitry Andric 
16482754fe60SDimitry Andric       ForceLRSpill = false;
16492754fe60SDimitry Andric       ExtraCSSpill = true;
16502754fe60SDimitry Andric     }
16512754fe60SDimitry Andric 
16522754fe60SDimitry Andric     if (hasFP(MF)) {
1653875ed548SDimitry Andric       SavedRegs.set(FramePtr);
165491bc56edSDimitry Andric       auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
165591bc56edSDimitry Andric                              FramePtr);
165691bc56edSDimitry Andric       if (FPPos != UnspilledCS1GPRs.end())
165791bc56edSDimitry Andric         UnspilledCS1GPRs.erase(FPPos);
16582754fe60SDimitry Andric       NumGPRSpills++;
16592754fe60SDimitry Andric     }
16602754fe60SDimitry Andric 
16612754fe60SDimitry Andric     // If stack and double are 8-byte aligned and we are spilling an odd number
16622754fe60SDimitry Andric     // of GPRs, spill one extra callee save GPR so we won't have to pad between
16632754fe60SDimitry Andric     // the integer and double callee save areas.
16642754fe60SDimitry Andric     unsigned TargetAlign = getStackAlignment();
166539d628a0SDimitry Andric     if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
16662754fe60SDimitry Andric       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
16672754fe60SDimitry Andric         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
16682754fe60SDimitry Andric           unsigned Reg = UnspilledCS1GPRs[i];
16697d523365SDimitry Andric           // Don't spill high register if the function is thumb.  In the case of
16707d523365SDimitry Andric           // Windows on ARM, accept R11 (frame pointer)
1671ff0cc061SDimitry Andric           if (!AFI->isThumbFunction() ||
16727d523365SDimitry Andric               (STI.isTargetWindows() && Reg == ARM::R11) ||
16732754fe60SDimitry Andric               isARMLowRegister(Reg) || Reg == ARM::LR) {
1674875ed548SDimitry Andric             SavedRegs.set(Reg);
16753861d79fSDimitry Andric             if (!MRI.isReserved(Reg))
16762754fe60SDimitry Andric               ExtraCSSpill = true;
16772754fe60SDimitry Andric             break;
16782754fe60SDimitry Andric           }
16792754fe60SDimitry Andric         }
16802754fe60SDimitry Andric       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
16812754fe60SDimitry Andric         unsigned Reg = UnspilledCS2GPRs.front();
1682875ed548SDimitry Andric         SavedRegs.set(Reg);
16833861d79fSDimitry Andric         if (!MRI.isReserved(Reg))
16842754fe60SDimitry Andric           ExtraCSSpill = true;
16852754fe60SDimitry Andric       }
16862754fe60SDimitry Andric     }
16872754fe60SDimitry Andric 
16882754fe60SDimitry Andric     // Estimate if we might need to scavenge a register at some point in order
16892754fe60SDimitry Andric     // to materialize a stack offset. If so, either spill one additional
16902754fe60SDimitry Andric     // callee-saved register or reserve a special spill slot to facilitate
16912754fe60SDimitry Andric     // register scavenging. Thumb1 needs a spill slot for stack pointer
16922754fe60SDimitry Andric     // adjustments also, even when the frame itself is small.
16932754fe60SDimitry Andric     if (BigStack && !ExtraCSSpill) {
16942754fe60SDimitry Andric       // If any non-reserved CS register isn't spilled, just spill one or two
16952754fe60SDimitry Andric       // extra. That should take care of it!
16962754fe60SDimitry Andric       unsigned NumExtras = TargetAlign / 4;
16972754fe60SDimitry Andric       SmallVector<unsigned, 2> Extras;
16982754fe60SDimitry Andric       while (NumExtras && !UnspilledCS1GPRs.empty()) {
16992754fe60SDimitry Andric         unsigned Reg = UnspilledCS1GPRs.back();
17002754fe60SDimitry Andric         UnspilledCS1GPRs.pop_back();
17013861d79fSDimitry Andric         if (!MRI.isReserved(Reg) &&
17022754fe60SDimitry Andric             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
17032754fe60SDimitry Andric              Reg == ARM::LR)) {
17042754fe60SDimitry Andric           Extras.push_back(Reg);
17052754fe60SDimitry Andric           NumExtras--;
17062754fe60SDimitry Andric         }
17072754fe60SDimitry Andric       }
17082754fe60SDimitry Andric       // For non-Thumb1 functions, also check for hi-reg CS registers
17092754fe60SDimitry Andric       if (!AFI->isThumb1OnlyFunction()) {
17102754fe60SDimitry Andric         while (NumExtras && !UnspilledCS2GPRs.empty()) {
17112754fe60SDimitry Andric           unsigned Reg = UnspilledCS2GPRs.back();
17122754fe60SDimitry Andric           UnspilledCS2GPRs.pop_back();
17133861d79fSDimitry Andric           if (!MRI.isReserved(Reg)) {
17142754fe60SDimitry Andric             Extras.push_back(Reg);
17152754fe60SDimitry Andric             NumExtras--;
17162754fe60SDimitry Andric           }
17172754fe60SDimitry Andric         }
17182754fe60SDimitry Andric       }
17192754fe60SDimitry Andric       if (Extras.size() && NumExtras == 0) {
17202754fe60SDimitry Andric         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1721875ed548SDimitry Andric           SavedRegs.set(Extras[i]);
17222754fe60SDimitry Andric         }
17232754fe60SDimitry Andric       } else if (!AFI->isThumb1OnlyFunction()) {
17242754fe60SDimitry Andric         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
17252754fe60SDimitry Andric         // closest to SP or frame pointer.
17263ca95b02SDimitry Andric         assert(RS && "Register scavenging not provided");
17277ae0e2c9SDimitry Andric         const TargetRegisterClass *RC = &ARM::GPRRegClass;
1728139f7f9bSDimitry Andric         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
17292754fe60SDimitry Andric                                                            RC->getAlignment(),
17302754fe60SDimitry Andric                                                            false));
17312754fe60SDimitry Andric       }
17322754fe60SDimitry Andric     }
17332754fe60SDimitry Andric   }
17342754fe60SDimitry Andric 
17352754fe60SDimitry Andric   if (ForceLRSpill) {
1736875ed548SDimitry Andric     SavedRegs.set(ARM::LR);
17372754fe60SDimitry Andric     AFI->setLRIsSpilledForFarJump(true);
17382754fe60SDimitry Andric   }
17392754fe60SDimitry Andric }
1740139f7f9bSDimitry Andric 
17413ca95b02SDimitry Andric MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
17423ca95b02SDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
1743139f7f9bSDimitry Andric     MachineBasicBlock::iterator I) const {
1744139f7f9bSDimitry Andric   const ARMBaseInstrInfo &TII =
174539d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1746139f7f9bSDimitry Andric   if (!hasReservedCallFrame(MF)) {
1747139f7f9bSDimitry Andric     // If we have alloca, convert as follows:
1748139f7f9bSDimitry Andric     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1749139f7f9bSDimitry Andric     // ADJCALLSTACKUP   -> add, sp, sp, amount
17503ca95b02SDimitry Andric     MachineInstr &Old = *I;
17513ca95b02SDimitry Andric     DebugLoc dl = Old.getDebugLoc();
17523ca95b02SDimitry Andric     unsigned Amount = Old.getOperand(0).getImm();
1753139f7f9bSDimitry Andric     if (Amount != 0) {
1754139f7f9bSDimitry Andric       // We need to keep the stack aligned properly.  To do this, we round the
1755139f7f9bSDimitry Andric       // amount of space needed for the outgoing arguments up to the next
1756139f7f9bSDimitry Andric       // alignment boundary.
17577d523365SDimitry Andric       Amount = alignSPAdjust(Amount);
1758139f7f9bSDimitry Andric 
1759139f7f9bSDimitry Andric       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1760139f7f9bSDimitry Andric       assert(!AFI->isThumb1OnlyFunction() &&
1761139f7f9bSDimitry Andric              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1762139f7f9bSDimitry Andric       bool isARM = !AFI->isThumbFunction();
1763139f7f9bSDimitry Andric 
1764139f7f9bSDimitry Andric       // Replace the pseudo instruction with a new instruction...
17653ca95b02SDimitry Andric       unsigned Opc = Old.getOpcode();
17663ca95b02SDimitry Andric       int PIdx = Old.findFirstPredOperandIdx();
17673ca95b02SDimitry Andric       ARMCC::CondCodes Pred =
17683ca95b02SDimitry Andric           (PIdx == -1) ? ARMCC::AL
17693ca95b02SDimitry Andric                        : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
1770139f7f9bSDimitry Andric       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1771139f7f9bSDimitry Andric         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
17723ca95b02SDimitry Andric         unsigned PredReg = Old.getOperand(2).getReg();
1773139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1774139f7f9bSDimitry Andric                      Pred, PredReg);
1775139f7f9bSDimitry Andric       } else {
1776139f7f9bSDimitry Andric         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
17773ca95b02SDimitry Andric         unsigned PredReg = Old.getOperand(3).getReg();
1778139f7f9bSDimitry Andric         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1779139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1780139f7f9bSDimitry Andric                      Pred, PredReg);
1781139f7f9bSDimitry Andric       }
1782139f7f9bSDimitry Andric     }
1783139f7f9bSDimitry Andric   }
17843ca95b02SDimitry Andric   return MBB.erase(I);
1785139f7f9bSDimitry Andric }
1786139f7f9bSDimitry Andric 
178791bc56edSDimitry Andric /// Get the minimum constant for ARM that is greater than or equal to the
178891bc56edSDimitry Andric /// argument. In ARM, constants can have any value that can be produced by
178991bc56edSDimitry Andric /// rotating an 8-bit value to the right by an even number of bits within a
179091bc56edSDimitry Andric /// 32-bit word.
179191bc56edSDimitry Andric static uint32_t alignToARMConstant(uint32_t Value) {
179291bc56edSDimitry Andric   unsigned Shifted = 0;
179391bc56edSDimitry Andric 
179491bc56edSDimitry Andric   if (Value == 0)
179591bc56edSDimitry Andric       return 0;
179691bc56edSDimitry Andric 
179791bc56edSDimitry Andric   while (!(Value & 0xC0000000)) {
179891bc56edSDimitry Andric       Value = Value << 2;
179991bc56edSDimitry Andric       Shifted += 2;
180091bc56edSDimitry Andric   }
180191bc56edSDimitry Andric 
180291bc56edSDimitry Andric   bool Carry = (Value & 0x00FFFFFF);
180391bc56edSDimitry Andric   Value = ((Value & 0xFF000000) >> 24) + Carry;
180491bc56edSDimitry Andric 
180591bc56edSDimitry Andric   if (Value & 0x0000100)
180691bc56edSDimitry Andric       Value = Value & 0x000001FC;
180791bc56edSDimitry Andric 
180891bc56edSDimitry Andric   if (Shifted > 24)
180991bc56edSDimitry Andric       Value = Value >> (Shifted - 24);
181091bc56edSDimitry Andric   else
181191bc56edSDimitry Andric       Value = Value << (24 - Shifted);
181291bc56edSDimitry Andric 
181391bc56edSDimitry Andric   return Value;
181491bc56edSDimitry Andric }
181591bc56edSDimitry Andric 
181691bc56edSDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual
181791bc56edSDimitry Andric // stack limit.
181891bc56edSDimitry Andric static const uint64_t kSplitStackAvailable = 256;
181991bc56edSDimitry Andric 
182091bc56edSDimitry Andric // Adjust the function prologue to enable split stacks. This currently only
182191bc56edSDimitry Andric // supports android and linux.
182291bc56edSDimitry Andric //
182391bc56edSDimitry Andric // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
182491bc56edSDimitry Andric // must be well defined in order to allow for consistent implementations of the
182591bc56edSDimitry Andric // __morestack helper function. The ABI is also not a normal ABI in that it
182691bc56edSDimitry Andric // doesn't follow the normal calling conventions because this allows the
182791bc56edSDimitry Andric // prologue of each function to be optimized further.
182891bc56edSDimitry Andric //
182991bc56edSDimitry Andric // Currently, the ABI looks like (when calling __morestack)
183091bc56edSDimitry Andric //
183191bc56edSDimitry Andric //  * r4 holds the minimum stack size requested for this function call
183291bc56edSDimitry Andric //  * r5 holds the stack size of the arguments to the function
183391bc56edSDimitry Andric //  * the beginning of the function is 3 instructions after the call to
183491bc56edSDimitry Andric //    __morestack
183591bc56edSDimitry Andric //
183691bc56edSDimitry Andric // Implementations of __morestack should use r4 to allocate a new stack, r5 to
183791bc56edSDimitry Andric // place the arguments on to the new stack, and the 3-instruction knowledge to
183891bc56edSDimitry Andric // jump directly to the body of the function when working on the new stack.
183991bc56edSDimitry Andric //
184091bc56edSDimitry Andric // An old (and possibly no longer compatible) implementation of __morestack for
184191bc56edSDimitry Andric // ARM can be found at [1].
184291bc56edSDimitry Andric //
184391bc56edSDimitry Andric // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1844ff0cc061SDimitry Andric void ARMFrameLowering::adjustForSegmentedStacks(
1845ff0cc061SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
184691bc56edSDimitry Andric   unsigned Opcode;
184791bc56edSDimitry Andric   unsigned CFIIndex;
1848ff0cc061SDimitry Andric   const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
184991bc56edSDimitry Andric   bool Thumb = ST->isThumb();
185091bc56edSDimitry Andric 
185191bc56edSDimitry Andric   // Sadly, this currently doesn't support varargs, platforms other than
185291bc56edSDimitry Andric   // android/linux. Note that thumb1/thumb2 are support for android/linux.
185391bc56edSDimitry Andric   if (MF.getFunction()->isVarArg())
185491bc56edSDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
185591bc56edSDimitry Andric   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
185691bc56edSDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
185791bc56edSDimitry Andric 
185891bc56edSDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
185991bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
186091bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
186191bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
186291bc56edSDimitry Andric   const ARMBaseInstrInfo &TII =
186339d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
186491bc56edSDimitry Andric   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
186591bc56edSDimitry Andric   DebugLoc DL;
186691bc56edSDimitry Andric 
186791bc56edSDimitry Andric   uint64_t StackSize = MFI->getStackSize();
186891bc56edSDimitry Andric 
186991bc56edSDimitry Andric   // Do not generate a prologue for functions with a stack of size zero
187091bc56edSDimitry Andric   if (StackSize == 0)
187191bc56edSDimitry Andric     return;
187291bc56edSDimitry Andric 
187391bc56edSDimitry Andric   // Use R4 and R5 as scratch registers.
187491bc56edSDimitry Andric   // We save R4 and R5 before use and restore them before leaving the function.
187591bc56edSDimitry Andric   unsigned ScratchReg0 = ARM::R4;
187691bc56edSDimitry Andric   unsigned ScratchReg1 = ARM::R5;
187791bc56edSDimitry Andric   uint64_t AlignedStackSize;
187891bc56edSDimitry Andric 
187991bc56edSDimitry Andric   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
188091bc56edSDimitry Andric   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
188191bc56edSDimitry Andric   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
188291bc56edSDimitry Andric   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
188391bc56edSDimitry Andric   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
188491bc56edSDimitry Andric 
18857d523365SDimitry Andric   // Grab everything that reaches PrologueMBB to update there liveness as well.
18867d523365SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
18877d523365SDimitry Andric   SmallVector<MachineBasicBlock *, 2> WalkList;
18887d523365SDimitry Andric   WalkList.push_back(&PrologueMBB);
18897d523365SDimitry Andric 
18907d523365SDimitry Andric   do {
18917d523365SDimitry Andric     MachineBasicBlock *CurMBB = WalkList.pop_back_val();
18927d523365SDimitry Andric     for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
18937d523365SDimitry Andric       if (BeforePrologueRegion.insert(PredBB).second)
18947d523365SDimitry Andric         WalkList.push_back(PredBB);
18957d523365SDimitry Andric     }
18967d523365SDimitry Andric   } while (!WalkList.empty());
18977d523365SDimitry Andric 
18987d523365SDimitry Andric   // The order in that list is important.
18997d523365SDimitry Andric   // The blocks will all be inserted before PrologueMBB using that order.
19007d523365SDimitry Andric   // Therefore the block that should appear first in the CFG should appear
19017d523365SDimitry Andric   // first in the list.
19027d523365SDimitry Andric   MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
19037d523365SDimitry Andric                                       PostStackMBB};
19047d523365SDimitry Andric 
19057d523365SDimitry Andric   for (MachineBasicBlock *B : AddedBlocks)
19067d523365SDimitry Andric     BeforePrologueRegion.insert(B);
19077d523365SDimitry Andric 
19087d523365SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
19097d523365SDimitry Andric     for (MachineBasicBlock *PredBB : BeforePrologueRegion)
19107d523365SDimitry Andric       PredBB->addLiveIn(LI);
191191bc56edSDimitry Andric   }
191291bc56edSDimitry Andric 
19137d523365SDimitry Andric   // Remove the newly added blocks from the list, since we know
19147d523365SDimitry Andric   // we do not have to do the following updates for them.
19157d523365SDimitry Andric   for (MachineBasicBlock *B : AddedBlocks) {
19167d523365SDimitry Andric     BeforePrologueRegion.erase(B);
19177d523365SDimitry Andric     MF.insert(PrologueMBB.getIterator(), B);
19187d523365SDimitry Andric   }
19197d523365SDimitry Andric 
19207d523365SDimitry Andric   for (MachineBasicBlock *MBB : BeforePrologueRegion) {
19217d523365SDimitry Andric     // Make sure the LiveIns are still sorted and unique.
19227d523365SDimitry Andric     MBB->sortUniqueLiveIns();
19237d523365SDimitry Andric     // Replace the edges to PrologueMBB by edges to the sequences
19247d523365SDimitry Andric     // we are about to add.
19257d523365SDimitry Andric     MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
19267d523365SDimitry Andric   }
192791bc56edSDimitry Andric 
192891bc56edSDimitry Andric   // The required stack size that is aligned to ARM constant criterion.
192991bc56edSDimitry Andric   AlignedStackSize = alignToARMConstant(StackSize);
193091bc56edSDimitry Andric 
193191bc56edSDimitry Andric   // When the frame size is less than 256 we just compare the stack
193291bc56edSDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
193391bc56edSDimitry Andric   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
193491bc56edSDimitry Andric 
193591bc56edSDimitry Andric   // We will use two of the callee save registers as scratch registers so we
193691bc56edSDimitry Andric   // need to save those registers onto the stack.
193791bc56edSDimitry Andric   // We will use SR0 to hold stack limit and SR1 to hold the stack size
193891bc56edSDimitry Andric   // requested and arguments for __morestack().
193991bc56edSDimitry Andric   // SR0: Scratch Register #0
194091bc56edSDimitry Andric   // SR1: Scratch Register #1
194191bc56edSDimitry Andric   // push {SR0, SR1}
194291bc56edSDimitry Andric   if (Thumb) {
194391bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
194491bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
194591bc56edSDimitry Andric   } else {
194691bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
194791bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
194891bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
194991bc56edSDimitry Andric   }
195091bc56edSDimitry Andric 
195191bc56edSDimitry Andric   // Emit the relevant DWARF information about the change in stack pointer as
195291bc56edSDimitry Andric   // well as where to find both r4 and r5 (the callee-save registers)
195391bc56edSDimitry Andric   CFIIndex =
195491bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
195591bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
195691bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
195791bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
195891bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
195991bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
196091bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
196191bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
196291bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
196391bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
196491bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
196591bc56edSDimitry Andric 
196691bc56edSDimitry Andric   // mov SR1, sp
196791bc56edSDimitry Andric   if (Thumb) {
196891bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
196991bc56edSDimitry Andric                       .addReg(ARM::SP));
197091bc56edSDimitry Andric   } else if (CompareStackPointer) {
197191bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
197291bc56edSDimitry Andric                       .addReg(ARM::SP)).addReg(0);
197391bc56edSDimitry Andric   }
197491bc56edSDimitry Andric 
197591bc56edSDimitry Andric   // sub SR1, sp, #StackSize
197691bc56edSDimitry Andric   if (!CompareStackPointer && Thumb) {
197791bc56edSDimitry Andric     AddDefaultPred(
197891bc56edSDimitry Andric         AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
197991bc56edSDimitry Andric             .addReg(ScratchReg1).addImm(AlignedStackSize));
198091bc56edSDimitry Andric   } else if (!CompareStackPointer) {
198191bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
198291bc56edSDimitry Andric                       .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
198391bc56edSDimitry Andric   }
198491bc56edSDimitry Andric 
198591bc56edSDimitry Andric   if (Thumb && ST->isThumb1Only()) {
198691bc56edSDimitry Andric     unsigned PCLabelId = ARMFI->createPICLabelUId();
198791bc56edSDimitry Andric     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
198891bc56edSDimitry Andric         MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
198991bc56edSDimitry Andric     MachineConstantPool *MCP = MF.getConstantPool();
19907d523365SDimitry Andric     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
199191bc56edSDimitry Andric 
199291bc56edSDimitry Andric     // ldr SR0, [pc, offset(STACK_LIMIT)]
199391bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
199491bc56edSDimitry Andric                       .addConstantPoolIndex(CPI));
199591bc56edSDimitry Andric 
199691bc56edSDimitry Andric     // ldr SR0, [SR0]
199791bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
199891bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(0));
199991bc56edSDimitry Andric   } else {
200091bc56edSDimitry Andric     // Get TLS base address from the coprocessor
200191bc56edSDimitry Andric     // mrc p15, #0, SR0, c13, c0, #3
200291bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
200391bc56edSDimitry Andric                      .addImm(15)
200491bc56edSDimitry Andric                      .addImm(0)
200591bc56edSDimitry Andric                      .addImm(13)
200691bc56edSDimitry Andric                      .addImm(0)
200791bc56edSDimitry Andric                      .addImm(3));
200891bc56edSDimitry Andric 
200991bc56edSDimitry Andric     // Use the last tls slot on android and a private field of the TCP on linux.
201091bc56edSDimitry Andric     assert(ST->isTargetAndroid() || ST->isTargetLinux());
201191bc56edSDimitry Andric     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
201291bc56edSDimitry Andric 
201391bc56edSDimitry Andric     // Get the stack limit from the right offset
201491bc56edSDimitry Andric     // ldr SR0, [sr0, #4 * TlsOffset]
201591bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
201691bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(4 * TlsOffset));
201791bc56edSDimitry Andric   }
201891bc56edSDimitry Andric 
201991bc56edSDimitry Andric   // Compare stack limit with stack size requested.
202091bc56edSDimitry Andric   // cmp SR0, SR1
202191bc56edSDimitry Andric   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
202291bc56edSDimitry Andric   AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
202391bc56edSDimitry Andric                     .addReg(ScratchReg0)
202491bc56edSDimitry Andric                     .addReg(ScratchReg1));
202591bc56edSDimitry Andric 
202691bc56edSDimitry Andric   // This jump is taken if StackLimit < SP - stack required.
202791bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
202891bc56edSDimitry Andric   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
202991bc56edSDimitry Andric        .addImm(ARMCC::LO)
203091bc56edSDimitry Andric        .addReg(ARM::CPSR);
203191bc56edSDimitry Andric 
203291bc56edSDimitry Andric 
203391bc56edSDimitry Andric   // Calling __morestack(StackSize, Size of stack arguments).
203491bc56edSDimitry Andric   // __morestack knows that the stack size requested is in SR0(r4)
203591bc56edSDimitry Andric   // and amount size of stack arguments is in SR1(r5).
203691bc56edSDimitry Andric 
203791bc56edSDimitry Andric   // Pass first argument for the __morestack by Scratch Register #0.
203891bc56edSDimitry Andric   //   The amount size of stack required
203991bc56edSDimitry Andric   if (Thumb) {
204091bc56edSDimitry Andric     AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
204191bc56edSDimitry Andric                                         ScratchReg0)).addImm(AlignedStackSize));
204291bc56edSDimitry Andric   } else {
204391bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
204491bc56edSDimitry Andric                       .addImm(AlignedStackSize)).addReg(0);
204591bc56edSDimitry Andric   }
204691bc56edSDimitry Andric   // Pass second argument for the __morestack by Scratch Register #1.
204791bc56edSDimitry Andric   //   The amount size of stack consumed to save function arguments.
204891bc56edSDimitry Andric   if (Thumb) {
204991bc56edSDimitry Andric     AddDefaultPred(
205091bc56edSDimitry Andric         AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
205191bc56edSDimitry Andric             .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
205291bc56edSDimitry Andric   } else {
205391bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
205491bc56edSDimitry Andric                    .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
205591bc56edSDimitry Andric                    .addReg(0);
205691bc56edSDimitry Andric   }
205791bc56edSDimitry Andric 
205891bc56edSDimitry Andric   // push {lr} - Save return address of this function.
205991bc56edSDimitry Andric   if (Thumb) {
206091bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
206191bc56edSDimitry Andric         .addReg(ARM::LR);
206291bc56edSDimitry Andric   } else {
206391bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
206491bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
206591bc56edSDimitry Andric                    .addReg(ARM::SP))
206691bc56edSDimitry Andric         .addReg(ARM::LR);
206791bc56edSDimitry Andric   }
206891bc56edSDimitry Andric 
206991bc56edSDimitry Andric   // Emit the DWARF info about the change in stack as well as where to find the
207091bc56edSDimitry Andric   // previous link register
207191bc56edSDimitry Andric   CFIIndex =
207291bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
207391bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
207491bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
207591bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
207691bc56edSDimitry Andric         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
207791bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
207891bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
207991bc56edSDimitry Andric 
208091bc56edSDimitry Andric   // Call __morestack().
208191bc56edSDimitry Andric   if (Thumb) {
208291bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
208391bc56edSDimitry Andric         .addExternalSymbol("__morestack");
208491bc56edSDimitry Andric   } else {
208591bc56edSDimitry Andric     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
208691bc56edSDimitry Andric         .addExternalSymbol("__morestack");
208791bc56edSDimitry Andric   }
208891bc56edSDimitry Andric 
208991bc56edSDimitry Andric   // pop {lr} - Restore return address of this original function.
209091bc56edSDimitry Andric   if (Thumb) {
209191bc56edSDimitry Andric     if (ST->isThumb1Only()) {
209291bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
209391bc56edSDimitry Andric                      .addReg(ScratchReg0);
209491bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
209591bc56edSDimitry Andric                      .addReg(ScratchReg0));
209691bc56edSDimitry Andric     } else {
209791bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
209891bc56edSDimitry Andric                      .addReg(ARM::LR, RegState::Define)
209991bc56edSDimitry Andric                      .addReg(ARM::SP, RegState::Define)
210091bc56edSDimitry Andric                      .addReg(ARM::SP)
210191bc56edSDimitry Andric                      .addImm(4));
210291bc56edSDimitry Andric     }
210391bc56edSDimitry Andric   } else {
210491bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
210591bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
210691bc56edSDimitry Andric                    .addReg(ARM::SP))
210791bc56edSDimitry Andric       .addReg(ARM::LR);
210891bc56edSDimitry Andric   }
210991bc56edSDimitry Andric 
211091bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was called.
211191bc56edSDimitry Andric   // __morestack() will skip PostStackMBB block so we need to restore
211291bc56edSDimitry Andric   // scratch registers from here.
211391bc56edSDimitry Andric   // pop {SR0, SR1}
211491bc56edSDimitry Andric   if (Thumb) {
211591bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
211691bc56edSDimitry Andric       .addReg(ScratchReg0)
211791bc56edSDimitry Andric       .addReg(ScratchReg1);
211891bc56edSDimitry Andric   } else {
211991bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
212091bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
212191bc56edSDimitry Andric                    .addReg(ARM::SP))
212291bc56edSDimitry Andric       .addReg(ScratchReg0)
212391bc56edSDimitry Andric       .addReg(ScratchReg1);
212491bc56edSDimitry Andric   }
212591bc56edSDimitry Andric 
212691bc56edSDimitry Andric   // Update the CFA offset now that we've popped
212791bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
212891bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
212991bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
213091bc56edSDimitry Andric 
213191bc56edSDimitry Andric   // bx lr - Return from this function.
213291bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
213391bc56edSDimitry Andric   AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
213491bc56edSDimitry Andric 
213591bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was not called.
213691bc56edSDimitry Andric   // pop {SR0, SR1}
213791bc56edSDimitry Andric   if (Thumb) {
213891bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
213991bc56edSDimitry Andric       .addReg(ScratchReg0)
214091bc56edSDimitry Andric       .addReg(ScratchReg1);
214191bc56edSDimitry Andric   } else {
214291bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
214391bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
214491bc56edSDimitry Andric                    .addReg(ARM::SP))
214591bc56edSDimitry Andric       .addReg(ScratchReg0)
214691bc56edSDimitry Andric       .addReg(ScratchReg1);
214791bc56edSDimitry Andric   }
214891bc56edSDimitry Andric 
214991bc56edSDimitry Andric   // Update the CFA offset now that we've popped
215091bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
215191bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
215291bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
215391bc56edSDimitry Andric 
215491bc56edSDimitry Andric   // Tell debuggers that r4 and r5 are now the same as they were in the
215591bc56edSDimitry Andric   // previous function, that they're the "Same Value".
215691bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
215791bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
215891bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
215991bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
216091bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
216191bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
216291bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
216391bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
216491bc56edSDimitry Andric 
216591bc56edSDimitry Andric   // Organizing MBB lists
2166ff0cc061SDimitry Andric   PostStackMBB->addSuccessor(&PrologueMBB);
216791bc56edSDimitry Andric 
216891bc56edSDimitry Andric   AllocMBB->addSuccessor(PostStackMBB);
216991bc56edSDimitry Andric 
217091bc56edSDimitry Andric   GetMBB->addSuccessor(PostStackMBB);
217191bc56edSDimitry Andric   GetMBB->addSuccessor(AllocMBB);
217291bc56edSDimitry Andric 
217391bc56edSDimitry Andric   McrMBB->addSuccessor(GetMBB);
217491bc56edSDimitry Andric 
217591bc56edSDimitry Andric   PrevStackMBB->addSuccessor(McrMBB);
217691bc56edSDimitry Andric 
21773ca95b02SDimitry Andric #ifdef EXPENSIVE_CHECKS
217891bc56edSDimitry Andric   MF.verify();
217991bc56edSDimitry Andric #endif
218091bc56edSDimitry Andric }
2181