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 
1012754fe60SDimitry Andric static bool isCSRestore(MachineInstr *MI,
1022754fe60SDimitry Andric                         const ARMBaseInstrInfo &TII,
10391bc56edSDimitry Andric                         const MCPhysReg *CSRegs) {
1042754fe60SDimitry Andric   // Integer spill area is handled with "pop".
105f785676fSDimitry Andric   if (isPopOpcode(MI->getOpcode())) {
1062754fe60SDimitry Andric     // The first two operands are predicates. The last two are
1072754fe60SDimitry Andric     // imp-def and imp-use of SP. Check everything in between.
1082754fe60SDimitry Andric     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
1092754fe60SDimitry Andric       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
1102754fe60SDimitry Andric         return false;
1112754fe60SDimitry Andric     return true;
1122754fe60SDimitry Andric   }
1136122f3e6SDimitry Andric   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
1146122f3e6SDimitry Andric        MI->getOpcode() == ARM::LDR_POST_REG ||
1152754fe60SDimitry Andric        MI->getOpcode() == ARM::t2LDR_POST) &&
1162754fe60SDimitry Andric       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
1172754fe60SDimitry Andric       MI->getOperand(1).getReg() == ARM::SP)
1182754fe60SDimitry Andric     return true;
1192754fe60SDimitry Andric 
1202754fe60SDimitry Andric   return false;
1212754fe60SDimitry Andric }
1222754fe60SDimitry Andric 
123f785676fSDimitry Andric static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
124f785676fSDimitry Andric                                  MachineBasicBlock::iterator &MBBI, DebugLoc dl,
125f785676fSDimitry Andric                                  const ARMBaseInstrInfo &TII, unsigned DestReg,
126f785676fSDimitry Andric                                  unsigned SrcReg, int NumBytes,
127f785676fSDimitry Andric                                  unsigned MIFlags = MachineInstr::NoFlags,
128f785676fSDimitry Andric                                  ARMCC::CondCodes Pred = ARMCC::AL,
129f785676fSDimitry Andric                                  unsigned PredReg = 0) {
1302754fe60SDimitry Andric   if (isARM)
131f785676fSDimitry Andric     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
132139f7f9bSDimitry Andric                             Pred, PredReg, TII, MIFlags);
1332754fe60SDimitry Andric   else
134f785676fSDimitry Andric     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
135139f7f9bSDimitry Andric                            Pred, PredReg, TII, MIFlags);
1362754fe60SDimitry Andric }
1372754fe60SDimitry Andric 
138f785676fSDimitry Andric static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
139f785676fSDimitry Andric                          MachineBasicBlock::iterator &MBBI, DebugLoc dl,
140f785676fSDimitry Andric                          const ARMBaseInstrInfo &TII, int NumBytes,
141f785676fSDimitry Andric                          unsigned MIFlags = MachineInstr::NoFlags,
142f785676fSDimitry Andric                          ARMCC::CondCodes Pred = ARMCC::AL,
143f785676fSDimitry Andric                          unsigned PredReg = 0) {
144f785676fSDimitry Andric   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
145f785676fSDimitry Andric                        MIFlags, Pred, PredReg);
146f785676fSDimitry Andric }
147f785676fSDimitry Andric 
14891bc56edSDimitry Andric static int sizeOfSPAdjustment(const MachineInstr *MI) {
14939d628a0SDimitry Andric   int RegSize;
15039d628a0SDimitry Andric   switch (MI->getOpcode()) {
15139d628a0SDimitry Andric   case ARM::VSTMDDB_UPD:
15239d628a0SDimitry Andric     RegSize = 8;
15339d628a0SDimitry Andric     break;
15439d628a0SDimitry Andric   case ARM::STMDB_UPD:
15539d628a0SDimitry Andric   case ARM::t2STMDB_UPD:
15639d628a0SDimitry Andric     RegSize = 4;
15739d628a0SDimitry Andric     break;
15839d628a0SDimitry Andric   case ARM::t2STR_PRE:
15939d628a0SDimitry Andric   case ARM::STR_PRE_IMM:
16039d628a0SDimitry Andric     return 4;
16139d628a0SDimitry Andric   default:
16239d628a0SDimitry Andric     llvm_unreachable("Unknown push or pop like instruction");
16339d628a0SDimitry Andric   }
16439d628a0SDimitry Andric 
16591bc56edSDimitry Andric   int count = 0;
16691bc56edSDimitry Andric   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
16791bc56edSDimitry Andric   // pred) so the list starts at 4.
16891bc56edSDimitry Andric   for (int i = MI->getNumOperands() - 1; i >= 4; --i)
16939d628a0SDimitry Andric     count += RegSize;
17091bc56edSDimitry Andric   return count;
17191bc56edSDimitry Andric }
17291bc56edSDimitry Andric 
17391bc56edSDimitry Andric static bool WindowsRequiresStackProbe(const MachineFunction &MF,
17491bc56edSDimitry Andric                                       size_t StackSizeInBytes) {
17591bc56edSDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
176ff0cc061SDimitry Andric   const Function *F = MF.getFunction();
177ff0cc061SDimitry Andric   unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
178ff0cc061SDimitry Andric   if (F->hasFnAttribute("stack-probe-size"))
179ff0cc061SDimitry Andric     F->getFnAttribute("stack-probe-size")
180ff0cc061SDimitry Andric         .getValueAsString()
181ff0cc061SDimitry Andric         .getAsInteger(0, StackProbeSize);
182ff0cc061SDimitry Andric   return StackSizeInBytes >= StackProbeSize;
18391bc56edSDimitry Andric }
18491bc56edSDimitry Andric 
18539d628a0SDimitry Andric namespace {
18639d628a0SDimitry Andric struct StackAdjustingInsts {
18739d628a0SDimitry Andric   struct InstInfo {
18839d628a0SDimitry Andric     MachineBasicBlock::iterator I;
18939d628a0SDimitry Andric     unsigned SPAdjust;
19039d628a0SDimitry Andric     bool BeforeFPSet;
19139d628a0SDimitry Andric   };
19239d628a0SDimitry Andric 
19339d628a0SDimitry Andric   SmallVector<InstInfo, 4> Insts;
19439d628a0SDimitry Andric 
19539d628a0SDimitry Andric   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
19639d628a0SDimitry Andric                bool BeforeFPSet = false) {
19739d628a0SDimitry Andric     InstInfo Info = {I, SPAdjust, BeforeFPSet};
19839d628a0SDimitry Andric     Insts.push_back(Info);
19939d628a0SDimitry Andric   }
20039d628a0SDimitry Andric 
20139d628a0SDimitry Andric   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
20239d628a0SDimitry Andric     auto Info = std::find_if(Insts.begin(), Insts.end(),
20339d628a0SDimitry Andric                              [&](InstInfo &Info) { return Info.I == I; });
20439d628a0SDimitry Andric     assert(Info != Insts.end() && "invalid sp adjusting instruction");
20539d628a0SDimitry Andric     Info->SPAdjust += ExtraBytes;
20639d628a0SDimitry Andric   }
20739d628a0SDimitry Andric 
20839d628a0SDimitry Andric   void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
20939d628a0SDimitry Andric                          DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
21039d628a0SDimitry Andric     unsigned CFAOffset = 0;
21139d628a0SDimitry Andric     for (auto &Info : Insts) {
21239d628a0SDimitry Andric       if (HasFP && !Info.BeforeFPSet)
21339d628a0SDimitry Andric         return;
21439d628a0SDimitry Andric 
21539d628a0SDimitry Andric       CFAOffset -= Info.SPAdjust;
21639d628a0SDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(
21739d628a0SDimitry Andric           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
21839d628a0SDimitry Andric       BuildMI(MBB, std::next(Info.I), dl,
21939d628a0SDimitry Andric               TII.get(TargetOpcode::CFI_INSTRUCTION))
22039d628a0SDimitry Andric               .addCFIIndex(CFIIndex)
22139d628a0SDimitry Andric               .setMIFlags(MachineInstr::FrameSetup);
22239d628a0SDimitry Andric     }
22339d628a0SDimitry Andric   }
22439d628a0SDimitry Andric };
2253dac3a9bSDimitry Andric }
22639d628a0SDimitry Andric 
22739d628a0SDimitry Andric /// Emit an instruction sequence that will align the address in
22839d628a0SDimitry Andric /// register Reg by zero-ing out the lower bits.  For versions of the
22939d628a0SDimitry Andric /// architecture that support Neon, this must be done in a single
23039d628a0SDimitry Andric /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
23139d628a0SDimitry Andric /// single instruction. That function only gets called when optimizing
23239d628a0SDimitry Andric /// spilling of D registers on a core with the Neon instruction set
23339d628a0SDimitry Andric /// present.
23439d628a0SDimitry Andric static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
23539d628a0SDimitry Andric                                      const TargetInstrInfo &TII,
23639d628a0SDimitry Andric                                      MachineBasicBlock &MBB,
23739d628a0SDimitry Andric                                      MachineBasicBlock::iterator MBBI,
23839d628a0SDimitry Andric                                      DebugLoc DL, const unsigned Reg,
23939d628a0SDimitry Andric                                      const unsigned Alignment,
24039d628a0SDimitry Andric                                      const bool MustBeSingleInstruction) {
241ff0cc061SDimitry Andric   const ARMSubtarget &AST =
242ff0cc061SDimitry Andric       static_cast<const ARMSubtarget &>(MF.getSubtarget());
24339d628a0SDimitry Andric   const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
24439d628a0SDimitry Andric   const unsigned AlignMask = Alignment - 1;
24539d628a0SDimitry Andric   const unsigned NrBitsToZero = countTrailingZeros(Alignment);
24639d628a0SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
24739d628a0SDimitry Andric   if (!AFI->isThumbFunction()) {
24839d628a0SDimitry Andric     // if the BFC instruction is available, use that to zero the lower
24939d628a0SDimitry Andric     // bits:
25039d628a0SDimitry Andric     //   bfc Reg, #0, log2(Alignment)
25139d628a0SDimitry Andric     // otherwise use BIC, if the mask to zero the required number of bits
25239d628a0SDimitry Andric     // can be encoded in the bic immediate field
25339d628a0SDimitry Andric     //   bic Reg, Reg, Alignment-1
25439d628a0SDimitry Andric     // otherwise, emit
25539d628a0SDimitry Andric     //   lsr Reg, Reg, log2(Alignment)
25639d628a0SDimitry Andric     //   lsl Reg, Reg, log2(Alignment)
25739d628a0SDimitry Andric     if (CanUseBFC) {
25839d628a0SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
25939d628a0SDimitry Andric                          .addReg(Reg, RegState::Kill)
26039d628a0SDimitry Andric                          .addImm(~AlignMask));
26139d628a0SDimitry Andric     } else if (AlignMask <= 255) {
26239d628a0SDimitry Andric       AddDefaultCC(
26339d628a0SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
26439d628a0SDimitry Andric                              .addReg(Reg, RegState::Kill)
26539d628a0SDimitry Andric                              .addImm(AlignMask)));
26639d628a0SDimitry Andric     } else {
26739d628a0SDimitry Andric       assert(!MustBeSingleInstruction &&
26839d628a0SDimitry Andric              "Shouldn't call emitAligningInstructions demanding a single "
26939d628a0SDimitry Andric              "instruction to be emitted for large stack alignment for a target "
27039d628a0SDimitry Andric              "without BFC.");
27139d628a0SDimitry Andric       AddDefaultCC(AddDefaultPred(
27239d628a0SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
27339d628a0SDimitry Andric               .addReg(Reg, RegState::Kill)
27439d628a0SDimitry Andric               .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
27539d628a0SDimitry Andric       AddDefaultCC(AddDefaultPred(
27639d628a0SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
27739d628a0SDimitry Andric               .addReg(Reg, RegState::Kill)
27839d628a0SDimitry Andric               .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
27939d628a0SDimitry Andric     }
28039d628a0SDimitry Andric   } else {
28139d628a0SDimitry Andric     // Since this is only reached for Thumb-2 targets, the BFC instruction
28239d628a0SDimitry Andric     // should always be available.
28339d628a0SDimitry Andric     assert(CanUseBFC);
28439d628a0SDimitry Andric     AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
28539d628a0SDimitry Andric                        .addReg(Reg, RegState::Kill)
28639d628a0SDimitry Andric                        .addImm(~AlignMask));
28739d628a0SDimitry Andric   }
28839d628a0SDimitry Andric }
28939d628a0SDimitry Andric 
290ff0cc061SDimitry Andric void ARMFrameLowering::emitPrologue(MachineFunction &MF,
291ff0cc061SDimitry Andric                                     MachineBasicBlock &MBB) const {
2922754fe60SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
2932754fe60SDimitry Andric   MachineFrameInfo  *MFI = MF.getFrameInfo();
2942754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
29591bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
29691bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
29791bc56edSDimitry Andric   const TargetMachine &TM = MF.getTarget();
29891bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
299ff0cc061SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
300ff0cc061SDimitry Andric   const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
3012754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
3022754fe60SDimitry Andric          "This emitPrologue does not support Thumb1!");
3032754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
304ff0cc061SDimitry Andric   unsigned Align = STI.getFrameLowering()->getStackAlignment();
305ff0cc061SDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
3062754fe60SDimitry Andric   unsigned NumBytes = MFI->getStackSize();
3072754fe60SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
3087d523365SDimitry Andric 
3097d523365SDimitry Andric   // Debug location must be unknown since the first debug location is used
3107d523365SDimitry Andric   // to determine the end of the prologue.
3117d523365SDimitry Andric   DebugLoc dl;
3127d523365SDimitry Andric 
3132754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
3142754fe60SDimitry Andric 
3152754fe60SDimitry Andric   // Determine the sizes of each callee-save spill areas and record which frame
3162754fe60SDimitry Andric   // belongs to which callee-save spill areas.
3172754fe60SDimitry Andric   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
3182754fe60SDimitry Andric   int FramePtrSpillFI = 0;
319dff0c46cSDimitry Andric   int D8SpillFI = 0;
320f8254f43SDimitry Andric 
3213861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
3223861d79fSDimitry Andric   // prologue/epilogue.
3237ae0e2c9SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
3247ae0e2c9SDimitry Andric     return;
3257ae0e2c9SDimitry Andric 
32639d628a0SDimitry Andric   StackAdjustingInsts DefCFAOffsetCandidates;
327ff0cc061SDimitry Andric   bool HasFP = hasFP(MF);
32839d628a0SDimitry Andric 
32991bc56edSDimitry Andric   // Allocate the vararg register save area.
33091bc56edSDimitry Andric   if (ArgRegsSaveSize) {
331284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
3323b0f4066SDimitry Andric                  MachineInstr::FrameSetup);
33339d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
33491bc56edSDimitry Andric   }
3352754fe60SDimitry Andric 
33691bc56edSDimitry Andric   if (!AFI->hasStackFrame() &&
33791bc56edSDimitry Andric       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
33891bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0) {
33991bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
3403b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
34139d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
34239d628a0SDimitry Andric                                      NumBytes - ArgRegsSaveSize, true);
34391bc56edSDimitry Andric     }
344ff0cc061SDimitry Andric     DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
3452754fe60SDimitry Andric     return;
3462754fe60SDimitry Andric   }
3472754fe60SDimitry Andric 
34891bc56edSDimitry Andric   // Determine spill area sizes.
3492754fe60SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
3502754fe60SDimitry Andric     unsigned Reg = CSI[i].getReg();
3512754fe60SDimitry Andric     int FI = CSI[i].getFrameIdx();
3522754fe60SDimitry Andric     switch (Reg) {
35391bc56edSDimitry Andric     case ARM::R8:
35491bc56edSDimitry Andric     case ARM::R9:
35591bc56edSDimitry Andric     case ARM::R10:
35691bc56edSDimitry Andric     case ARM::R11:
35791bc56edSDimitry Andric     case ARM::R12:
35891bc56edSDimitry Andric       if (STI.isTargetDarwin()) {
35991bc56edSDimitry Andric         GPRCS2Size += 4;
36091bc56edSDimitry Andric         break;
36191bc56edSDimitry Andric       }
36291bc56edSDimitry Andric       // fallthrough
363f785676fSDimitry Andric     case ARM::R0:
364f785676fSDimitry Andric     case ARM::R1:
365f785676fSDimitry Andric     case ARM::R2:
366f785676fSDimitry Andric     case ARM::R3:
3672754fe60SDimitry Andric     case ARM::R4:
3682754fe60SDimitry Andric     case ARM::R5:
3692754fe60SDimitry Andric     case ARM::R6:
3702754fe60SDimitry Andric     case ARM::R7:
3712754fe60SDimitry Andric     case ARM::LR:
3722754fe60SDimitry Andric       if (Reg == FramePtr)
3732754fe60SDimitry Andric         FramePtrSpillFI = FI;
3742754fe60SDimitry Andric       GPRCS1Size += 4;
3752754fe60SDimitry Andric       break;
3762754fe60SDimitry Andric     default:
377dff0c46cSDimitry Andric       // This is a DPR. Exclude the aligned DPRCS2 spills.
378dff0c46cSDimitry Andric       if (Reg == ARM::D8)
379dff0c46cSDimitry Andric         D8SpillFI = FI;
380f785676fSDimitry Andric       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
3812754fe60SDimitry Andric         DPRCSSize += 8;
3822754fe60SDimitry Andric     }
3832754fe60SDimitry Andric   }
3842754fe60SDimitry Andric 
3852754fe60SDimitry Andric   // Move past area 1.
38639d628a0SDimitry Andric   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
38739d628a0SDimitry Andric   if (GPRCS1Size > 0) {
38891bc56edSDimitry Andric     GPRCS1Push = LastPush = MBBI++;
38939d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
39039d628a0SDimitry Andric   }
3912754fe60SDimitry Andric 
3922754fe60SDimitry Andric   // Determine starting offsets of spill areas.
39339d628a0SDimitry Andric   unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
39439d628a0SDimitry Andric   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
39539d628a0SDimitry Andric   unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
39639d628a0SDimitry Andric   unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
39739d628a0SDimitry Andric   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
398f785676fSDimitry Andric   int FramePtrOffsetInPush = 0;
399f785676fSDimitry Andric   if (HasFP) {
40039d628a0SDimitry Andric     FramePtrOffsetInPush =
40139d628a0SDimitry Andric         MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
4022754fe60SDimitry Andric     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
4032754fe60SDimitry Andric                                 NumBytes);
404f785676fSDimitry Andric   }
4052754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
4062754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
4072754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
4082754fe60SDimitry Andric 
409f785676fSDimitry Andric   // Move past area 2.
41039d628a0SDimitry Andric   if (GPRCS2Size > 0) {
41191bc56edSDimitry Andric     GPRCS2Push = LastPush = MBBI++;
41239d628a0SDimitry Andric     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
41339d628a0SDimitry Andric   }
41439d628a0SDimitry Andric 
41539d628a0SDimitry Andric   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
41639d628a0SDimitry Andric   // .cfi_offset operations will reflect that.
41739d628a0SDimitry Andric   if (DPRGapSize) {
41839d628a0SDimitry Andric     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
41939d628a0SDimitry Andric     if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
42039d628a0SDimitry Andric       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
42139d628a0SDimitry Andric     else {
42239d628a0SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
42339d628a0SDimitry Andric                    MachineInstr::FrameSetup);
42439d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
42539d628a0SDimitry Andric     }
42639d628a0SDimitry Andric   }
427f785676fSDimitry Andric 
4282754fe60SDimitry Andric   // Move past area 3.
429dd6029ffSDimitry Andric   if (DPRCSSize > 0) {
430dd6029ffSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
431dd6029ffSDimitry Andric     // instructions in the prologue.
43239d628a0SDimitry Andric     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
43339d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
434f785676fSDimitry Andric       LastPush = MBBI++;
435dd6029ffSDimitry Andric     }
43639d628a0SDimitry Andric   }
4372754fe60SDimitry Andric 
438dff0c46cSDimitry Andric   // Move past the aligned DPRCS2 area.
439dff0c46cSDimitry Andric   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
440dff0c46cSDimitry Andric     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
441dff0c46cSDimitry Andric     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
442dff0c46cSDimitry Andric     // leaves the stack pointer pointing to the DPRCS2 area.
443dff0c46cSDimitry Andric     //
444dff0c46cSDimitry Andric     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
445dff0c46cSDimitry Andric     NumBytes += MFI->getObjectOffset(D8SpillFI);
446dff0c46cSDimitry Andric   } else
4472754fe60SDimitry Andric     NumBytes = DPRCSOffset;
448dff0c46cSDimitry Andric 
44991bc56edSDimitry Andric   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
45091bc56edSDimitry Andric     uint32_t NumWords = NumBytes >> 2;
45191bc56edSDimitry Andric 
45291bc56edSDimitry Andric     if (NumWords < 65536)
45391bc56edSDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
45491bc56edSDimitry Andric                      .addImm(NumWords)
45591bc56edSDimitry Andric                      .setMIFlags(MachineInstr::FrameSetup));
45691bc56edSDimitry Andric     else
45791bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
45891bc56edSDimitry Andric         .addImm(NumWords)
45991bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
46091bc56edSDimitry Andric 
46191bc56edSDimitry Andric     switch (TM.getCodeModel()) {
46291bc56edSDimitry Andric     case CodeModel::Small:
46391bc56edSDimitry Andric     case CodeModel::Medium:
46491bc56edSDimitry Andric     case CodeModel::Default:
46591bc56edSDimitry Andric     case CodeModel::Kernel:
46691bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
46791bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
46891bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
46991bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
47091bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
47191bc56edSDimitry Andric       break;
47291bc56edSDimitry Andric     case CodeModel::Large:
47391bc56edSDimitry Andric     case CodeModel::JITDefault:
47491bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
47591bc56edSDimitry Andric         .addExternalSymbol("__chkstk")
47691bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
47791bc56edSDimitry Andric 
47891bc56edSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
47991bc56edSDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0)
48091bc56edSDimitry Andric         .addReg(ARM::R12, RegState::Kill)
48191bc56edSDimitry Andric         .addReg(ARM::R4, RegState::Implicit)
48291bc56edSDimitry Andric         .setMIFlags(MachineInstr::FrameSetup);
48391bc56edSDimitry Andric       break;
48491bc56edSDimitry Andric     }
48591bc56edSDimitry Andric 
48691bc56edSDimitry Andric     AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
48791bc56edSDimitry Andric                                         ARM::SP)
48891bc56edSDimitry Andric                                 .addReg(ARM::SP, RegState::Define)
48991bc56edSDimitry Andric                                 .addReg(ARM::R4, RegState::Kill)
49091bc56edSDimitry Andric                                 .setMIFlags(MachineInstr::FrameSetup)));
49191bc56edSDimitry Andric     NumBytes = 0;
49291bc56edSDimitry Andric   }
49391bc56edSDimitry Andric 
4942754fe60SDimitry Andric   if (NumBytes) {
4952754fe60SDimitry Andric     // Adjust SP after all the callee-save spills.
4967d523365SDimitry Andric     if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
4977d523365SDimitry Andric         tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
49839d628a0SDimitry Andric       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
49939d628a0SDimitry Andric     else {
5003b0f4066SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
5013b0f4066SDimitry Andric                    MachineInstr::FrameSetup);
50239d628a0SDimitry Andric       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
50339d628a0SDimitry Andric     }
504f785676fSDimitry Andric 
5052754fe60SDimitry Andric     if (HasFP && isARM)
5062754fe60SDimitry Andric       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
5072754fe60SDimitry Andric       // Note it's not safe to do this in Thumb2 mode because it would have
5082754fe60SDimitry Andric       // taken two instructions:
5092754fe60SDimitry Andric       // mov sp, r7
5102754fe60SDimitry Andric       // sub sp, #24
5112754fe60SDimitry Andric       // If an interrupt is taken between the two instructions, then sp is in
5122754fe60SDimitry Andric       // an inconsistent state (pointing to the middle of callee-saved area).
5132754fe60SDimitry Andric       // The interrupt handler can end up clobbering the registers.
5142754fe60SDimitry Andric       AFI->setShouldRestoreSPFromFP(true);
5152754fe60SDimitry Andric   }
5162754fe60SDimitry Andric 
51739d628a0SDimitry Andric   // Set FP to point to the stack slot that contains the previous FP.
51839d628a0SDimitry Andric   // For iOS, FP is R7, which has now been stored in spill area 1.
51939d628a0SDimitry Andric   // Otherwise, if this is not iOS, all the callee-saved registers go
52039d628a0SDimitry Andric   // into spill area 1, including the FP in R11.  In either case, it
52139d628a0SDimitry Andric   // is in area one and the adjustment needs to take place just after
52239d628a0SDimitry Andric   // that push.
52339d628a0SDimitry Andric   if (HasFP) {
52439d628a0SDimitry Andric     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
52539d628a0SDimitry Andric     unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
52639d628a0SDimitry Andric     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
52739d628a0SDimitry Andric                          dl, TII, FramePtr, ARM::SP,
52839d628a0SDimitry Andric                          PushSize + FramePtrOffsetInPush,
52939d628a0SDimitry Andric                          MachineInstr::FrameSetup);
53039d628a0SDimitry Andric     if (FramePtrOffsetInPush + PushSize != 0) {
53139d628a0SDimitry Andric       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
53239d628a0SDimitry Andric           nullptr, MRI->getDwarfRegNum(FramePtr, true),
53339d628a0SDimitry Andric           -(ArgRegsSaveSize - FramePtrOffsetInPush)));
53439d628a0SDimitry Andric       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
53539d628a0SDimitry Andric           .addCFIIndex(CFIIndex)
53639d628a0SDimitry Andric           .setMIFlags(MachineInstr::FrameSetup);
53739d628a0SDimitry Andric     } else {
53839d628a0SDimitry Andric       unsigned CFIIndex =
53939d628a0SDimitry Andric           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
54039d628a0SDimitry Andric               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
54139d628a0SDimitry Andric       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
54239d628a0SDimitry Andric           .addCFIIndex(CFIIndex)
54339d628a0SDimitry Andric           .setMIFlags(MachineInstr::FrameSetup);
54439d628a0SDimitry Andric     }
54539d628a0SDimitry Andric   }
54639d628a0SDimitry Andric 
54739d628a0SDimitry Andric   // Now that the prologue's actual instructions are finalised, we can insert
54839d628a0SDimitry Andric   // the necessary DWARF cf instructions to describe the situation. Start by
54939d628a0SDimitry Andric   // recording where each register ended up:
55039d628a0SDimitry Andric   if (GPRCS1Size > 0) {
55139d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
55239d628a0SDimitry Andric     int CFIIndex;
55391bc56edSDimitry Andric     for (const auto &Entry : CSI) {
55491bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
55591bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
55691bc56edSDimitry Andric       switch (Reg) {
55791bc56edSDimitry Andric       case ARM::R8:
55891bc56edSDimitry Andric       case ARM::R9:
55991bc56edSDimitry Andric       case ARM::R10:
56091bc56edSDimitry Andric       case ARM::R11:
56191bc56edSDimitry Andric       case ARM::R12:
56291bc56edSDimitry Andric         if (STI.isTargetDarwin())
56391bc56edSDimitry Andric           break;
56491bc56edSDimitry Andric         // fallthrough
56591bc56edSDimitry Andric       case ARM::R0:
56691bc56edSDimitry Andric       case ARM::R1:
56791bc56edSDimitry Andric       case ARM::R2:
56891bc56edSDimitry Andric       case ARM::R3:
56991bc56edSDimitry Andric       case ARM::R4:
57091bc56edSDimitry Andric       case ARM::R5:
57191bc56edSDimitry Andric       case ARM::R6:
57291bc56edSDimitry Andric       case ARM::R7:
57391bc56edSDimitry Andric       case ARM::LR:
57491bc56edSDimitry Andric         CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
57591bc56edSDimitry Andric             nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
57691bc56edSDimitry Andric         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
57739d628a0SDimitry Andric             .addCFIIndex(CFIIndex)
57839d628a0SDimitry Andric             .setMIFlags(MachineInstr::FrameSetup);
57991bc56edSDimitry Andric         break;
58091bc56edSDimitry Andric       }
58191bc56edSDimitry Andric     }
58291bc56edSDimitry Andric   }
58391bc56edSDimitry Andric 
58491bc56edSDimitry Andric   if (GPRCS2Size > 0) {
58539d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
58691bc56edSDimitry Andric     for (const auto &Entry : CSI) {
58791bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
58891bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
58991bc56edSDimitry Andric       switch (Reg) {
59091bc56edSDimitry Andric       case ARM::R8:
59191bc56edSDimitry Andric       case ARM::R9:
59291bc56edSDimitry Andric       case ARM::R10:
59391bc56edSDimitry Andric       case ARM::R11:
59491bc56edSDimitry Andric       case ARM::R12:
59591bc56edSDimitry Andric         if (STI.isTargetDarwin()) {
59691bc56edSDimitry Andric           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
59791bc56edSDimitry Andric           unsigned Offset = MFI->getObjectOffset(FI);
59891bc56edSDimitry Andric           unsigned CFIIndex = MMI.addFrameInst(
59991bc56edSDimitry Andric               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
60091bc56edSDimitry Andric           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
60139d628a0SDimitry Andric               .addCFIIndex(CFIIndex)
60239d628a0SDimitry Andric               .setMIFlags(MachineInstr::FrameSetup);
60391bc56edSDimitry Andric         }
60491bc56edSDimitry Andric         break;
60591bc56edSDimitry Andric       }
60691bc56edSDimitry Andric     }
60791bc56edSDimitry Andric   }
60891bc56edSDimitry Andric 
60991bc56edSDimitry Andric   if (DPRCSSize > 0) {
61091bc56edSDimitry Andric     // Since vpush register list cannot have gaps, there may be multiple vpush
61191bc56edSDimitry Andric     // instructions in the prologue.
61239d628a0SDimitry Andric     MachineBasicBlock::iterator Pos = std::next(LastPush);
61391bc56edSDimitry Andric     for (const auto &Entry : CSI) {
61491bc56edSDimitry Andric       unsigned Reg = Entry.getReg();
61591bc56edSDimitry Andric       int FI = Entry.getFrameIdx();
61691bc56edSDimitry Andric       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
61791bc56edSDimitry Andric           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
61891bc56edSDimitry Andric         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
61991bc56edSDimitry Andric         unsigned Offset = MFI->getObjectOffset(FI);
62091bc56edSDimitry Andric         unsigned CFIIndex = MMI.addFrameInst(
62191bc56edSDimitry Andric             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
62239d628a0SDimitry Andric         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
62339d628a0SDimitry Andric             .addCFIIndex(CFIIndex)
62439d628a0SDimitry Andric             .setMIFlags(MachineInstr::FrameSetup);
62591bc56edSDimitry Andric       }
62691bc56edSDimitry Andric     }
62791bc56edSDimitry Andric   }
62891bc56edSDimitry Andric 
62939d628a0SDimitry Andric   // Now we can emit descriptions of where the canonical frame address was
63039d628a0SDimitry Andric   // throughout the process. If we have a frame pointer, it takes over the job
63139d628a0SDimitry Andric   // half-way through, so only the first few .cfi_def_cfa_offset instructions
63239d628a0SDimitry Andric   // actually get emitted.
63339d628a0SDimitry Andric   DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
634f785676fSDimitry Andric 
6352754fe60SDimitry Andric   if (STI.isTargetELF() && hasFP(MF))
6362754fe60SDimitry Andric     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
6372754fe60SDimitry Andric                              AFI->getFramePtrSpillOffset());
6382754fe60SDimitry Andric 
6392754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
6402754fe60SDimitry Andric   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
64139d628a0SDimitry Andric   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
6422754fe60SDimitry Andric   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
6432754fe60SDimitry Andric 
6442754fe60SDimitry Andric   // If we need dynamic stack realignment, do it here. Be paranoid and make
6452754fe60SDimitry Andric   // sure if we also have VLAs, we have a base pointer for frame access.
646dff0c46cSDimitry Andric   // If aligned NEON registers were spilled, the stack has already been
647dff0c46cSDimitry Andric   // realigned.
648dff0c46cSDimitry Andric   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
6492754fe60SDimitry Andric     unsigned MaxAlign = MFI->getMaxAlignment();
6502754fe60SDimitry Andric     assert(!AFI->isThumb1OnlyFunction());
6512754fe60SDimitry Andric     if (!AFI->isThumbFunction()) {
65239d628a0SDimitry Andric       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
65339d628a0SDimitry Andric                                false);
6542754fe60SDimitry Andric     } else {
65539d628a0SDimitry Andric       // We cannot use sp as source/dest register here, thus we're using r4 to
65639d628a0SDimitry Andric       // perform the calculations. We're emitting the following sequence:
6572754fe60SDimitry Andric       // mov r4, sp
65839d628a0SDimitry Andric       // -- use emitAligningInstructions to produce best sequence to zero
65939d628a0SDimitry Andric       // -- out lower bits in r4
6602754fe60SDimitry Andric       // mov sp, r4
6612754fe60SDimitry Andric       // FIXME: It will be better just to find spare register here.
66217a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
66317a519f9SDimitry Andric                          .addReg(ARM::SP, RegState::Kill));
66439d628a0SDimitry Andric       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
66539d628a0SDimitry Andric                                false);
66617a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
66717a519f9SDimitry Andric                          .addReg(ARM::R4, RegState::Kill));
6682754fe60SDimitry Andric     }
6692754fe60SDimitry Andric 
6702754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
6712754fe60SDimitry Andric   }
6722754fe60SDimitry Andric 
6732754fe60SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
6742754fe60SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
6752754fe60SDimitry Andric   // will be allocated after this, so we can still use the base pointer
6762754fe60SDimitry Andric   // to reference locals.
6773b0f4066SDimitry Andric   // FIXME: Clarify FrameSetup flags here.
6782754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
6792754fe60SDimitry Andric     if (isARM)
6802754fe60SDimitry Andric       BuildMI(MBB, MBBI, dl,
6812754fe60SDimitry Andric               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
6822754fe60SDimitry Andric         .addReg(ARM::SP)
6832754fe60SDimitry Andric         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6842754fe60SDimitry Andric     else
68517a519f9SDimitry Andric       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
68617a519f9SDimitry Andric                              RegInfo->getBaseRegister())
68717a519f9SDimitry Andric         .addReg(ARM::SP));
6882754fe60SDimitry Andric   }
6892754fe60SDimitry Andric 
6902754fe60SDimitry Andric   // If the frame has variable sized objects then the epilogue must restore
6912754fe60SDimitry Andric   // the sp from fp. We can assume there's an FP here since hasFP already
6922754fe60SDimitry Andric   // checks for hasVarSizedObjects.
6932754fe60SDimitry Andric   if (MFI->hasVarSizedObjects())
6942754fe60SDimitry Andric     AFI->setShouldRestoreSPFromFP(true);
6952754fe60SDimitry Andric }
6962754fe60SDimitry Andric 
6979cac79b3SDimitry Andric void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
6989cac79b3SDimitry Andric                                     MachineBasicBlock &MBB) const {
6992754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
7002754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
70139d628a0SDimitry Andric   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
7022754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
70339d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
7042754fe60SDimitry Andric   assert(!AFI->isThumb1OnlyFunction() &&
7052754fe60SDimitry Andric          "This emitEpilogue does not support Thumb1!");
7062754fe60SDimitry Andric   bool isARM = !AFI->isThumbFunction();
7072754fe60SDimitry Andric 
708ff0cc061SDimitry Andric   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
7092754fe60SDimitry Andric   int NumBytes = (int)MFI->getStackSize();
7102754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
7112754fe60SDimitry Andric 
7123861d79fSDimitry Andric   // All calls are tail calls in GHC calling conv, and functions have no
7133861d79fSDimitry Andric   // prologue/epilogue.
7147d523365SDimitry Andric   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
7157ae0e2c9SDimitry Andric     return;
7167d523365SDimitry Andric 
7177d523365SDimitry Andric   // First put ourselves on the first (from top) terminator instructions.
7187d523365SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
7197d523365SDimitry Andric   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
7207ae0e2c9SDimitry Andric 
7212754fe60SDimitry Andric   if (!AFI->hasStackFrame()) {
72291bc56edSDimitry Andric     if (NumBytes - ArgRegsSaveSize != 0)
72391bc56edSDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
7242754fe60SDimitry Andric   } else {
7252754fe60SDimitry Andric     // Unwind MBBI to point to first LDR / VLDRD.
72691bc56edSDimitry Andric     const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
7272754fe60SDimitry Andric     if (MBBI != MBB.begin()) {
728f785676fSDimitry Andric       do {
7292754fe60SDimitry Andric         --MBBI;
730f785676fSDimitry Andric       } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
7312754fe60SDimitry Andric       if (!isCSRestore(MBBI, TII, CSRegs))
7322754fe60SDimitry Andric         ++MBBI;
7332754fe60SDimitry Andric     }
7342754fe60SDimitry Andric 
7352754fe60SDimitry Andric     // Move SP to start of FP callee save spill area.
73691bc56edSDimitry Andric     NumBytes -= (ArgRegsSaveSize +
73791bc56edSDimitry Andric                  AFI->getGPRCalleeSavedArea1Size() +
7382754fe60SDimitry Andric                  AFI->getGPRCalleeSavedArea2Size() +
73939d628a0SDimitry Andric                  AFI->getDPRCalleeSavedGapSize() +
7402754fe60SDimitry Andric                  AFI->getDPRCalleeSavedAreaSize());
7412754fe60SDimitry Andric 
7422754fe60SDimitry Andric     // Reset SP based on frame pointer only if the stack frame extends beyond
7432754fe60SDimitry Andric     // frame pointer stack slot or target is ELF and the function has FP.
7442754fe60SDimitry Andric     if (AFI->shouldRestoreSPFromFP()) {
7452754fe60SDimitry Andric       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
7462754fe60SDimitry Andric       if (NumBytes) {
7472754fe60SDimitry Andric         if (isARM)
7482754fe60SDimitry Andric           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
7492754fe60SDimitry Andric                                   ARMCC::AL, 0, TII);
7502754fe60SDimitry Andric         else {
7512754fe60SDimitry Andric           // It's not possible to restore SP from FP in a single instruction.
752dff0c46cSDimitry Andric           // For iOS, this looks like:
7532754fe60SDimitry Andric           // mov sp, r7
7542754fe60SDimitry Andric           // sub sp, #24
7552754fe60SDimitry Andric           // This is bad, if an interrupt is taken after the mov, sp is in an
7562754fe60SDimitry Andric           // inconsistent state.
7572754fe60SDimitry Andric           // Use the first callee-saved register as a scratch register.
758875ed548SDimitry Andric           assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
7592754fe60SDimitry Andric                  "No scratch register to restore SP from FP!");
7602754fe60SDimitry Andric           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
7612754fe60SDimitry Andric                                  ARMCC::AL, 0, TII);
76217a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
76317a519f9SDimitry Andric                                  ARM::SP)
76417a519f9SDimitry Andric             .addReg(ARM::R4));
7652754fe60SDimitry Andric         }
7662754fe60SDimitry Andric       } else {
7672754fe60SDimitry Andric         // Thumb2 or ARM.
7682754fe60SDimitry Andric         if (isARM)
7692754fe60SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
7702754fe60SDimitry Andric             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7712754fe60SDimitry Andric         else
77217a519f9SDimitry Andric           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
77317a519f9SDimitry Andric                                  ARM::SP)
77417a519f9SDimitry Andric             .addReg(FramePtr));
7752754fe60SDimitry Andric       }
77691bc56edSDimitry Andric     } else if (NumBytes &&
77791bc56edSDimitry Andric                !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
7782754fe60SDimitry Andric         emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
7792754fe60SDimitry Andric 
7802754fe60SDimitry Andric     // Increment past our save areas.
781dd6029ffSDimitry Andric     if (AFI->getDPRCalleeSavedAreaSize()) {
782dd6029ffSDimitry Andric       MBBI++;
783dd6029ffSDimitry Andric       // Since vpop register list cannot have gaps, there may be multiple vpop
784dd6029ffSDimitry Andric       // instructions in the epilogue.
785dd6029ffSDimitry Andric       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
786dd6029ffSDimitry Andric         MBBI++;
787dd6029ffSDimitry Andric     }
78839d628a0SDimitry Andric     if (AFI->getDPRCalleeSavedGapSize()) {
78939d628a0SDimitry Andric       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
79039d628a0SDimitry Andric              "unexpected DPR alignment gap");
79139d628a0SDimitry Andric       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
79239d628a0SDimitry Andric     }
79339d628a0SDimitry Andric 
7942754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
7952754fe60SDimitry Andric     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
7962754fe60SDimitry Andric   }
7972754fe60SDimitry Andric 
798284c1978SDimitry Andric   if (ArgRegsSaveSize)
799284c1978SDimitry Andric     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
8002754fe60SDimitry Andric }
8012754fe60SDimitry Andric 
8022754fe60SDimitry Andric /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
8032754fe60SDimitry Andric /// debug info.  It's the same as what we use for resolving the code-gen
8042754fe60SDimitry Andric /// references for now.  FIXME: This can go wrong when references are
8052754fe60SDimitry Andric /// SP-relative and simple call frames aren't used.
8062754fe60SDimitry Andric int
8072754fe60SDimitry Andric ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
8082754fe60SDimitry Andric                                          unsigned &FrameReg) const {
8092754fe60SDimitry Andric   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
8102754fe60SDimitry Andric }
8112754fe60SDimitry Andric 
8122754fe60SDimitry Andric int
8132754fe60SDimitry Andric ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
8143b0f4066SDimitry Andric                                              int FI, unsigned &FrameReg,
8152754fe60SDimitry Andric                                              int SPAdj) const {
8162754fe60SDimitry Andric   const MachineFrameInfo *MFI = MF.getFrameInfo();
81739d628a0SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
81839d628a0SDimitry Andric       MF.getSubtarget().getRegisterInfo());
8192754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
8202754fe60SDimitry Andric   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
8212754fe60SDimitry Andric   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
8222754fe60SDimitry Andric   bool isFixed = MFI->isFixedObjectIndex(FI);
8232754fe60SDimitry Andric 
8242754fe60SDimitry Andric   FrameReg = ARM::SP;
8252754fe60SDimitry Andric   Offset += SPAdj;
8262754fe60SDimitry Andric 
827dff0c46cSDimitry Andric   // SP can move around if there are allocas.  We may also lose track of SP
828dff0c46cSDimitry Andric   // when emergency spilling inside a non-reserved call frame setup.
829dff0c46cSDimitry Andric   bool hasMovingSP = !hasReservedCallFrame(MF);
830dff0c46cSDimitry Andric 
8312754fe60SDimitry Andric   // When dynamically realigning the stack, use the frame pointer for
8322754fe60SDimitry Andric   // parameters, and the stack/base pointer for locals.
8332754fe60SDimitry Andric   if (RegInfo->needsStackRealignment(MF)) {
8342754fe60SDimitry Andric     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
8352754fe60SDimitry Andric     if (isFixed) {
8362754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8372754fe60SDimitry Andric       Offset = FPOffset;
838dff0c46cSDimitry Andric     } else if (hasMovingSP) {
8392754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) &&
8402754fe60SDimitry Andric              "VLAs and dynamic stack alignment, but missing base pointer!");
8412754fe60SDimitry Andric       FrameReg = RegInfo->getBaseRegister();
8422754fe60SDimitry Andric     }
8432754fe60SDimitry Andric     return Offset;
8442754fe60SDimitry Andric   }
8452754fe60SDimitry Andric 
8462754fe60SDimitry Andric   // If there is a frame pointer, use it when we can.
8472754fe60SDimitry Andric   if (hasFP(MF) && AFI->hasStackFrame()) {
8482754fe60SDimitry Andric     // Use frame pointer to reference fixed objects. Use it for locals if
8492754fe60SDimitry Andric     // there are VLAs (and thus the SP isn't reliable as a base).
850dff0c46cSDimitry Andric     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
8512754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8522754fe60SDimitry Andric       return FPOffset;
853dff0c46cSDimitry Andric     } else if (hasMovingSP) {
8542754fe60SDimitry Andric       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
8553b0f4066SDimitry Andric       if (AFI->isThumb2Function()) {
8562754fe60SDimitry Andric         // Try to use the frame pointer if we can, else use the base pointer
8572754fe60SDimitry Andric         // since it's available. This is handy for the emergency spill slot, in
8582754fe60SDimitry Andric         // particular.
8592754fe60SDimitry Andric         if (FPOffset >= -255 && FPOffset < 0) {
8602754fe60SDimitry Andric           FrameReg = RegInfo->getFrameRegister(MF);
8612754fe60SDimitry Andric           return FPOffset;
8622754fe60SDimitry Andric         }
8633b0f4066SDimitry Andric       }
8642754fe60SDimitry Andric     } else if (AFI->isThumb2Function()) {
8653b0f4066SDimitry Andric       // Use  add <rd>, sp, #<imm8>
8663b0f4066SDimitry Andric       //      ldr <rd>, [sp, #<imm8>]
8673b0f4066SDimitry Andric       // if at all possible to save space.
8683b0f4066SDimitry Andric       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
8693b0f4066SDimitry Andric         return Offset;
8702754fe60SDimitry Andric       // In Thumb2 mode, the negative offset is very limited. Try to avoid
8713b0f4066SDimitry Andric       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
8722754fe60SDimitry Andric       if (FPOffset >= -255 && FPOffset < 0) {
8732754fe60SDimitry Andric         FrameReg = RegInfo->getFrameRegister(MF);
8742754fe60SDimitry Andric         return FPOffset;
8752754fe60SDimitry Andric       }
8762754fe60SDimitry Andric     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
8772754fe60SDimitry Andric       // Otherwise, use SP or FP, whichever is closer to the stack slot.
8782754fe60SDimitry Andric       FrameReg = RegInfo->getFrameRegister(MF);
8792754fe60SDimitry Andric       return FPOffset;
8802754fe60SDimitry Andric     }
8812754fe60SDimitry Andric   }
8822754fe60SDimitry Andric   // Use the base pointer if we have one.
8832754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
8842754fe60SDimitry Andric     FrameReg = RegInfo->getBaseRegister();
8852754fe60SDimitry Andric   return Offset;
8862754fe60SDimitry Andric }
8872754fe60SDimitry Andric 
8882754fe60SDimitry Andric void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
8892754fe60SDimitry Andric                                     MachineBasicBlock::iterator MI,
8902754fe60SDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
8912754fe60SDimitry Andric                                     unsigned StmOpc, unsigned StrOpc,
8922754fe60SDimitry Andric                                     bool NoGap,
8933b0f4066SDimitry Andric                                     bool(*Func)(unsigned, bool),
894dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
8953b0f4066SDimitry Andric                                     unsigned MIFlags) const {
8962754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
89739d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8982754fe60SDimitry Andric 
8992754fe60SDimitry Andric   DebugLoc DL;
9002754fe60SDimitry Andric 
9012754fe60SDimitry Andric   SmallVector<std::pair<unsigned,bool>, 4> Regs;
9022754fe60SDimitry Andric   unsigned i = CSI.size();
9032754fe60SDimitry Andric   while (i != 0) {
9042754fe60SDimitry Andric     unsigned LastReg = 0;
9052754fe60SDimitry Andric     for (; i != 0; --i) {
9062754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
90791bc56edSDimitry Andric       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
908dff0c46cSDimitry Andric 
909dff0c46cSDimitry Andric       // D-registers in the aligned area DPRCS2 are NOT spilled here.
910dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
911dff0c46cSDimitry Andric         continue;
9122754fe60SDimitry Andric 
9132754fe60SDimitry Andric       // Add the callee-saved register as live-in unless it's LR and
9142754fe60SDimitry Andric       // @llvm.returnaddress is called. If LR is returned for
9152754fe60SDimitry Andric       // @llvm.returnaddress then it's already added to the function and
9162754fe60SDimitry Andric       // entry block live-in sets.
9172754fe60SDimitry Andric       bool isKill = true;
9182754fe60SDimitry Andric       if (Reg == ARM::LR) {
9192754fe60SDimitry Andric         if (MF.getFrameInfo()->isReturnAddressTaken() &&
9202754fe60SDimitry Andric             MF.getRegInfo().isLiveIn(Reg))
9212754fe60SDimitry Andric           isKill = false;
9222754fe60SDimitry Andric       }
9232754fe60SDimitry Andric 
9242754fe60SDimitry Andric       if (isKill)
9252754fe60SDimitry Andric         MBB.addLiveIn(Reg);
9262754fe60SDimitry Andric 
9272754fe60SDimitry Andric       // If NoGap is true, push consecutive registers and then leave the rest
9282754fe60SDimitry Andric       // for other instructions. e.g.
9292754fe60SDimitry Andric       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
9302754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
9312754fe60SDimitry Andric         break;
9322754fe60SDimitry Andric       LastReg = Reg;
9332754fe60SDimitry Andric       Regs.push_back(std::make_pair(Reg, isKill));
9342754fe60SDimitry Andric     }
9352754fe60SDimitry Andric 
9362754fe60SDimitry Andric     if (Regs.empty())
9372754fe60SDimitry Andric       continue;
9382754fe60SDimitry Andric     if (Regs.size() > 1 || StrOpc== 0) {
9392754fe60SDimitry Andric       MachineInstrBuilder MIB =
9402754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
9413b0f4066SDimitry Andric                        .addReg(ARM::SP).setMIFlags(MIFlags));
9422754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
9432754fe60SDimitry Andric         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
9442754fe60SDimitry Andric     } else if (Regs.size() == 1) {
9452754fe60SDimitry Andric       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
9462754fe60SDimitry Andric                                         ARM::SP)
9472754fe60SDimitry Andric         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
9486122f3e6SDimitry Andric         .addReg(ARM::SP).setMIFlags(MIFlags)
9496122f3e6SDimitry Andric         .addImm(-4);
9502754fe60SDimitry Andric       AddDefaultPred(MIB);
9512754fe60SDimitry Andric     }
9522754fe60SDimitry Andric     Regs.clear();
95391bc56edSDimitry Andric 
95491bc56edSDimitry Andric     // Put any subsequent vpush instructions before this one: they will refer to
95591bc56edSDimitry Andric     // higher register numbers so need to be pushed first in order to preserve
95691bc56edSDimitry Andric     // monotonicity.
9577d523365SDimitry Andric     if (MI != MBB.begin())
95891bc56edSDimitry Andric       --MI;
9592754fe60SDimitry Andric   }
9602754fe60SDimitry Andric }
9612754fe60SDimitry Andric 
9622754fe60SDimitry Andric void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
9632754fe60SDimitry Andric                                    MachineBasicBlock::iterator MI,
9642754fe60SDimitry Andric                                    const std::vector<CalleeSavedInfo> &CSI,
9652754fe60SDimitry Andric                                    unsigned LdmOpc, unsigned LdrOpc,
9662754fe60SDimitry Andric                                    bool isVarArg, bool NoGap,
967dff0c46cSDimitry Andric                                    bool(*Func)(unsigned, bool),
968dff0c46cSDimitry Andric                                    unsigned NumAlignedDPRCS2Regs) const {
9692754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
97039d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9712754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
9727d523365SDimitry Andric   DebugLoc DL;
9737d523365SDimitry Andric   bool isTailCall = false;
9747d523365SDimitry Andric   bool isInterrupt = false;
9757d523365SDimitry Andric   bool isTrap = false;
9767d523365SDimitry Andric   if (MBB.end() != MI) {
9777d523365SDimitry Andric     DL = MI->getDebugLoc();
9782754fe60SDimitry Andric     unsigned RetOpcode = MI->getOpcode();
9797d523365SDimitry Andric     isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
9807d523365SDimitry Andric     isInterrupt =
981f785676fSDimitry Andric         RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
9827d523365SDimitry Andric     isTrap =
9837d523365SDimitry Andric         RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
9847d523365SDimitry Andric         RetOpcode == ARM::tTRAP;
9857d523365SDimitry Andric   }
9862754fe60SDimitry Andric 
9872754fe60SDimitry Andric   SmallVector<unsigned, 4> Regs;
9882754fe60SDimitry Andric   unsigned i = CSI.size();
9892754fe60SDimitry Andric   while (i != 0) {
9902754fe60SDimitry Andric     unsigned LastReg = 0;
9912754fe60SDimitry Andric     bool DeleteRet = false;
9922754fe60SDimitry Andric     for (; i != 0; --i) {
9932754fe60SDimitry Andric       unsigned Reg = CSI[i-1].getReg();
99491bc56edSDimitry Andric       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
995dff0c46cSDimitry Andric 
996dff0c46cSDimitry Andric       // The aligned reloads from area DPRCS2 are not inserted here.
997dff0c46cSDimitry Andric       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
998dff0c46cSDimitry Andric         continue;
9992754fe60SDimitry Andric 
1000f785676fSDimitry Andric       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
10017d523365SDimitry Andric           !isTrap && STI.hasV5TOps()) {
10027d523365SDimitry Andric         if (MBB.succ_empty()) {
10032754fe60SDimitry Andric           Reg = ARM::PC;
10042754fe60SDimitry Andric           DeleteRet = true;
10057d523365SDimitry Andric           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
10067d523365SDimitry Andric         } else
10077d523365SDimitry Andric           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
10087d523365SDimitry Andric         // Fold the return instruction into the LDM.
10092754fe60SDimitry Andric       }
10102754fe60SDimitry Andric 
10112754fe60SDimitry Andric       // If NoGap is true, pop consecutive registers and then leave the rest
10122754fe60SDimitry Andric       // for other instructions. e.g.
10132754fe60SDimitry Andric       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
10142754fe60SDimitry Andric       if (NoGap && LastReg && LastReg != Reg-1)
10152754fe60SDimitry Andric         break;
10162754fe60SDimitry Andric 
10172754fe60SDimitry Andric       LastReg = Reg;
10182754fe60SDimitry Andric       Regs.push_back(Reg);
10192754fe60SDimitry Andric     }
10202754fe60SDimitry Andric 
10212754fe60SDimitry Andric     if (Regs.empty())
10222754fe60SDimitry Andric       continue;
10232754fe60SDimitry Andric     if (Regs.size() > 1 || LdrOpc == 0) {
10242754fe60SDimitry Andric       MachineInstrBuilder MIB =
10252754fe60SDimitry Andric         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
10262754fe60SDimitry Andric                        .addReg(ARM::SP));
10272754fe60SDimitry Andric       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
10282754fe60SDimitry Andric         MIB.addReg(Regs[i], getDefRegState(true));
10297d523365SDimitry Andric       if (DeleteRet && MI != MBB.end()) {
1030139f7f9bSDimitry Andric         MIB.copyImplicitOps(&*MI);
10312754fe60SDimitry Andric         MI->eraseFromParent();
10326122f3e6SDimitry Andric       }
10332754fe60SDimitry Andric       MI = MIB;
10342754fe60SDimitry Andric     } else if (Regs.size() == 1) {
10352754fe60SDimitry Andric       // If we adjusted the reg to PC from LR above, switch it back here. We
10362754fe60SDimitry Andric       // only do that for LDM.
10372754fe60SDimitry Andric       if (Regs[0] == ARM::PC)
10382754fe60SDimitry Andric         Regs[0] = ARM::LR;
10392754fe60SDimitry Andric       MachineInstrBuilder MIB =
10402754fe60SDimitry Andric         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
10412754fe60SDimitry Andric           .addReg(ARM::SP, RegState::Define)
10422754fe60SDimitry Andric           .addReg(ARM::SP);
10432754fe60SDimitry Andric       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
10442754fe60SDimitry Andric       // that refactoring is complete (eventually).
10456122f3e6SDimitry Andric       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
10462754fe60SDimitry Andric         MIB.addReg(0);
10472754fe60SDimitry Andric         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
10482754fe60SDimitry Andric       } else
10492754fe60SDimitry Andric         MIB.addImm(4);
10502754fe60SDimitry Andric       AddDefaultPred(MIB);
10512754fe60SDimitry Andric     }
10522754fe60SDimitry Andric     Regs.clear();
105391bc56edSDimitry Andric 
105491bc56edSDimitry Andric     // Put any subsequent vpop instructions after this one: they will refer to
105591bc56edSDimitry Andric     // higher register numbers so need to be popped afterwards.
10567d523365SDimitry Andric     if (MI != MBB.end())
105791bc56edSDimitry Andric       ++MI;
10582754fe60SDimitry Andric   }
10592754fe60SDimitry Andric }
10602754fe60SDimitry Andric 
1061dff0c46cSDimitry Andric /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1062dff0c46cSDimitry Andric /// starting from d8.  Also insert stack realignment code and leave the stack
1063dff0c46cSDimitry Andric /// pointer pointing to the d8 spill slot.
1064dff0c46cSDimitry Andric static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1065dff0c46cSDimitry Andric                                     MachineBasicBlock::iterator MI,
1066dff0c46cSDimitry Andric                                     unsigned NumAlignedDPRCS2Regs,
1067dff0c46cSDimitry Andric                                     const std::vector<CalleeSavedInfo> &CSI,
1068dff0c46cSDimitry Andric                                     const TargetRegisterInfo *TRI) {
1069dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1070dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
10717d523365SDimitry Andric   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
107239d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1073dff0c46cSDimitry Andric   MachineFrameInfo &MFI = *MF.getFrameInfo();
1074dff0c46cSDimitry Andric 
1075dff0c46cSDimitry Andric   // Mark the D-register spill slots as properly aligned.  Since MFI computes
1076dff0c46cSDimitry Andric   // stack slot layout backwards, this can actually mean that the d-reg stack
1077dff0c46cSDimitry Andric   // slot offsets can be wrong. The offset for d8 will always be correct.
1078dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1079dff0c46cSDimitry Andric     unsigned DNum = CSI[i].getReg() - ARM::D8;
10807d523365SDimitry Andric     if (DNum > NumAlignedDPRCS2Regs - 1)
1081dff0c46cSDimitry Andric       continue;
1082dff0c46cSDimitry Andric     int FI = CSI[i].getFrameIdx();
1083dff0c46cSDimitry Andric     // The even-numbered registers will be 16-byte aligned, the odd-numbered
1084dff0c46cSDimitry Andric     // registers will be 8-byte aligned.
1085dff0c46cSDimitry Andric     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1086dff0c46cSDimitry Andric 
1087dff0c46cSDimitry Andric     // The stack slot for D8 needs to be maximally aligned because this is
1088dff0c46cSDimitry Andric     // actually the point where we align the stack pointer.  MachineFrameInfo
1089dff0c46cSDimitry Andric     // computes all offsets relative to the incoming stack pointer which is a
1090dff0c46cSDimitry Andric     // bit weird when realigning the stack.  Any extra padding for this
1091dff0c46cSDimitry Andric     // over-alignment is not realized because the code inserted below adjusts
1092dff0c46cSDimitry Andric     // the stack pointer by numregs * 8 before aligning the stack pointer.
1093dff0c46cSDimitry Andric     if (DNum == 0)
1094dff0c46cSDimitry Andric       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1095dff0c46cSDimitry Andric   }
1096dff0c46cSDimitry Andric 
1097dff0c46cSDimitry Andric   // Move the stack pointer to the d8 spill slot, and align it at the same
1098dff0c46cSDimitry Andric   // time. Leave the stack slot address in the scratch register r4.
1099dff0c46cSDimitry Andric   //
1100dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1101dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1102dff0c46cSDimitry Andric   //   mov sp, r4
1103dff0c46cSDimitry Andric   //
1104dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1105dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1106dff0c46cSDimitry Andric   AFI->setShouldRestoreSPFromFP(true);
1107dff0c46cSDimitry Andric 
1108dff0c46cSDimitry Andric   // sub r4, sp, #numregs * 8
1109dff0c46cSDimitry Andric   // The immediate is <= 64, so it doesn't need any special encoding.
1110dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1111dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1112dff0c46cSDimitry Andric                                   .addReg(ARM::SP)
1113dff0c46cSDimitry Andric                                   .addImm(8 * NumAlignedDPRCS2Regs)));
1114dff0c46cSDimitry Andric 
1115dff0c46cSDimitry Andric   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
111639d628a0SDimitry Andric   // We must set parameter MustBeSingleInstruction to true, since
111739d628a0SDimitry Andric   // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
111839d628a0SDimitry Andric   // stack alignment.  Luckily, this can always be done since all ARM
111939d628a0SDimitry Andric   // architecture versions that support Neon also support the BFC
112039d628a0SDimitry Andric   // instruction.
112139d628a0SDimitry Andric   emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1122dff0c46cSDimitry Andric 
1123dff0c46cSDimitry Andric   // mov sp, r4
1124dff0c46cSDimitry Andric   // The stack pointer must be adjusted before spilling anything, otherwise
1125dff0c46cSDimitry Andric   // the stack slots could be clobbered by an interrupt handler.
1126dff0c46cSDimitry Andric   // Leave r4 live, it is used below.
1127dff0c46cSDimitry Andric   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1128dff0c46cSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1129dff0c46cSDimitry Andric                             .addReg(ARM::R4);
1130dff0c46cSDimitry Andric   MIB = AddDefaultPred(MIB);
1131dff0c46cSDimitry Andric   if (!isThumb)
1132dff0c46cSDimitry Andric     AddDefaultCC(MIB);
1133dff0c46cSDimitry Andric 
1134dff0c46cSDimitry Andric   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1135dff0c46cSDimitry Andric   // r4 holds the stack slot address.
1136dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1137dff0c46cSDimitry Andric 
1138dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1139dff0c46cSDimitry Andric   // The writeback is only needed when emitting two vst1.64 instructions.
1140dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1141dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11427ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1143dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1144dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1145dff0c46cSDimitry Andric                            ARM::R4)
1146dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1147dff0c46cSDimitry Andric                    .addReg(NextReg)
1148dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1149dff0c46cSDimitry Andric     NextReg += 4;
1150dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1151dff0c46cSDimitry Andric   }
1152dff0c46cSDimitry Andric 
1153dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1154dff0c46cSDimitry Andric   // register to be spilled.
1155dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1156dff0c46cSDimitry Andric 
1157dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1158dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1159dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11607ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1161dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1162dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1163dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
1164dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitKill));
1165dff0c46cSDimitry Andric     NextReg += 4;
1166dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1167dff0c46cSDimitry Andric   }
1168dff0c46cSDimitry Andric 
1169dff0c46cSDimitry Andric   // 16-byte aligned vst1.64 with 2 d-regs.
1170dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1171dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
11727ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1173dff0c46cSDimitry Andric     MBB.addLiveIn(SupReg);
1174dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1175dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
1176dff0c46cSDimitry Andric     NextReg += 2;
1177dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1178dff0c46cSDimitry Andric   }
1179dff0c46cSDimitry Andric 
1180dff0c46cSDimitry Andric   // Finally, use a vanilla vstr.64 for the odd last register.
1181dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs) {
1182dff0c46cSDimitry Andric     MBB.addLiveIn(NextReg);
1183dff0c46cSDimitry Andric     // vstr.64 uses addrmode5 which has an offset scale of 4.
1184dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1185dff0c46cSDimitry Andric                    .addReg(NextReg)
1186dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1187dff0c46cSDimitry Andric   }
1188dff0c46cSDimitry Andric 
1189dff0c46cSDimitry Andric   // The last spill instruction inserted should kill the scratch register r4.
119091bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1191dff0c46cSDimitry Andric }
1192dff0c46cSDimitry Andric 
1193dff0c46cSDimitry Andric /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1194dff0c46cSDimitry Andric /// iterator to the following instruction.
1195dff0c46cSDimitry Andric static MachineBasicBlock::iterator
1196dff0c46cSDimitry Andric skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1197dff0c46cSDimitry Andric                         unsigned NumAlignedDPRCS2Regs) {
1198dff0c46cSDimitry Andric   //   sub r4, sp, #numregs * 8
1199dff0c46cSDimitry Andric   //   bic r4, r4, #align - 1
1200dff0c46cSDimitry Andric   //   mov sp, r4
1201dff0c46cSDimitry Andric   ++MI; ++MI; ++MI;
1202dff0c46cSDimitry Andric   assert(MI->mayStore() && "Expecting spill instruction");
1203dff0c46cSDimitry Andric 
1204dff0c46cSDimitry Andric   // These switches all fall through.
1205dff0c46cSDimitry Andric   switch(NumAlignedDPRCS2Regs) {
1206dff0c46cSDimitry Andric   case 7:
1207dff0c46cSDimitry Andric     ++MI;
1208dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1209dff0c46cSDimitry Andric   default:
1210dff0c46cSDimitry Andric     ++MI;
1211dff0c46cSDimitry Andric     assert(MI->mayStore() && "Expecting spill instruction");
1212dff0c46cSDimitry Andric   case 1:
1213dff0c46cSDimitry Andric   case 2:
1214dff0c46cSDimitry Andric   case 4:
1215dff0c46cSDimitry Andric     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1216dff0c46cSDimitry Andric     ++MI;
1217dff0c46cSDimitry Andric   }
1218dff0c46cSDimitry Andric   return MI;
1219dff0c46cSDimitry Andric }
1220dff0c46cSDimitry Andric 
1221dff0c46cSDimitry Andric /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1222dff0c46cSDimitry Andric /// starting from d8.  These instructions are assumed to execute while the
1223dff0c46cSDimitry Andric /// stack is still aligned, unlike the code inserted by emitPopInst.
1224dff0c46cSDimitry Andric static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1225dff0c46cSDimitry Andric                                       MachineBasicBlock::iterator MI,
1226dff0c46cSDimitry Andric                                       unsigned NumAlignedDPRCS2Regs,
1227dff0c46cSDimitry Andric                                       const std::vector<CalleeSavedInfo> &CSI,
1228dff0c46cSDimitry Andric                                       const TargetRegisterInfo *TRI) {
1229dff0c46cSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1230dff0c46cSDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
12317d523365SDimitry Andric   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
123239d628a0SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1233dff0c46cSDimitry Andric 
1234dff0c46cSDimitry Andric   // Find the frame index assigned to d8.
1235dff0c46cSDimitry Andric   int D8SpillFI = 0;
1236dff0c46cSDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1237dff0c46cSDimitry Andric     if (CSI[i].getReg() == ARM::D8) {
1238dff0c46cSDimitry Andric       D8SpillFI = CSI[i].getFrameIdx();
1239dff0c46cSDimitry Andric       break;
1240dff0c46cSDimitry Andric     }
1241dff0c46cSDimitry Andric 
1242dff0c46cSDimitry Andric   // Materialize the address of the d8 spill slot into the scratch register r4.
1243dff0c46cSDimitry Andric   // This can be fairly complicated if the stack frame is large, so just use
1244dff0c46cSDimitry Andric   // the normal frame index elimination mechanism to do it.  This code runs as
1245dff0c46cSDimitry Andric   // the initial part of the epilog where the stack and base pointers haven't
1246dff0c46cSDimitry Andric   // been changed yet.
1247dff0c46cSDimitry Andric   bool isThumb = AFI->isThumbFunction();
1248dff0c46cSDimitry Andric   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1249dff0c46cSDimitry Andric 
1250dff0c46cSDimitry Andric   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1251dff0c46cSDimitry Andric   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1252dff0c46cSDimitry Andric                               .addFrameIndex(D8SpillFI).addImm(0)));
1253dff0c46cSDimitry Andric 
1254dff0c46cSDimitry Andric   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1255dff0c46cSDimitry Andric   unsigned NextReg = ARM::D8;
1256dff0c46cSDimitry Andric 
1257dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1258dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 6) {
1259dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12607ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1261dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1262dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Define)
1263dff0c46cSDimitry Andric                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1264dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1265dff0c46cSDimitry Andric     NextReg += 4;
1266dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1267dff0c46cSDimitry Andric   }
1268dff0c46cSDimitry Andric 
1269dff0c46cSDimitry Andric   // We won't modify r4 beyond this point.  It currently points to the next
1270dff0c46cSDimitry Andric   // register to be spilled.
1271dff0c46cSDimitry Andric   unsigned R4BaseReg = NextReg;
1272dff0c46cSDimitry Andric 
1273dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1274dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 4) {
1275dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12767ae0e2c9SDimitry Andric                                                &ARM::QQPRRegClass);
1277dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1278dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16)
1279dff0c46cSDimitry Andric                    .addReg(SupReg, RegState::ImplicitDefine));
1280dff0c46cSDimitry Andric     NextReg += 4;
1281dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 4;
1282dff0c46cSDimitry Andric   }
1283dff0c46cSDimitry Andric 
1284dff0c46cSDimitry Andric   // 16-byte aligned vld1.64 with 2 d-regs.
1285dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs >= 2) {
1286dff0c46cSDimitry Andric     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
12877ae0e2c9SDimitry Andric                                                &ARM::QPRRegClass);
1288dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1289dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(16));
1290dff0c46cSDimitry Andric     NextReg += 2;
1291dff0c46cSDimitry Andric     NumAlignedDPRCS2Regs -= 2;
1292dff0c46cSDimitry Andric   }
1293dff0c46cSDimitry Andric 
1294dff0c46cSDimitry Andric   // Finally, use a vanilla vldr.64 for the remaining odd register.
1295dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1296dff0c46cSDimitry Andric     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1297dff0c46cSDimitry Andric                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1298dff0c46cSDimitry Andric 
1299dff0c46cSDimitry Andric   // Last store kills r4.
130091bc56edSDimitry Andric   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1301dff0c46cSDimitry Andric }
1302dff0c46cSDimitry Andric 
13032754fe60SDimitry Andric bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
13042754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
13052754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
13062754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
13072754fe60SDimitry Andric   if (CSI.empty())
13082754fe60SDimitry Andric     return false;
13092754fe60SDimitry Andric 
13102754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
13112754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
13122754fe60SDimitry Andric 
13132754fe60SDimitry Andric   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
13146122f3e6SDimitry Andric   unsigned PushOneOpc = AFI->isThumbFunction() ?
13156122f3e6SDimitry Andric     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
13162754fe60SDimitry Andric   unsigned FltOpc = ARM::VSTMDDB_UPD;
1317dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1318dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
13193b0f4066SDimitry Andric                MachineInstr::FrameSetup);
1320dff0c46cSDimitry Andric   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
13213b0f4066SDimitry Andric                MachineInstr::FrameSetup);
13223b0f4066SDimitry Andric   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1323dff0c46cSDimitry Andric                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1324dff0c46cSDimitry Andric 
1325dff0c46cSDimitry Andric   // The code above does not insert spill code for the aligned DPRCS2 registers.
1326dff0c46cSDimitry Andric   // The stack realignment code will be inserted between the push instructions
1327dff0c46cSDimitry Andric   // and these spills.
1328dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1329dff0c46cSDimitry Andric     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
13302754fe60SDimitry Andric 
13312754fe60SDimitry Andric   return true;
13322754fe60SDimitry Andric }
13332754fe60SDimitry Andric 
13342754fe60SDimitry Andric bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
13352754fe60SDimitry Andric                                         MachineBasicBlock::iterator MI,
13362754fe60SDimitry Andric                                         const std::vector<CalleeSavedInfo> &CSI,
13372754fe60SDimitry Andric                                         const TargetRegisterInfo *TRI) const {
13382754fe60SDimitry Andric   if (CSI.empty())
13392754fe60SDimitry Andric     return false;
13402754fe60SDimitry Andric 
13412754fe60SDimitry Andric   MachineFunction &MF = *MBB.getParent();
13422754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1343284c1978SDimitry Andric   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1344dff0c46cSDimitry Andric   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1345dff0c46cSDimitry Andric 
1346dff0c46cSDimitry Andric   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1347dff0c46cSDimitry Andric   // registers. Do that here instead.
1348dff0c46cSDimitry Andric   if (NumAlignedDPRCS2Regs)
1349dff0c46cSDimitry Andric     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
13502754fe60SDimitry Andric 
13512754fe60SDimitry Andric   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
13526122f3e6SDimitry Andric   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
13532754fe60SDimitry Andric   unsigned FltOpc = ARM::VLDMDIA_UPD;
1354dff0c46cSDimitry Andric   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1355dff0c46cSDimitry Andric               NumAlignedDPRCS2Regs);
13562754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1357dff0c46cSDimitry Andric               &isARMArea2Register, 0);
13582754fe60SDimitry Andric   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1359dff0c46cSDimitry Andric               &isARMArea1Register, 0);
13602754fe60SDimitry Andric 
13612754fe60SDimitry Andric   return true;
13622754fe60SDimitry Andric }
13632754fe60SDimitry Andric 
13642754fe60SDimitry Andric // FIXME: Make generic?
13652754fe60SDimitry Andric static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
13662754fe60SDimitry Andric                                        const ARMBaseInstrInfo &TII) {
13672754fe60SDimitry Andric   unsigned FnSize = 0;
136891bc56edSDimitry Andric   for (auto &MBB : MF) {
136991bc56edSDimitry Andric     for (auto &MI : MBB)
137091bc56edSDimitry Andric       FnSize += TII.GetInstSizeInBytes(&MI);
13712754fe60SDimitry Andric   }
13722754fe60SDimitry Andric   return FnSize;
13732754fe60SDimitry Andric }
13742754fe60SDimitry Andric 
13752754fe60SDimitry Andric /// estimateRSStackSizeLimit - Look at each instruction that references stack
13762754fe60SDimitry Andric /// frames and return the stack size limit beyond which some of these
13772754fe60SDimitry Andric /// instructions will require a scratch register during their expansion later.
13782754fe60SDimitry Andric // FIXME: Move to TII?
13792754fe60SDimitry Andric static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
13802754fe60SDimitry Andric                                          const TargetFrameLowering *TFI) {
13812754fe60SDimitry Andric   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
13822754fe60SDimitry Andric   unsigned Limit = (1 << 12) - 1;
138391bc56edSDimitry Andric   for (auto &MBB : MF) {
138491bc56edSDimitry Andric     for (auto &MI : MBB) {
138591bc56edSDimitry Andric       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
138691bc56edSDimitry Andric         if (!MI.getOperand(i).isFI())
138791bc56edSDimitry Andric           continue;
13882754fe60SDimitry Andric 
13892754fe60SDimitry Andric         // When using ADDri to get the address of a stack object, 255 is the
13902754fe60SDimitry Andric         // largest offset guaranteed to fit in the immediate offset.
139191bc56edSDimitry Andric         if (MI.getOpcode() == ARM::ADDri) {
13922754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
13932754fe60SDimitry Andric           break;
13942754fe60SDimitry Andric         }
13952754fe60SDimitry Andric 
13962754fe60SDimitry Andric         // Otherwise check the addressing mode.
139791bc56edSDimitry Andric         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
13982754fe60SDimitry Andric         case ARMII::AddrMode3:
13992754fe60SDimitry Andric         case ARMII::AddrModeT2_i8:
14002754fe60SDimitry Andric           Limit = std::min(Limit, (1U << 8) - 1);
14012754fe60SDimitry Andric           break;
14022754fe60SDimitry Andric         case ARMII::AddrMode5:
14032754fe60SDimitry Andric         case ARMII::AddrModeT2_i8s4:
14042754fe60SDimitry Andric           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
14052754fe60SDimitry Andric           break;
14062754fe60SDimitry Andric         case ARMII::AddrModeT2_i12:
14072754fe60SDimitry Andric           // i12 supports only positive offset so these will be converted to
14082754fe60SDimitry Andric           // i8 opcodes. See llvm::rewriteT2FrameIndex.
14092754fe60SDimitry Andric           if (TFI->hasFP(MF) && AFI->hasStackFrame())
14102754fe60SDimitry Andric             Limit = std::min(Limit, (1U << 8) - 1);
14112754fe60SDimitry Andric           break;
14122754fe60SDimitry Andric         case ARMII::AddrMode4:
14132754fe60SDimitry Andric         case ARMII::AddrMode6:
14142754fe60SDimitry Andric           // Addressing modes 4 & 6 (load/store) instructions can't encode an
14152754fe60SDimitry Andric           // immediate offset for stack references.
14162754fe60SDimitry Andric           return 0;
14172754fe60SDimitry Andric         default:
14182754fe60SDimitry Andric           break;
14192754fe60SDimitry Andric         }
14202754fe60SDimitry Andric         break; // At most one FI per instruction
14212754fe60SDimitry Andric       }
14222754fe60SDimitry Andric     }
14232754fe60SDimitry Andric   }
14242754fe60SDimitry Andric 
14252754fe60SDimitry Andric   return Limit;
14262754fe60SDimitry Andric }
14272754fe60SDimitry Andric 
1428dff0c46cSDimitry Andric // In functions that realign the stack, it can be an advantage to spill the
1429dff0c46cSDimitry Andric // callee-saved vector registers after realigning the stack. The vst1 and vld1
1430dff0c46cSDimitry Andric // instructions take alignment hints that can improve performance.
1431dff0c46cSDimitry Andric //
1432875ed548SDimitry Andric static void
1433875ed548SDimitry Andric checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1434dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1435dff0c46cSDimitry Andric   if (!SpillAlignedNEONRegs)
1436dff0c46cSDimitry Andric     return;
1437dff0c46cSDimitry Andric 
1438dff0c46cSDimitry Andric   // Naked functions don't spill callee-saved registers.
1439ff0cc061SDimitry Andric   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1440dff0c46cSDimitry Andric     return;
1441dff0c46cSDimitry Andric 
1442dff0c46cSDimitry Andric   // We are planning to use NEON instructions vst1 / vld1.
1443ff0cc061SDimitry Andric   if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1444dff0c46cSDimitry Andric     return;
1445dff0c46cSDimitry Andric 
1446dff0c46cSDimitry Andric   // Don't bother if the default stack alignment is sufficiently high.
1447ff0cc061SDimitry Andric   if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1448dff0c46cSDimitry Andric     return;
1449dff0c46cSDimitry Andric 
1450dff0c46cSDimitry Andric   // Aligned spills require stack realignment.
1451ff0cc061SDimitry Andric   if (!static_cast<const ARMBaseRegisterInfo *>(
1452ff0cc061SDimitry Andric            MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1453dff0c46cSDimitry Andric     return;
1454dff0c46cSDimitry Andric 
1455dff0c46cSDimitry Andric   // We always spill contiguous d-registers starting from d8. Count how many
1456dff0c46cSDimitry Andric   // needs spilling.  The register allocator will almost always use the
1457dff0c46cSDimitry Andric   // callee-saved registers in order, but it can happen that there are holes in
1458dff0c46cSDimitry Andric   // the range.  Registers above the hole will be spilled to the standard DPRCS
1459dff0c46cSDimitry Andric   // area.
1460dff0c46cSDimitry Andric   unsigned NumSpills = 0;
1461dff0c46cSDimitry Andric   for (; NumSpills < 8; ++NumSpills)
1462875ed548SDimitry Andric     if (!SavedRegs.test(ARM::D8 + NumSpills))
1463dff0c46cSDimitry Andric       break;
1464dff0c46cSDimitry Andric 
1465dff0c46cSDimitry Andric   // Don't do this for just one d-register. It's not worth it.
1466dff0c46cSDimitry Andric   if (NumSpills < 2)
1467dff0c46cSDimitry Andric     return;
1468dff0c46cSDimitry Andric 
1469dff0c46cSDimitry Andric   // Spill the first NumSpills D-registers after realigning the stack.
1470dff0c46cSDimitry Andric   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1471dff0c46cSDimitry Andric 
1472dff0c46cSDimitry Andric   // A scratch register is required for the vst1 / vld1 instructions.
1473875ed548SDimitry Andric   SavedRegs.set(ARM::R4);
1474dff0c46cSDimitry Andric }
1475dff0c46cSDimitry Andric 
1476875ed548SDimitry Andric void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1477875ed548SDimitry Andric                                             BitVector &SavedRegs,
14782754fe60SDimitry Andric                                             RegScavenger *RS) const {
1479875ed548SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
14802754fe60SDimitry Andric   // This tells PEI to spill the FP as if it is any other callee-save register
14812754fe60SDimitry Andric   // to take advantage the eliminateFrameIndex machinery. This also ensures it
14822754fe60SDimitry Andric   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
14832754fe60SDimitry Andric   // to combine multiple loads / stores.
14842754fe60SDimitry Andric   bool CanEliminateFrame = true;
14852754fe60SDimitry Andric   bool CS1Spilled = false;
14862754fe60SDimitry Andric   bool LRSpilled = false;
14872754fe60SDimitry Andric   unsigned NumGPRSpills = 0;
14882754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS1GPRs;
14892754fe60SDimitry Andric   SmallVector<unsigned, 4> UnspilledCS2GPRs;
149039d628a0SDimitry Andric   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
149139d628a0SDimitry Andric       MF.getSubtarget().getRegisterInfo());
14922754fe60SDimitry Andric   const ARMBaseInstrInfo &TII =
149339d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
14942754fe60SDimitry Andric   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
14952754fe60SDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
14963861d79fSDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
14972754fe60SDimitry Andric   unsigned FramePtr = RegInfo->getFrameRegister(MF);
14982754fe60SDimitry Andric 
14992754fe60SDimitry Andric   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
15002754fe60SDimitry Andric   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
15012754fe60SDimitry Andric   // since it's not always possible to restore sp from fp in a single
15022754fe60SDimitry Andric   // instruction.
15032754fe60SDimitry Andric   // FIXME: It will be better just to find spare register here.
15042754fe60SDimitry Andric   if (AFI->isThumb2Function() &&
15052754fe60SDimitry Andric       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1506875ed548SDimitry Andric     SavedRegs.set(ARM::R4);
15072754fe60SDimitry Andric 
15082754fe60SDimitry Andric   if (AFI->isThumb1OnlyFunction()) {
15092754fe60SDimitry Andric     // Spill LR if Thumb1 function uses variable length argument lists.
1510284c1978SDimitry Andric     if (AFI->getArgRegsSaveSize() > 0)
1511875ed548SDimitry Andric       SavedRegs.set(ARM::LR);
15122754fe60SDimitry Andric 
151317a519f9SDimitry Andric     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
151417a519f9SDimitry Andric     // for sure what the stack size will be, but for this, an estimate is good
151517a519f9SDimitry Andric     // enough. If there anything changes it, it'll be a spill, which implies
151617a519f9SDimitry Andric     // we've used all the registers and so R4 is already used, so not marking
151717a519f9SDimitry Andric     // it here will be OK.
15182754fe60SDimitry Andric     // FIXME: It will be better just to find spare register here.
1519139f7f9bSDimitry Andric     unsigned StackSize = MFI->estimateStackSize(MF);
152017a519f9SDimitry Andric     if (MFI->hasVarSizedObjects() || StackSize > 508)
1521875ed548SDimitry Andric       SavedRegs.set(ARM::R4);
15222754fe60SDimitry Andric   }
15232754fe60SDimitry Andric 
1524dff0c46cSDimitry Andric   // See if we can spill vector registers to aligned stack.
1525875ed548SDimitry Andric   checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1526dff0c46cSDimitry Andric 
15272754fe60SDimitry Andric   // Spill the BasePtr if it's used.
15282754fe60SDimitry Andric   if (RegInfo->hasBasePointer(MF))
1529875ed548SDimitry Andric     SavedRegs.set(RegInfo->getBaseRegister());
15302754fe60SDimitry Andric 
15312754fe60SDimitry Andric   // Don't spill FP if the frame can be eliminated. This is determined
1532875ed548SDimitry Andric   // by scanning the callee-save registers to see if any is modified.
153391bc56edSDimitry Andric   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
15342754fe60SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i) {
15352754fe60SDimitry Andric     unsigned Reg = CSRegs[i];
15362754fe60SDimitry Andric     bool Spilled = false;
1537875ed548SDimitry Andric     if (SavedRegs.test(Reg)) {
15382754fe60SDimitry Andric       Spilled = true;
15392754fe60SDimitry Andric       CanEliminateFrame = false;
15402754fe60SDimitry Andric     }
15412754fe60SDimitry Andric 
15427ae0e2c9SDimitry Andric     if (!ARM::GPRRegClass.contains(Reg))
15432754fe60SDimitry Andric       continue;
15442754fe60SDimitry Andric 
15452754fe60SDimitry Andric     if (Spilled) {
15462754fe60SDimitry Andric       NumGPRSpills++;
15472754fe60SDimitry Andric 
154891bc56edSDimitry Andric       if (!STI.isTargetDarwin()) {
15492754fe60SDimitry Andric         if (Reg == ARM::LR)
15502754fe60SDimitry Andric           LRSpilled = true;
15512754fe60SDimitry Andric         CS1Spilled = true;
15522754fe60SDimitry Andric         continue;
15532754fe60SDimitry Andric       }
15542754fe60SDimitry Andric 
15552754fe60SDimitry Andric       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
15562754fe60SDimitry Andric       switch (Reg) {
15572754fe60SDimitry Andric       case ARM::LR:
15582754fe60SDimitry Andric         LRSpilled = true;
15592754fe60SDimitry Andric         // Fallthrough
1560f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1561f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
15622754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
15632754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
15642754fe60SDimitry Andric         CS1Spilled = true;
15652754fe60SDimitry Andric         break;
15662754fe60SDimitry Andric       default:
15672754fe60SDimitry Andric         break;
15682754fe60SDimitry Andric       }
15692754fe60SDimitry Andric     } else {
157091bc56edSDimitry Andric       if (!STI.isTargetDarwin()) {
15712754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
15722754fe60SDimitry Andric         continue;
15732754fe60SDimitry Andric       }
15742754fe60SDimitry Andric 
15752754fe60SDimitry Andric       switch (Reg) {
1576f785676fSDimitry Andric       case ARM::R0: case ARM::R1:
1577f785676fSDimitry Andric       case ARM::R2: case ARM::R3:
15782754fe60SDimitry Andric       case ARM::R4: case ARM::R5:
15792754fe60SDimitry Andric       case ARM::R6: case ARM::R7:
15802754fe60SDimitry Andric       case ARM::LR:
15812754fe60SDimitry Andric         UnspilledCS1GPRs.push_back(Reg);
15822754fe60SDimitry Andric         break;
15832754fe60SDimitry Andric       default:
15842754fe60SDimitry Andric         UnspilledCS2GPRs.push_back(Reg);
15852754fe60SDimitry Andric         break;
15862754fe60SDimitry Andric       }
15872754fe60SDimitry Andric     }
15882754fe60SDimitry Andric   }
15892754fe60SDimitry Andric 
15902754fe60SDimitry Andric   bool ForceLRSpill = false;
15912754fe60SDimitry Andric   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
15922754fe60SDimitry Andric     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
15932754fe60SDimitry Andric     // Force LR to be spilled if the Thumb function size is > 2048. This enables
15942754fe60SDimitry Andric     // use of BL to implement far jump. If it turns out that it's not needed
15952754fe60SDimitry Andric     // then the branch fix up path will undo it.
15962754fe60SDimitry Andric     if (FnSize >= (1 << 11)) {
15972754fe60SDimitry Andric       CanEliminateFrame = false;
15982754fe60SDimitry Andric       ForceLRSpill = true;
15992754fe60SDimitry Andric     }
16002754fe60SDimitry Andric   }
16012754fe60SDimitry Andric 
16022754fe60SDimitry Andric   // If any of the stack slot references may be out of range of an immediate
16032754fe60SDimitry Andric   // offset, make sure a register (or a spill slot) is available for the
16042754fe60SDimitry Andric   // register scavenger. Note that if we're indexing off the frame pointer, the
16052754fe60SDimitry Andric   // effective stack size is 4 bytes larger since the FP points to the stack
16062754fe60SDimitry Andric   // slot of the previous FP. Also, if we have variable sized objects in the
16072754fe60SDimitry Andric   // function, stack slot references will often be negative, and some of
16082754fe60SDimitry Andric   // our instructions are positive-offset only, so conservatively consider
16092754fe60SDimitry Andric   // that case to want a spill slot (or register) as well. Similarly, if
16102754fe60SDimitry Andric   // the function adjusts the stack pointer during execution and the
16112754fe60SDimitry Andric   // adjustments aren't already part of our stack size estimate, our offset
16122754fe60SDimitry Andric   // calculations may be off, so be conservative.
16132754fe60SDimitry Andric   // FIXME: We could add logic to be more precise about negative offsets
16142754fe60SDimitry Andric   //        and which instructions will need a scratch register for them. Is it
16152754fe60SDimitry Andric   //        worth the effort and added fragility?
16167d523365SDimitry Andric   bool BigStack = (RS && (MFI->estimateStackSize(MF) +
1617139f7f9bSDimitry Andric                               ((hasFP(MF) && AFI->hasStackFrame()) ? 4 : 0) >=
16187d523365SDimitry Andric                           estimateRSStackSizeLimit(MF, this))) ||
16197d523365SDimitry Andric                   MFI->hasVarSizedObjects() ||
16207d523365SDimitry Andric                   (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
16212754fe60SDimitry Andric 
16222754fe60SDimitry Andric   bool ExtraCSSpill = false;
16232754fe60SDimitry Andric   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
16242754fe60SDimitry Andric     AFI->setHasStackFrame(true);
16252754fe60SDimitry Andric 
16262754fe60SDimitry Andric     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
16272754fe60SDimitry Andric     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
16282754fe60SDimitry Andric     if (!LRSpilled && CS1Spilled) {
1629875ed548SDimitry Andric       SavedRegs.set(ARM::LR);
16302754fe60SDimitry Andric       NumGPRSpills++;
1631f785676fSDimitry Andric       SmallVectorImpl<unsigned>::iterator LRPos;
1632f785676fSDimitry Andric       LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1633f785676fSDimitry Andric                         (unsigned)ARM::LR);
1634f785676fSDimitry Andric       if (LRPos != UnspilledCS1GPRs.end())
1635f785676fSDimitry Andric         UnspilledCS1GPRs.erase(LRPos);
1636f785676fSDimitry Andric 
16372754fe60SDimitry Andric       ForceLRSpill = false;
16382754fe60SDimitry Andric       ExtraCSSpill = true;
16392754fe60SDimitry Andric     }
16402754fe60SDimitry Andric 
16412754fe60SDimitry Andric     if (hasFP(MF)) {
1642875ed548SDimitry Andric       SavedRegs.set(FramePtr);
164391bc56edSDimitry Andric       auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
164491bc56edSDimitry Andric                              FramePtr);
164591bc56edSDimitry Andric       if (FPPos != UnspilledCS1GPRs.end())
164691bc56edSDimitry Andric         UnspilledCS1GPRs.erase(FPPos);
16472754fe60SDimitry Andric       NumGPRSpills++;
16482754fe60SDimitry Andric     }
16492754fe60SDimitry Andric 
16502754fe60SDimitry Andric     // If stack and double are 8-byte aligned and we are spilling an odd number
16512754fe60SDimitry Andric     // of GPRs, spill one extra callee save GPR so we won't have to pad between
16522754fe60SDimitry Andric     // the integer and double callee save areas.
16532754fe60SDimitry Andric     unsigned TargetAlign = getStackAlignment();
165439d628a0SDimitry Andric     if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
16552754fe60SDimitry Andric       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
16562754fe60SDimitry Andric         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
16572754fe60SDimitry Andric           unsigned Reg = UnspilledCS1GPRs[i];
16587d523365SDimitry Andric           // Don't spill high register if the function is thumb.  In the case of
16597d523365SDimitry Andric           // Windows on ARM, accept R11 (frame pointer)
1660ff0cc061SDimitry Andric           if (!AFI->isThumbFunction() ||
16617d523365SDimitry Andric               (STI.isTargetWindows() && Reg == ARM::R11) ||
16622754fe60SDimitry Andric               isARMLowRegister(Reg) || Reg == ARM::LR) {
1663875ed548SDimitry Andric             SavedRegs.set(Reg);
16643861d79fSDimitry Andric             if (!MRI.isReserved(Reg))
16652754fe60SDimitry Andric               ExtraCSSpill = true;
16662754fe60SDimitry Andric             break;
16672754fe60SDimitry Andric           }
16682754fe60SDimitry Andric         }
16692754fe60SDimitry Andric       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
16702754fe60SDimitry Andric         unsigned Reg = UnspilledCS2GPRs.front();
1671875ed548SDimitry Andric         SavedRegs.set(Reg);
16723861d79fSDimitry Andric         if (!MRI.isReserved(Reg))
16732754fe60SDimitry Andric           ExtraCSSpill = true;
16742754fe60SDimitry Andric       }
16752754fe60SDimitry Andric     }
16762754fe60SDimitry Andric 
16772754fe60SDimitry Andric     // Estimate if we might need to scavenge a register at some point in order
16782754fe60SDimitry Andric     // to materialize a stack offset. If so, either spill one additional
16792754fe60SDimitry Andric     // callee-saved register or reserve a special spill slot to facilitate
16802754fe60SDimitry Andric     // register scavenging. Thumb1 needs a spill slot for stack pointer
16812754fe60SDimitry Andric     // adjustments also, even when the frame itself is small.
16822754fe60SDimitry Andric     if (BigStack && !ExtraCSSpill) {
16832754fe60SDimitry Andric       // If any non-reserved CS register isn't spilled, just spill one or two
16842754fe60SDimitry Andric       // extra. That should take care of it!
16852754fe60SDimitry Andric       unsigned NumExtras = TargetAlign / 4;
16862754fe60SDimitry Andric       SmallVector<unsigned, 2> Extras;
16872754fe60SDimitry Andric       while (NumExtras && !UnspilledCS1GPRs.empty()) {
16882754fe60SDimitry Andric         unsigned Reg = UnspilledCS1GPRs.back();
16892754fe60SDimitry Andric         UnspilledCS1GPRs.pop_back();
16903861d79fSDimitry Andric         if (!MRI.isReserved(Reg) &&
16912754fe60SDimitry Andric             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
16922754fe60SDimitry Andric              Reg == ARM::LR)) {
16932754fe60SDimitry Andric           Extras.push_back(Reg);
16942754fe60SDimitry Andric           NumExtras--;
16952754fe60SDimitry Andric         }
16962754fe60SDimitry Andric       }
16972754fe60SDimitry Andric       // For non-Thumb1 functions, also check for hi-reg CS registers
16982754fe60SDimitry Andric       if (!AFI->isThumb1OnlyFunction()) {
16992754fe60SDimitry Andric         while (NumExtras && !UnspilledCS2GPRs.empty()) {
17002754fe60SDimitry Andric           unsigned Reg = UnspilledCS2GPRs.back();
17012754fe60SDimitry Andric           UnspilledCS2GPRs.pop_back();
17023861d79fSDimitry Andric           if (!MRI.isReserved(Reg)) {
17032754fe60SDimitry Andric             Extras.push_back(Reg);
17042754fe60SDimitry Andric             NumExtras--;
17052754fe60SDimitry Andric           }
17062754fe60SDimitry Andric         }
17072754fe60SDimitry Andric       }
17082754fe60SDimitry Andric       if (Extras.size() && NumExtras == 0) {
17092754fe60SDimitry Andric         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1710875ed548SDimitry Andric           SavedRegs.set(Extras[i]);
17112754fe60SDimitry Andric         }
17122754fe60SDimitry Andric       } else if (!AFI->isThumb1OnlyFunction()) {
17132754fe60SDimitry Andric         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
17142754fe60SDimitry Andric         // closest to SP or frame pointer.
17157ae0e2c9SDimitry Andric         const TargetRegisterClass *RC = &ARM::GPRRegClass;
1716139f7f9bSDimitry Andric         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
17172754fe60SDimitry Andric                                                            RC->getAlignment(),
17182754fe60SDimitry Andric                                                            false));
17192754fe60SDimitry Andric       }
17202754fe60SDimitry Andric     }
17212754fe60SDimitry Andric   }
17222754fe60SDimitry Andric 
17232754fe60SDimitry Andric   if (ForceLRSpill) {
1724875ed548SDimitry Andric     SavedRegs.set(ARM::LR);
17252754fe60SDimitry Andric     AFI->setLRIsSpilledForFarJump(true);
17262754fe60SDimitry Andric   }
17272754fe60SDimitry Andric }
1728139f7f9bSDimitry Andric 
1729139f7f9bSDimitry Andric 
1730139f7f9bSDimitry Andric void ARMFrameLowering::
1731139f7f9bSDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1732139f7f9bSDimitry Andric                               MachineBasicBlock::iterator I) const {
1733139f7f9bSDimitry Andric   const ARMBaseInstrInfo &TII =
173439d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1735139f7f9bSDimitry Andric   if (!hasReservedCallFrame(MF)) {
1736139f7f9bSDimitry Andric     // If we have alloca, convert as follows:
1737139f7f9bSDimitry Andric     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1738139f7f9bSDimitry Andric     // ADJCALLSTACKUP   -> add, sp, sp, amount
1739139f7f9bSDimitry Andric     MachineInstr *Old = I;
1740139f7f9bSDimitry Andric     DebugLoc dl = Old->getDebugLoc();
1741139f7f9bSDimitry Andric     unsigned Amount = Old->getOperand(0).getImm();
1742139f7f9bSDimitry Andric     if (Amount != 0) {
1743139f7f9bSDimitry Andric       // We need to keep the stack aligned properly.  To do this, we round the
1744139f7f9bSDimitry Andric       // amount of space needed for the outgoing arguments up to the next
1745139f7f9bSDimitry Andric       // alignment boundary.
17467d523365SDimitry Andric       Amount = alignSPAdjust(Amount);
1747139f7f9bSDimitry Andric 
1748139f7f9bSDimitry Andric       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1749139f7f9bSDimitry Andric       assert(!AFI->isThumb1OnlyFunction() &&
1750139f7f9bSDimitry Andric              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1751139f7f9bSDimitry Andric       bool isARM = !AFI->isThumbFunction();
1752139f7f9bSDimitry Andric 
1753139f7f9bSDimitry Andric       // Replace the pseudo instruction with a new instruction...
1754139f7f9bSDimitry Andric       unsigned Opc = Old->getOpcode();
1755139f7f9bSDimitry Andric       int PIdx = Old->findFirstPredOperandIdx();
1756139f7f9bSDimitry Andric       ARMCC::CondCodes Pred = (PIdx == -1)
1757139f7f9bSDimitry Andric         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1758139f7f9bSDimitry Andric       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1759139f7f9bSDimitry Andric         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1760139f7f9bSDimitry Andric         unsigned PredReg = Old->getOperand(2).getReg();
1761139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1762139f7f9bSDimitry Andric                      Pred, PredReg);
1763139f7f9bSDimitry Andric       } else {
1764139f7f9bSDimitry Andric         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1765139f7f9bSDimitry Andric         unsigned PredReg = Old->getOperand(3).getReg();
1766139f7f9bSDimitry Andric         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1767139f7f9bSDimitry Andric         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1768139f7f9bSDimitry Andric                      Pred, PredReg);
1769139f7f9bSDimitry Andric       }
1770139f7f9bSDimitry Andric     }
1771139f7f9bSDimitry Andric   }
1772139f7f9bSDimitry Andric   MBB.erase(I);
1773139f7f9bSDimitry Andric }
1774139f7f9bSDimitry Andric 
177591bc56edSDimitry Andric /// Get the minimum constant for ARM that is greater than or equal to the
177691bc56edSDimitry Andric /// argument. In ARM, constants can have any value that can be produced by
177791bc56edSDimitry Andric /// rotating an 8-bit value to the right by an even number of bits within a
177891bc56edSDimitry Andric /// 32-bit word.
177991bc56edSDimitry Andric static uint32_t alignToARMConstant(uint32_t Value) {
178091bc56edSDimitry Andric   unsigned Shifted = 0;
178191bc56edSDimitry Andric 
178291bc56edSDimitry Andric   if (Value == 0)
178391bc56edSDimitry Andric       return 0;
178491bc56edSDimitry Andric 
178591bc56edSDimitry Andric   while (!(Value & 0xC0000000)) {
178691bc56edSDimitry Andric       Value = Value << 2;
178791bc56edSDimitry Andric       Shifted += 2;
178891bc56edSDimitry Andric   }
178991bc56edSDimitry Andric 
179091bc56edSDimitry Andric   bool Carry = (Value & 0x00FFFFFF);
179191bc56edSDimitry Andric   Value = ((Value & 0xFF000000) >> 24) + Carry;
179291bc56edSDimitry Andric 
179391bc56edSDimitry Andric   if (Value & 0x0000100)
179491bc56edSDimitry Andric       Value = Value & 0x000001FC;
179591bc56edSDimitry Andric 
179691bc56edSDimitry Andric   if (Shifted > 24)
179791bc56edSDimitry Andric       Value = Value >> (Shifted - 24);
179891bc56edSDimitry Andric   else
179991bc56edSDimitry Andric       Value = Value << (24 - Shifted);
180091bc56edSDimitry Andric 
180191bc56edSDimitry Andric   return Value;
180291bc56edSDimitry Andric }
180391bc56edSDimitry Andric 
180491bc56edSDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual
180591bc56edSDimitry Andric // stack limit.
180691bc56edSDimitry Andric static const uint64_t kSplitStackAvailable = 256;
180791bc56edSDimitry Andric 
180891bc56edSDimitry Andric // Adjust the function prologue to enable split stacks. This currently only
180991bc56edSDimitry Andric // supports android and linux.
181091bc56edSDimitry Andric //
181191bc56edSDimitry Andric // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
181291bc56edSDimitry Andric // must be well defined in order to allow for consistent implementations of the
181391bc56edSDimitry Andric // __morestack helper function. The ABI is also not a normal ABI in that it
181491bc56edSDimitry Andric // doesn't follow the normal calling conventions because this allows the
181591bc56edSDimitry Andric // prologue of each function to be optimized further.
181691bc56edSDimitry Andric //
181791bc56edSDimitry Andric // Currently, the ABI looks like (when calling __morestack)
181891bc56edSDimitry Andric //
181991bc56edSDimitry Andric //  * r4 holds the minimum stack size requested for this function call
182091bc56edSDimitry Andric //  * r5 holds the stack size of the arguments to the function
182191bc56edSDimitry Andric //  * the beginning of the function is 3 instructions after the call to
182291bc56edSDimitry Andric //    __morestack
182391bc56edSDimitry Andric //
182491bc56edSDimitry Andric // Implementations of __morestack should use r4 to allocate a new stack, r5 to
182591bc56edSDimitry Andric // place the arguments on to the new stack, and the 3-instruction knowledge to
182691bc56edSDimitry Andric // jump directly to the body of the function when working on the new stack.
182791bc56edSDimitry Andric //
182891bc56edSDimitry Andric // An old (and possibly no longer compatible) implementation of __morestack for
182991bc56edSDimitry Andric // ARM can be found at [1].
183091bc56edSDimitry Andric //
183191bc56edSDimitry Andric // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1832ff0cc061SDimitry Andric void ARMFrameLowering::adjustForSegmentedStacks(
1833ff0cc061SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
183491bc56edSDimitry Andric   unsigned Opcode;
183591bc56edSDimitry Andric   unsigned CFIIndex;
1836ff0cc061SDimitry Andric   const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
183791bc56edSDimitry Andric   bool Thumb = ST->isThumb();
183891bc56edSDimitry Andric 
183991bc56edSDimitry Andric   // Sadly, this currently doesn't support varargs, platforms other than
184091bc56edSDimitry Andric   // android/linux. Note that thumb1/thumb2 are support for android/linux.
184191bc56edSDimitry Andric   if (MF.getFunction()->isVarArg())
184291bc56edSDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
184391bc56edSDimitry Andric   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
184491bc56edSDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
184591bc56edSDimitry Andric 
184691bc56edSDimitry Andric   MachineFrameInfo *MFI = MF.getFrameInfo();
184791bc56edSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
184891bc56edSDimitry Andric   MCContext &Context = MMI.getContext();
184991bc56edSDimitry Andric   const MCRegisterInfo *MRI = Context.getRegisterInfo();
185091bc56edSDimitry Andric   const ARMBaseInstrInfo &TII =
185139d628a0SDimitry Andric       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
185291bc56edSDimitry Andric   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
185391bc56edSDimitry Andric   DebugLoc DL;
185491bc56edSDimitry Andric 
185591bc56edSDimitry Andric   uint64_t StackSize = MFI->getStackSize();
185691bc56edSDimitry Andric 
185791bc56edSDimitry Andric   // Do not generate a prologue for functions with a stack of size zero
185891bc56edSDimitry Andric   if (StackSize == 0)
185991bc56edSDimitry Andric     return;
186091bc56edSDimitry Andric 
186191bc56edSDimitry Andric   // Use R4 and R5 as scratch registers.
186291bc56edSDimitry Andric   // We save R4 and R5 before use and restore them before leaving the function.
186391bc56edSDimitry Andric   unsigned ScratchReg0 = ARM::R4;
186491bc56edSDimitry Andric   unsigned ScratchReg1 = ARM::R5;
186591bc56edSDimitry Andric   uint64_t AlignedStackSize;
186691bc56edSDimitry Andric 
186791bc56edSDimitry Andric   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
186891bc56edSDimitry Andric   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
186991bc56edSDimitry Andric   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
187091bc56edSDimitry Andric   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
187191bc56edSDimitry Andric   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
187291bc56edSDimitry Andric 
18737d523365SDimitry Andric   // Grab everything that reaches PrologueMBB to update there liveness as well.
18747d523365SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
18757d523365SDimitry Andric   SmallVector<MachineBasicBlock *, 2> WalkList;
18767d523365SDimitry Andric   WalkList.push_back(&PrologueMBB);
18777d523365SDimitry Andric 
18787d523365SDimitry Andric   do {
18797d523365SDimitry Andric     MachineBasicBlock *CurMBB = WalkList.pop_back_val();
18807d523365SDimitry Andric     for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
18817d523365SDimitry Andric       if (BeforePrologueRegion.insert(PredBB).second)
18827d523365SDimitry Andric         WalkList.push_back(PredBB);
18837d523365SDimitry Andric     }
18847d523365SDimitry Andric   } while (!WalkList.empty());
18857d523365SDimitry Andric 
18867d523365SDimitry Andric   // The order in that list is important.
18877d523365SDimitry Andric   // The blocks will all be inserted before PrologueMBB using that order.
18887d523365SDimitry Andric   // Therefore the block that should appear first in the CFG should appear
18897d523365SDimitry Andric   // first in the list.
18907d523365SDimitry Andric   MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
18917d523365SDimitry Andric                                       PostStackMBB};
18927d523365SDimitry Andric 
18937d523365SDimitry Andric   for (MachineBasicBlock *B : AddedBlocks)
18947d523365SDimitry Andric     BeforePrologueRegion.insert(B);
18957d523365SDimitry Andric 
18967d523365SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
18977d523365SDimitry Andric     for (MachineBasicBlock *PredBB : BeforePrologueRegion)
18987d523365SDimitry Andric       PredBB->addLiveIn(LI);
189991bc56edSDimitry Andric   }
190091bc56edSDimitry Andric 
19017d523365SDimitry Andric   // Remove the newly added blocks from the list, since we know
19027d523365SDimitry Andric   // we do not have to do the following updates for them.
19037d523365SDimitry Andric   for (MachineBasicBlock *B : AddedBlocks) {
19047d523365SDimitry Andric     BeforePrologueRegion.erase(B);
19057d523365SDimitry Andric     MF.insert(PrologueMBB.getIterator(), B);
19067d523365SDimitry Andric   }
19077d523365SDimitry Andric 
19087d523365SDimitry Andric   for (MachineBasicBlock *MBB : BeforePrologueRegion) {
19097d523365SDimitry Andric     // Make sure the LiveIns are still sorted and unique.
19107d523365SDimitry Andric     MBB->sortUniqueLiveIns();
19117d523365SDimitry Andric     // Replace the edges to PrologueMBB by edges to the sequences
19127d523365SDimitry Andric     // we are about to add.
19137d523365SDimitry Andric     MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
19147d523365SDimitry Andric   }
191591bc56edSDimitry Andric 
191691bc56edSDimitry Andric   // The required stack size that is aligned to ARM constant criterion.
191791bc56edSDimitry Andric   AlignedStackSize = alignToARMConstant(StackSize);
191891bc56edSDimitry Andric 
191991bc56edSDimitry Andric   // When the frame size is less than 256 we just compare the stack
192091bc56edSDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
192191bc56edSDimitry Andric   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
192291bc56edSDimitry Andric 
192391bc56edSDimitry Andric   // We will use two of the callee save registers as scratch registers so we
192491bc56edSDimitry Andric   // need to save those registers onto the stack.
192591bc56edSDimitry Andric   // We will use SR0 to hold stack limit and SR1 to hold the stack size
192691bc56edSDimitry Andric   // requested and arguments for __morestack().
192791bc56edSDimitry Andric   // SR0: Scratch Register #0
192891bc56edSDimitry Andric   // SR1: Scratch Register #1
192991bc56edSDimitry Andric   // push {SR0, SR1}
193091bc56edSDimitry Andric   if (Thumb) {
193191bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
193291bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
193391bc56edSDimitry Andric   } else {
193491bc56edSDimitry Andric     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
193591bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
193691bc56edSDimitry Andric         .addReg(ScratchReg0).addReg(ScratchReg1);
193791bc56edSDimitry Andric   }
193891bc56edSDimitry Andric 
193991bc56edSDimitry Andric   // Emit the relevant DWARF information about the change in stack pointer as
194091bc56edSDimitry Andric   // well as where to find both r4 and r5 (the callee-save registers)
194191bc56edSDimitry Andric   CFIIndex =
194291bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
194391bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
194491bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
194591bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
194691bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
194791bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
194891bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
194991bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
195091bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
195191bc56edSDimitry Andric   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
195291bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
195391bc56edSDimitry Andric 
195491bc56edSDimitry Andric   // mov SR1, sp
195591bc56edSDimitry Andric   if (Thumb) {
195691bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
195791bc56edSDimitry Andric                       .addReg(ARM::SP));
195891bc56edSDimitry Andric   } else if (CompareStackPointer) {
195991bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
196091bc56edSDimitry Andric                       .addReg(ARM::SP)).addReg(0);
196191bc56edSDimitry Andric   }
196291bc56edSDimitry Andric 
196391bc56edSDimitry Andric   // sub SR1, sp, #StackSize
196491bc56edSDimitry Andric   if (!CompareStackPointer && Thumb) {
196591bc56edSDimitry Andric     AddDefaultPred(
196691bc56edSDimitry Andric         AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
196791bc56edSDimitry Andric             .addReg(ScratchReg1).addImm(AlignedStackSize));
196891bc56edSDimitry Andric   } else if (!CompareStackPointer) {
196991bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
197091bc56edSDimitry Andric                       .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
197191bc56edSDimitry Andric   }
197291bc56edSDimitry Andric 
197391bc56edSDimitry Andric   if (Thumb && ST->isThumb1Only()) {
197491bc56edSDimitry Andric     unsigned PCLabelId = ARMFI->createPICLabelUId();
197591bc56edSDimitry Andric     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
197691bc56edSDimitry Andric         MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
197791bc56edSDimitry Andric     MachineConstantPool *MCP = MF.getConstantPool();
19787d523365SDimitry Andric     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
197991bc56edSDimitry Andric 
198091bc56edSDimitry Andric     // ldr SR0, [pc, offset(STACK_LIMIT)]
198191bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
198291bc56edSDimitry Andric                       .addConstantPoolIndex(CPI));
198391bc56edSDimitry Andric 
198491bc56edSDimitry Andric     // ldr SR0, [SR0]
198591bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
198691bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(0));
198791bc56edSDimitry Andric   } else {
198891bc56edSDimitry Andric     // Get TLS base address from the coprocessor
198991bc56edSDimitry Andric     // mrc p15, #0, SR0, c13, c0, #3
199091bc56edSDimitry Andric     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
199191bc56edSDimitry Andric                      .addImm(15)
199291bc56edSDimitry Andric                      .addImm(0)
199391bc56edSDimitry Andric                      .addImm(13)
199491bc56edSDimitry Andric                      .addImm(0)
199591bc56edSDimitry Andric                      .addImm(3));
199691bc56edSDimitry Andric 
199791bc56edSDimitry Andric     // Use the last tls slot on android and a private field of the TCP on linux.
199891bc56edSDimitry Andric     assert(ST->isTargetAndroid() || ST->isTargetLinux());
199991bc56edSDimitry Andric     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
200091bc56edSDimitry Andric 
200191bc56edSDimitry Andric     // Get the stack limit from the right offset
200291bc56edSDimitry Andric     // ldr SR0, [sr0, #4 * TlsOffset]
200391bc56edSDimitry Andric     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
200491bc56edSDimitry Andric                       .addReg(ScratchReg0).addImm(4 * TlsOffset));
200591bc56edSDimitry Andric   }
200691bc56edSDimitry Andric 
200791bc56edSDimitry Andric   // Compare stack limit with stack size requested.
200891bc56edSDimitry Andric   // cmp SR0, SR1
200991bc56edSDimitry Andric   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
201091bc56edSDimitry Andric   AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
201191bc56edSDimitry Andric                     .addReg(ScratchReg0)
201291bc56edSDimitry Andric                     .addReg(ScratchReg1));
201391bc56edSDimitry Andric 
201491bc56edSDimitry Andric   // This jump is taken if StackLimit < SP - stack required.
201591bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
201691bc56edSDimitry Andric   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
201791bc56edSDimitry Andric        .addImm(ARMCC::LO)
201891bc56edSDimitry Andric        .addReg(ARM::CPSR);
201991bc56edSDimitry Andric 
202091bc56edSDimitry Andric 
202191bc56edSDimitry Andric   // Calling __morestack(StackSize, Size of stack arguments).
202291bc56edSDimitry Andric   // __morestack knows that the stack size requested is in SR0(r4)
202391bc56edSDimitry Andric   // and amount size of stack arguments is in SR1(r5).
202491bc56edSDimitry Andric 
202591bc56edSDimitry Andric   // Pass first argument for the __morestack by Scratch Register #0.
202691bc56edSDimitry Andric   //   The amount size of stack required
202791bc56edSDimitry Andric   if (Thumb) {
202891bc56edSDimitry Andric     AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
202991bc56edSDimitry Andric                                         ScratchReg0)).addImm(AlignedStackSize));
203091bc56edSDimitry Andric   } else {
203191bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
203291bc56edSDimitry Andric                       .addImm(AlignedStackSize)).addReg(0);
203391bc56edSDimitry Andric   }
203491bc56edSDimitry Andric   // Pass second argument for the __morestack by Scratch Register #1.
203591bc56edSDimitry Andric   //   The amount size of stack consumed to save function arguments.
203691bc56edSDimitry Andric   if (Thumb) {
203791bc56edSDimitry Andric     AddDefaultPred(
203891bc56edSDimitry Andric         AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
203991bc56edSDimitry Andric             .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
204091bc56edSDimitry Andric   } else {
204191bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
204291bc56edSDimitry Andric                    .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
204391bc56edSDimitry Andric                    .addReg(0);
204491bc56edSDimitry Andric   }
204591bc56edSDimitry Andric 
204691bc56edSDimitry Andric   // push {lr} - Save return address of this function.
204791bc56edSDimitry Andric   if (Thumb) {
204891bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
204991bc56edSDimitry Andric         .addReg(ARM::LR);
205091bc56edSDimitry Andric   } else {
205191bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
205291bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
205391bc56edSDimitry Andric                    .addReg(ARM::SP))
205491bc56edSDimitry Andric         .addReg(ARM::LR);
205591bc56edSDimitry Andric   }
205691bc56edSDimitry Andric 
205791bc56edSDimitry Andric   // Emit the DWARF info about the change in stack as well as where to find the
205891bc56edSDimitry Andric   // previous link register
205991bc56edSDimitry Andric   CFIIndex =
206091bc56edSDimitry Andric       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
206191bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
206291bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
206391bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
206491bc56edSDimitry Andric         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
206591bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
206691bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
206791bc56edSDimitry Andric 
206891bc56edSDimitry Andric   // Call __morestack().
206991bc56edSDimitry Andric   if (Thumb) {
207091bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
207191bc56edSDimitry Andric         .addExternalSymbol("__morestack");
207291bc56edSDimitry Andric   } else {
207391bc56edSDimitry Andric     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
207491bc56edSDimitry Andric         .addExternalSymbol("__morestack");
207591bc56edSDimitry Andric   }
207691bc56edSDimitry Andric 
207791bc56edSDimitry Andric   // pop {lr} - Restore return address of this original function.
207891bc56edSDimitry Andric   if (Thumb) {
207991bc56edSDimitry Andric     if (ST->isThumb1Only()) {
208091bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
208191bc56edSDimitry Andric                      .addReg(ScratchReg0);
208291bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
208391bc56edSDimitry Andric                      .addReg(ScratchReg0));
208491bc56edSDimitry Andric     } else {
208591bc56edSDimitry Andric       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
208691bc56edSDimitry Andric                      .addReg(ARM::LR, RegState::Define)
208791bc56edSDimitry Andric                      .addReg(ARM::SP, RegState::Define)
208891bc56edSDimitry Andric                      .addReg(ARM::SP)
208991bc56edSDimitry Andric                      .addImm(4));
209091bc56edSDimitry Andric     }
209191bc56edSDimitry Andric   } else {
209291bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
209391bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
209491bc56edSDimitry Andric                    .addReg(ARM::SP))
209591bc56edSDimitry Andric       .addReg(ARM::LR);
209691bc56edSDimitry Andric   }
209791bc56edSDimitry Andric 
209891bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was called.
209991bc56edSDimitry Andric   // __morestack() will skip PostStackMBB block so we need to restore
210091bc56edSDimitry Andric   // scratch registers from here.
210191bc56edSDimitry Andric   // pop {SR0, SR1}
210291bc56edSDimitry Andric   if (Thumb) {
210391bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
210491bc56edSDimitry Andric       .addReg(ScratchReg0)
210591bc56edSDimitry Andric       .addReg(ScratchReg1);
210691bc56edSDimitry Andric   } else {
210791bc56edSDimitry Andric     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
210891bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
210991bc56edSDimitry Andric                    .addReg(ARM::SP))
211091bc56edSDimitry Andric       .addReg(ScratchReg0)
211191bc56edSDimitry Andric       .addReg(ScratchReg1);
211291bc56edSDimitry Andric   }
211391bc56edSDimitry Andric 
211491bc56edSDimitry Andric   // Update the CFA offset now that we've popped
211591bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
211691bc56edSDimitry Andric   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
211791bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
211891bc56edSDimitry Andric 
211991bc56edSDimitry Andric   // bx lr - Return from this function.
212091bc56edSDimitry Andric   Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
212191bc56edSDimitry Andric   AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
212291bc56edSDimitry Andric 
212391bc56edSDimitry Andric   // Restore SR0 and SR1 in case of __morestack() was not called.
212491bc56edSDimitry Andric   // pop {SR0, SR1}
212591bc56edSDimitry Andric   if (Thumb) {
212691bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
212791bc56edSDimitry Andric       .addReg(ScratchReg0)
212891bc56edSDimitry Andric       .addReg(ScratchReg1);
212991bc56edSDimitry Andric   } else {
213091bc56edSDimitry Andric     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
213191bc56edSDimitry Andric                    .addReg(ARM::SP, RegState::Define)
213291bc56edSDimitry Andric                    .addReg(ARM::SP))
213391bc56edSDimitry Andric       .addReg(ScratchReg0)
213491bc56edSDimitry Andric       .addReg(ScratchReg1);
213591bc56edSDimitry Andric   }
213691bc56edSDimitry Andric 
213791bc56edSDimitry Andric   // Update the CFA offset now that we've popped
213891bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
213991bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
214091bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
214191bc56edSDimitry Andric 
214291bc56edSDimitry Andric   // Tell debuggers that r4 and r5 are now the same as they were in the
214391bc56edSDimitry Andric   // previous function, that they're the "Same Value".
214491bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
214591bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
214691bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
214791bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
214891bc56edSDimitry Andric   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
214991bc56edSDimitry Andric       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
215091bc56edSDimitry Andric   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
215191bc56edSDimitry Andric       .addCFIIndex(CFIIndex);
215291bc56edSDimitry Andric 
215391bc56edSDimitry Andric   // Organizing MBB lists
2154ff0cc061SDimitry Andric   PostStackMBB->addSuccessor(&PrologueMBB);
215591bc56edSDimitry Andric 
215691bc56edSDimitry Andric   AllocMBB->addSuccessor(PostStackMBB);
215791bc56edSDimitry Andric 
215891bc56edSDimitry Andric   GetMBB->addSuccessor(PostStackMBB);
215991bc56edSDimitry Andric   GetMBB->addSuccessor(AllocMBB);
216091bc56edSDimitry Andric 
216191bc56edSDimitry Andric   McrMBB->addSuccessor(GetMBB);
216291bc56edSDimitry Andric 
216391bc56edSDimitry Andric   PrevStackMBB->addSuccessor(McrMBB);
216491bc56edSDimitry Andric 
216591bc56edSDimitry Andric #ifdef XDEBUG
216691bc56edSDimitry Andric   MF.verify();
216791bc56edSDimitry Andric #endif
216891bc56edSDimitry Andric }
2169