1 //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the ARM implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ARMFrameLowering.h"
14 #include "ARMBaseInstrInfo.h"
15 #include "ARMBaseRegisterInfo.h"
16 #include "ARMConstantPoolValue.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMSubtarget.h"
19 #include "MCTargetDesc/ARMAddressingModes.h"
20 #include "MCTargetDesc/ARMBaseInfo.h"
21 #include "Utils/ARMBaseInfo.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/RegisterScavenging.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetOpcodes.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/CallingConv.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCDwarf.h"
47 #include "llvm/MC/MCInstrDesc.h"
48 #include "llvm/MC/MCRegisterInfo.h"
49 #include "llvm/Support/CodeGen.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetMachine.h"
57 #include "llvm/Target/TargetOptions.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstddef>
61 #include <cstdint>
62 #include <iterator>
63 #include <utility>
64 #include <vector>
65 
66 #define DEBUG_TYPE "arm-frame-lowering"
67 
68 using namespace llvm;
69 
70 static cl::opt<bool>
71 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
72                      cl::desc("Align ARM NEON spills in prolog and epilog"));
73 
74 static MachineBasicBlock::iterator
75 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
76                         unsigned NumAlignedDPRCS2Regs);
77 
78 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
79     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
80       STI(sti) {}
81 
82 bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
83   // iOS always has a FP for backtracking, force other targets to keep their FP
84   // when doing FastISel. The emitted code is currently superior, and in cases
85   // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
86   return MF.getSubtarget<ARMSubtarget>().useFastISel();
87 }
88 
89 /// Returns true if the target can safely skip saving callee-saved registers
90 /// for noreturn nounwind functions.
91 bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
92   assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
93          MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
94          !MF.getFunction().hasFnAttribute(Attribute::UWTable));
95 
96   // Frame pointer and link register are not treated as normal CSR, thus we
97   // can always skip CSR saves for nonreturning functions.
98   return true;
99 }
100 
101 /// hasFP - Return true if the specified function should have a dedicated frame
102 /// pointer register.  This is true if the function has variable sized allocas
103 /// or if frame pointer elimination is disabled.
104 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
105   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
106   const MachineFrameInfo &MFI = MF.getFrameInfo();
107 
108   // ABI-required frame pointer.
109   if (MF.getTarget().Options.DisableFramePointerElim(MF))
110     return true;
111 
112   // Frame pointer required for use within this function.
113   return (RegInfo->needsStackRealignment(MF) ||
114           MFI.hasVarSizedObjects() ||
115           MFI.isFrameAddressTaken());
116 }
117 
118 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
119 /// not required, we reserve argument space for call sites in the function
120 /// immediately on entry to the current function.  This eliminates the need for
121 /// add/sub sp brackets around call sites.  Returns true if the call frame is
122 /// included as part of the stack frame.
123 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
124   const MachineFrameInfo &MFI = MF.getFrameInfo();
125   unsigned CFSize = MFI.getMaxCallFrameSize();
126   // It's not always a good idea to include the call frame as part of the
127   // stack frame. ARM (especially Thumb) has small immediate offset to
128   // address the stack frame. So a large call frame can cause poor codegen
129   // and may even makes it impossible to scavenge a register.
130   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
131     return false;
132 
133   return !MFI.hasVarSizedObjects();
134 }
135 
136 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
137 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
138 /// is not sufficient here since we still may reference some objects via SP
139 /// even when FP is available in Thumb2 mode.
140 bool
141 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
142   return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
143 }
144 
145 static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
146                         const MCPhysReg *CSRegs) {
147   // Integer spill area is handled with "pop".
148   if (isPopOpcode(MI.getOpcode())) {
149     // The first two operands are predicates. The last two are
150     // imp-def and imp-use of SP. Check everything in between.
151     for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
152       if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
153         return false;
154     return true;
155   }
156   if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
157        MI.getOpcode() == ARM::LDR_POST_REG ||
158        MI.getOpcode() == ARM::t2LDR_POST) &&
159       isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
160       MI.getOperand(1).getReg() == ARM::SP)
161     return true;
162 
163   return false;
164 }
165 
166 static void emitRegPlusImmediate(
167     bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
168     const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
169     unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
170     ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
171   if (isARM)
172     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
173                             Pred, PredReg, TII, MIFlags);
174   else
175     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
176                            Pred, PredReg, TII, MIFlags);
177 }
178 
179 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
180                          MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
181                          const ARMBaseInstrInfo &TII, int NumBytes,
182                          unsigned MIFlags = MachineInstr::NoFlags,
183                          ARMCC::CondCodes Pred = ARMCC::AL,
184                          unsigned PredReg = 0) {
185   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
186                        MIFlags, Pred, PredReg);
187 }
188 
189 static int sizeOfSPAdjustment(const MachineInstr &MI) {
190   int RegSize;
191   switch (MI.getOpcode()) {
192   case ARM::VSTMDDB_UPD:
193     RegSize = 8;
194     break;
195   case ARM::STMDB_UPD:
196   case ARM::t2STMDB_UPD:
197     RegSize = 4;
198     break;
199   case ARM::t2STR_PRE:
200   case ARM::STR_PRE_IMM:
201     return 4;
202   default:
203     llvm_unreachable("Unknown push or pop like instruction");
204   }
205 
206   int count = 0;
207   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
208   // pred) so the list starts at 4.
209   for (int i = MI.getNumOperands() - 1; i >= 4; --i)
210     count += RegSize;
211   return count;
212 }
213 
214 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
215                                       size_t StackSizeInBytes) {
216   const MachineFrameInfo &MFI = MF.getFrameInfo();
217   const Function &F = MF.getFunction();
218   unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
219   if (F.hasFnAttribute("stack-probe-size"))
220     F.getFnAttribute("stack-probe-size")
221         .getValueAsString()
222         .getAsInteger(0, StackProbeSize);
223   return (StackSizeInBytes >= StackProbeSize) &&
224          !F.hasFnAttribute("no-stack-arg-probe");
225 }
226 
227 namespace {
228 
229 struct StackAdjustingInsts {
230   struct InstInfo {
231     MachineBasicBlock::iterator I;
232     unsigned SPAdjust;
233     bool BeforeFPSet;
234   };
235 
236   SmallVector<InstInfo, 4> Insts;
237 
238   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
239                bool BeforeFPSet = false) {
240     InstInfo Info = {I, SPAdjust, BeforeFPSet};
241     Insts.push_back(Info);
242   }
243 
244   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
245     auto Info =
246         llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
247     assert(Info != Insts.end() && "invalid sp adjusting instruction");
248     Info->SPAdjust += ExtraBytes;
249   }
250 
251   void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
252                          const ARMBaseInstrInfo &TII, bool HasFP) {
253     MachineFunction &MF = *MBB.getParent();
254     unsigned CFAOffset = 0;
255     for (auto &Info : Insts) {
256       if (HasFP && !Info.BeforeFPSet)
257         return;
258 
259       CFAOffset -= Info.SPAdjust;
260       unsigned CFIIndex = MF.addFrameInst(
261           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
262       BuildMI(MBB, std::next(Info.I), dl,
263               TII.get(TargetOpcode::CFI_INSTRUCTION))
264               .addCFIIndex(CFIIndex)
265               .setMIFlags(MachineInstr::FrameSetup);
266     }
267   }
268 };
269 
270 } // end anonymous namespace
271 
272 /// Emit an instruction sequence that will align the address in
273 /// register Reg by zero-ing out the lower bits.  For versions of the
274 /// architecture that support Neon, this must be done in a single
275 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
276 /// single instruction. That function only gets called when optimizing
277 /// spilling of D registers on a core with the Neon instruction set
278 /// present.
279 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
280                                      const TargetInstrInfo &TII,
281                                      MachineBasicBlock &MBB,
282                                      MachineBasicBlock::iterator MBBI,
283                                      const DebugLoc &DL, const unsigned Reg,
284                                      const unsigned Alignment,
285                                      const bool MustBeSingleInstruction) {
286   const ARMSubtarget &AST =
287       static_cast<const ARMSubtarget &>(MF.getSubtarget());
288   const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
289   const unsigned AlignMask = Alignment - 1;
290   const unsigned NrBitsToZero = countTrailingZeros(Alignment);
291   assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
292   if (!AFI->isThumbFunction()) {
293     // if the BFC instruction is available, use that to zero the lower
294     // bits:
295     //   bfc Reg, #0, log2(Alignment)
296     // otherwise use BIC, if the mask to zero the required number of bits
297     // can be encoded in the bic immediate field
298     //   bic Reg, Reg, Alignment-1
299     // otherwise, emit
300     //   lsr Reg, Reg, log2(Alignment)
301     //   lsl Reg, Reg, log2(Alignment)
302     if (CanUseBFC) {
303       BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
304           .addReg(Reg, RegState::Kill)
305           .addImm(~AlignMask)
306           .add(predOps(ARMCC::AL));
307     } else if (AlignMask <= 255) {
308       BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
309           .addReg(Reg, RegState::Kill)
310           .addImm(AlignMask)
311           .add(predOps(ARMCC::AL))
312           .add(condCodeOp());
313     } else {
314       assert(!MustBeSingleInstruction &&
315              "Shouldn't call emitAligningInstructions demanding a single "
316              "instruction to be emitted for large stack alignment for a target "
317              "without BFC.");
318       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
319           .addReg(Reg, RegState::Kill)
320           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
321           .add(predOps(ARMCC::AL))
322           .add(condCodeOp());
323       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
324           .addReg(Reg, RegState::Kill)
325           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
326           .add(predOps(ARMCC::AL))
327           .add(condCodeOp());
328     }
329   } else {
330     // Since this is only reached for Thumb-2 targets, the BFC instruction
331     // should always be available.
332     assert(CanUseBFC);
333     BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
334         .addReg(Reg, RegState::Kill)
335         .addImm(~AlignMask)
336         .add(predOps(ARMCC::AL));
337   }
338 }
339 
340 /// We need the offset of the frame pointer relative to other MachineFrameInfo
341 /// offsets which are encoded relative to SP at function begin.
342 /// See also emitPrologue() for how the FP is set up.
343 /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
344 /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
345 /// this to produce a conservative estimate that we check in an assert() later.
346 static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
347   // For Thumb1, push.w isn't available, so the first push will always push
348   // r7 and lr onto the stack first.
349   if (AFI.isThumb1OnlyFunction())
350     return -AFI.getArgRegsSaveSize() - (2 * 4);
351   // This is a conservative estimation: Assume the frame pointer being r7 and
352   // pc("r15") up to r8 getting spilled before (= 8 registers).
353   return -AFI.getArgRegsSaveSize() - (8 * 4);
354 }
355 
356 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
357                                     MachineBasicBlock &MBB) const {
358   MachineBasicBlock::iterator MBBI = MBB.begin();
359   MachineFrameInfo  &MFI = MF.getFrameInfo();
360   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
361   MachineModuleInfo &MMI = MF.getMMI();
362   MCContext &Context = MMI.getContext();
363   const TargetMachine &TM = MF.getTarget();
364   const MCRegisterInfo *MRI = Context.getRegisterInfo();
365   const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
366   const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
367   assert(!AFI->isThumb1OnlyFunction() &&
368          "This emitPrologue does not support Thumb1!");
369   bool isARM = !AFI->isThumbFunction();
370   unsigned Align = STI.getFrameLowering()->getStackAlignment();
371   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
372   unsigned NumBytes = MFI.getStackSize();
373   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
374 
375   // Debug location must be unknown since the first debug location is used
376   // to determine the end of the prologue.
377   DebugLoc dl;
378 
379   Register FramePtr = RegInfo->getFrameRegister(MF);
380 
381   // Determine the sizes of each callee-save spill areas and record which frame
382   // belongs to which callee-save spill areas.
383   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
384   int FramePtrSpillFI = 0;
385   int D8SpillFI = 0;
386 
387   // All calls are tail calls in GHC calling conv, and functions have no
388   // prologue/epilogue.
389   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
390     return;
391 
392   StackAdjustingInsts DefCFAOffsetCandidates;
393   bool HasFP = hasFP(MF);
394 
395   // Allocate the vararg register save area.
396   if (ArgRegsSaveSize) {
397     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
398                  MachineInstr::FrameSetup);
399     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
400   }
401 
402   if (!AFI->hasStackFrame() &&
403       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
404     if (NumBytes - ArgRegsSaveSize != 0) {
405       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
406                    MachineInstr::FrameSetup);
407       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
408                                      NumBytes - ArgRegsSaveSize, true);
409     }
410     DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
411     return;
412   }
413 
414   // Determine spill area sizes.
415   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
416     unsigned Reg = CSI[i].getReg();
417     int FI = CSI[i].getFrameIdx();
418     switch (Reg) {
419     case ARM::R8:
420     case ARM::R9:
421     case ARM::R10:
422     case ARM::R11:
423     case ARM::R12:
424       if (STI.splitFramePushPop(MF)) {
425         GPRCS2Size += 4;
426         break;
427       }
428       LLVM_FALLTHROUGH;
429     case ARM::R0:
430     case ARM::R1:
431     case ARM::R2:
432     case ARM::R3:
433     case ARM::R4:
434     case ARM::R5:
435     case ARM::R6:
436     case ARM::R7:
437     case ARM::LR:
438       if (Reg == FramePtr)
439         FramePtrSpillFI = FI;
440       GPRCS1Size += 4;
441       break;
442     default:
443       // This is a DPR. Exclude the aligned DPRCS2 spills.
444       if (Reg == ARM::D8)
445         D8SpillFI = FI;
446       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
447         DPRCSSize += 8;
448     }
449   }
450 
451   // Move past area 1.
452   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
453   if (GPRCS1Size > 0) {
454     GPRCS1Push = LastPush = MBBI++;
455     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
456   }
457 
458   // Determine starting offsets of spill areas.
459   unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
460   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
461   unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
462   unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
463   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
464   int FramePtrOffsetInPush = 0;
465   if (HasFP) {
466     int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
467     assert(getMaxFPOffset(MF.getFunction(), *AFI) <= FPOffset &&
468            "Max FP estimation is wrong");
469     FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
470     AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
471                                 NumBytes);
472   }
473   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
474   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
475   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
476 
477   // Move past area 2.
478   if (GPRCS2Size > 0) {
479     GPRCS2Push = LastPush = MBBI++;
480     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
481   }
482 
483   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
484   // .cfi_offset operations will reflect that.
485   if (DPRGapSize) {
486     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
487     if (LastPush != MBB.end() &&
488         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
489       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
490     else {
491       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
492                    MachineInstr::FrameSetup);
493       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
494     }
495   }
496 
497   // Move past area 3.
498   if (DPRCSSize > 0) {
499     // Since vpush register list cannot have gaps, there may be multiple vpush
500     // instructions in the prologue.
501     while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
502       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
503       LastPush = MBBI++;
504     }
505   }
506 
507   // Move past the aligned DPRCS2 area.
508   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
509     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
510     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
511     // leaves the stack pointer pointing to the DPRCS2 area.
512     //
513     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
514     NumBytes += MFI.getObjectOffset(D8SpillFI);
515   } else
516     NumBytes = DPRCSOffset;
517 
518   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
519     uint32_t NumWords = NumBytes >> 2;
520 
521     if (NumWords < 65536)
522       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
523           .addImm(NumWords)
524           .setMIFlags(MachineInstr::FrameSetup)
525           .add(predOps(ARMCC::AL));
526     else
527       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
528         .addImm(NumWords)
529         .setMIFlags(MachineInstr::FrameSetup);
530 
531     switch (TM.getCodeModel()) {
532     case CodeModel::Tiny:
533       llvm_unreachable("Tiny code model not available on ARM.");
534     case CodeModel::Small:
535     case CodeModel::Medium:
536     case CodeModel::Kernel:
537       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
538           .add(predOps(ARMCC::AL))
539           .addExternalSymbol("__chkstk")
540           .addReg(ARM::R4, RegState::Implicit)
541           .setMIFlags(MachineInstr::FrameSetup);
542       break;
543     case CodeModel::Large:
544       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
545         .addExternalSymbol("__chkstk")
546         .setMIFlags(MachineInstr::FrameSetup);
547 
548       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
549           .add(predOps(ARMCC::AL))
550           .addReg(ARM::R12, RegState::Kill)
551           .addReg(ARM::R4, RegState::Implicit)
552           .setMIFlags(MachineInstr::FrameSetup);
553       break;
554     }
555 
556     BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
557         .addReg(ARM::SP, RegState::Kill)
558         .addReg(ARM::R4, RegState::Kill)
559         .setMIFlags(MachineInstr::FrameSetup)
560         .add(predOps(ARMCC::AL))
561         .add(condCodeOp());
562     NumBytes = 0;
563   }
564 
565   if (NumBytes) {
566     // Adjust SP after all the callee-save spills.
567     if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
568         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
569       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
570     else {
571       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
572                    MachineInstr::FrameSetup);
573       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
574     }
575 
576     if (HasFP && isARM)
577       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
578       // Note it's not safe to do this in Thumb2 mode because it would have
579       // taken two instructions:
580       // mov sp, r7
581       // sub sp, #24
582       // If an interrupt is taken between the two instructions, then sp is in
583       // an inconsistent state (pointing to the middle of callee-saved area).
584       // The interrupt handler can end up clobbering the registers.
585       AFI->setShouldRestoreSPFromFP(true);
586   }
587 
588   // Set FP to point to the stack slot that contains the previous FP.
589   // For iOS, FP is R7, which has now been stored in spill area 1.
590   // Otherwise, if this is not iOS, all the callee-saved registers go
591   // into spill area 1, including the FP in R11.  In either case, it
592   // is in area one and the adjustment needs to take place just after
593   // that push.
594   if (HasFP) {
595     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
596     unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
597     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
598                          dl, TII, FramePtr, ARM::SP,
599                          PushSize + FramePtrOffsetInPush,
600                          MachineInstr::FrameSetup);
601     if (FramePtrOffsetInPush + PushSize != 0) {
602       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
603           nullptr, MRI->getDwarfRegNum(FramePtr, true),
604           -(ArgRegsSaveSize - FramePtrOffsetInPush)));
605       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
606           .addCFIIndex(CFIIndex)
607           .setMIFlags(MachineInstr::FrameSetup);
608     } else {
609       unsigned CFIIndex =
610           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
611               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
612       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
613           .addCFIIndex(CFIIndex)
614           .setMIFlags(MachineInstr::FrameSetup);
615     }
616   }
617 
618   // Now that the prologue's actual instructions are finalised, we can insert
619   // the necessary DWARF cf instructions to describe the situation. Start by
620   // recording where each register ended up:
621   if (GPRCS1Size > 0) {
622     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
623     int CFIIndex;
624     for (const auto &Entry : CSI) {
625       unsigned Reg = Entry.getReg();
626       int FI = Entry.getFrameIdx();
627       switch (Reg) {
628       case ARM::R8:
629       case ARM::R9:
630       case ARM::R10:
631       case ARM::R11:
632       case ARM::R12:
633         if (STI.splitFramePushPop(MF))
634           break;
635         LLVM_FALLTHROUGH;
636       case ARM::R0:
637       case ARM::R1:
638       case ARM::R2:
639       case ARM::R3:
640       case ARM::R4:
641       case ARM::R5:
642       case ARM::R6:
643       case ARM::R7:
644       case ARM::LR:
645         CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
646             nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
647         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
648             .addCFIIndex(CFIIndex)
649             .setMIFlags(MachineInstr::FrameSetup);
650         break;
651       }
652     }
653   }
654 
655   if (GPRCS2Size > 0) {
656     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
657     for (const auto &Entry : CSI) {
658       unsigned Reg = Entry.getReg();
659       int FI = Entry.getFrameIdx();
660       switch (Reg) {
661       case ARM::R8:
662       case ARM::R9:
663       case ARM::R10:
664       case ARM::R11:
665       case ARM::R12:
666         if (STI.splitFramePushPop(MF)) {
667           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
668           unsigned Offset = MFI.getObjectOffset(FI);
669           unsigned CFIIndex = MF.addFrameInst(
670               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
671           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
672               .addCFIIndex(CFIIndex)
673               .setMIFlags(MachineInstr::FrameSetup);
674         }
675         break;
676       }
677     }
678   }
679 
680   if (DPRCSSize > 0) {
681     // Since vpush register list cannot have gaps, there may be multiple vpush
682     // instructions in the prologue.
683     MachineBasicBlock::iterator Pos = std::next(LastPush);
684     for (const auto &Entry : CSI) {
685       unsigned Reg = Entry.getReg();
686       int FI = Entry.getFrameIdx();
687       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
688           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
689         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
690         unsigned Offset = MFI.getObjectOffset(FI);
691         unsigned CFIIndex = MF.addFrameInst(
692             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
693         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
694             .addCFIIndex(CFIIndex)
695             .setMIFlags(MachineInstr::FrameSetup);
696       }
697     }
698   }
699 
700   // Now we can emit descriptions of where the canonical frame address was
701   // throughout the process. If we have a frame pointer, it takes over the job
702   // half-way through, so only the first few .cfi_def_cfa_offset instructions
703   // actually get emitted.
704   DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
705 
706   if (STI.isTargetELF() && hasFP(MF))
707     MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
708                             AFI->getFramePtrSpillOffset());
709 
710   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
711   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
712   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
713   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
714 
715   // If we need dynamic stack realignment, do it here. Be paranoid and make
716   // sure if we also have VLAs, we have a base pointer for frame access.
717   // If aligned NEON registers were spilled, the stack has already been
718   // realigned.
719   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
720     unsigned MaxAlign = MFI.getMaxAlignment();
721     assert(!AFI->isThumb1OnlyFunction());
722     if (!AFI->isThumbFunction()) {
723       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
724                                false);
725     } else {
726       // We cannot use sp as source/dest register here, thus we're using r4 to
727       // perform the calculations. We're emitting the following sequence:
728       // mov r4, sp
729       // -- use emitAligningInstructions to produce best sequence to zero
730       // -- out lower bits in r4
731       // mov sp, r4
732       // FIXME: It will be better just to find spare register here.
733       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
734           .addReg(ARM::SP, RegState::Kill)
735           .add(predOps(ARMCC::AL));
736       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
737                                false);
738       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
739           .addReg(ARM::R4, RegState::Kill)
740           .add(predOps(ARMCC::AL));
741     }
742 
743     AFI->setShouldRestoreSPFromFP(true);
744   }
745 
746   // If we need a base pointer, set it up here. It's whatever the value
747   // of the stack pointer is at this point. Any variable size objects
748   // will be allocated after this, so we can still use the base pointer
749   // to reference locals.
750   // FIXME: Clarify FrameSetup flags here.
751   if (RegInfo->hasBasePointer(MF)) {
752     if (isARM)
753       BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
754           .addReg(ARM::SP)
755           .add(predOps(ARMCC::AL))
756           .add(condCodeOp());
757     else
758       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
759           .addReg(ARM::SP)
760           .add(predOps(ARMCC::AL));
761   }
762 
763   // If the frame has variable sized objects then the epilogue must restore
764   // the sp from fp. We can assume there's an FP here since hasFP already
765   // checks for hasVarSizedObjects.
766   if (MFI.hasVarSizedObjects())
767     AFI->setShouldRestoreSPFromFP(true);
768 }
769 
770 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
771                                     MachineBasicBlock &MBB) const {
772   MachineFrameInfo &MFI = MF.getFrameInfo();
773   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
774   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
775   const ARMBaseInstrInfo &TII =
776       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
777   assert(!AFI->isThumb1OnlyFunction() &&
778          "This emitEpilogue does not support Thumb1!");
779   bool isARM = !AFI->isThumbFunction();
780 
781   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
782   int NumBytes = (int)MFI.getStackSize();
783   Register FramePtr = RegInfo->getFrameRegister(MF);
784 
785   // All calls are tail calls in GHC calling conv, and functions have no
786   // prologue/epilogue.
787   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
788     return;
789 
790   // First put ourselves on the first (from top) terminator instructions.
791   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
792   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
793 
794   if (!AFI->hasStackFrame()) {
795     if (NumBytes - ArgRegsSaveSize != 0)
796       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
797   } else {
798     // Unwind MBBI to point to first LDR / VLDRD.
799     const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
800     if (MBBI != MBB.begin()) {
801       do {
802         --MBBI;
803       } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
804       if (!isCSRestore(*MBBI, TII, CSRegs))
805         ++MBBI;
806     }
807 
808     // Move SP to start of FP callee save spill area.
809     NumBytes -= (ArgRegsSaveSize +
810                  AFI->getGPRCalleeSavedArea1Size() +
811                  AFI->getGPRCalleeSavedArea2Size() +
812                  AFI->getDPRCalleeSavedGapSize() +
813                  AFI->getDPRCalleeSavedAreaSize());
814 
815     // Reset SP based on frame pointer only if the stack frame extends beyond
816     // frame pointer stack slot or target is ELF and the function has FP.
817     if (AFI->shouldRestoreSPFromFP()) {
818       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
819       if (NumBytes) {
820         if (isARM)
821           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
822                                   ARMCC::AL, 0, TII);
823         else {
824           // It's not possible to restore SP from FP in a single instruction.
825           // For iOS, this looks like:
826           // mov sp, r7
827           // sub sp, #24
828           // This is bad, if an interrupt is taken after the mov, sp is in an
829           // inconsistent state.
830           // Use the first callee-saved register as a scratch register.
831           assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
832                  "No scratch register to restore SP from FP!");
833           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
834                                  ARMCC::AL, 0, TII);
835           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
836               .addReg(ARM::R4)
837               .add(predOps(ARMCC::AL));
838         }
839       } else {
840         // Thumb2 or ARM.
841         if (isARM)
842           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
843               .addReg(FramePtr)
844               .add(predOps(ARMCC::AL))
845               .add(condCodeOp());
846         else
847           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
848               .addReg(FramePtr)
849               .add(predOps(ARMCC::AL));
850       }
851     } else if (NumBytes &&
852                !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
853       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
854 
855     // Increment past our save areas.
856     if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
857       MBBI++;
858       // Since vpop register list cannot have gaps, there may be multiple vpop
859       // instructions in the epilogue.
860       while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
861         MBBI++;
862     }
863     if (AFI->getDPRCalleeSavedGapSize()) {
864       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
865              "unexpected DPR alignment gap");
866       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
867     }
868 
869     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
870     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
871   }
872 
873   if (ArgRegsSaveSize)
874     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
875 }
876 
877 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
878 /// debug info.  It's the same as what we use for resolving the code-gen
879 /// references for now.  FIXME: This can go wrong when references are
880 /// SP-relative and simple call frames aren't used.
881 int
882 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
883                                          unsigned &FrameReg) const {
884   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
885 }
886 
887 int
888 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
889                                              int FI, unsigned &FrameReg,
890                                              int SPAdj) const {
891   const MachineFrameInfo &MFI = MF.getFrameInfo();
892   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
893       MF.getSubtarget().getRegisterInfo());
894   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
895   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
896   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
897   bool isFixed = MFI.isFixedObjectIndex(FI);
898 
899   FrameReg = ARM::SP;
900   Offset += SPAdj;
901 
902   // SP can move around if there are allocas.  We may also lose track of SP
903   // when emergency spilling inside a non-reserved call frame setup.
904   bool hasMovingSP = !hasReservedCallFrame(MF);
905 
906   // When dynamically realigning the stack, use the frame pointer for
907   // parameters, and the stack/base pointer for locals.
908   if (RegInfo->needsStackRealignment(MF)) {
909     assert(hasFP(MF) && "dynamic stack realignment without a FP!");
910     if (isFixed) {
911       FrameReg = RegInfo->getFrameRegister(MF);
912       Offset = FPOffset;
913     } else if (hasMovingSP) {
914       assert(RegInfo->hasBasePointer(MF) &&
915              "VLAs and dynamic stack alignment, but missing base pointer!");
916       FrameReg = RegInfo->getBaseRegister();
917       Offset -= SPAdj;
918     }
919     return Offset;
920   }
921 
922   // If there is a frame pointer, use it when we can.
923   if (hasFP(MF) && AFI->hasStackFrame()) {
924     // Use frame pointer to reference fixed objects. Use it for locals if
925     // there are VLAs (and thus the SP isn't reliable as a base).
926     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
927       FrameReg = RegInfo->getFrameRegister(MF);
928       return FPOffset;
929     } else if (hasMovingSP) {
930       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
931       if (AFI->isThumb2Function()) {
932         // Try to use the frame pointer if we can, else use the base pointer
933         // since it's available. This is handy for the emergency spill slot, in
934         // particular.
935         if (FPOffset >= -255 && FPOffset < 0) {
936           FrameReg = RegInfo->getFrameRegister(MF);
937           return FPOffset;
938         }
939       }
940     } else if (AFI->isThumbFunction()) {
941       // Prefer SP to base pointer, if the offset is suitably aligned and in
942       // range as the effective range of the immediate offset is bigger when
943       // basing off SP.
944       // Use  add <rd>, sp, #<imm8>
945       //      ldr <rd>, [sp, #<imm8>]
946       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
947         return Offset;
948       // In Thumb2 mode, the negative offset is very limited. Try to avoid
949       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
950       if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
951         FrameReg = RegInfo->getFrameRegister(MF);
952         return FPOffset;
953       }
954     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
955       // Otherwise, use SP or FP, whichever is closer to the stack slot.
956       FrameReg = RegInfo->getFrameRegister(MF);
957       return FPOffset;
958     }
959   }
960   // Use the base pointer if we have one.
961   // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
962   // That can happen if we forced a base pointer for a large call frame.
963   if (RegInfo->hasBasePointer(MF)) {
964     FrameReg = RegInfo->getBaseRegister();
965     Offset -= SPAdj;
966   }
967   return Offset;
968 }
969 
970 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
971                                     MachineBasicBlock::iterator MI,
972                                     ArrayRef<CalleeSavedInfo> CSI,
973                                     unsigned StmOpc, unsigned StrOpc,
974                                     bool NoGap, bool (*Func)(unsigned, bool),
975                                     unsigned NumAlignedDPRCS2Regs,
976                                     unsigned MIFlags) const {
977   MachineFunction &MF = *MBB.getParent();
978   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
979   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
980 
981   DebugLoc DL;
982 
983   using RegAndKill = std::pair<unsigned, bool>;
984 
985   SmallVector<RegAndKill, 4> Regs;
986   unsigned i = CSI.size();
987   while (i != 0) {
988     unsigned LastReg = 0;
989     for (; i != 0; --i) {
990       unsigned Reg = CSI[i-1].getReg();
991       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
992 
993       // D-registers in the aligned area DPRCS2 are NOT spilled here.
994       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
995         continue;
996 
997       const MachineRegisterInfo &MRI = MF.getRegInfo();
998       bool isLiveIn = MRI.isLiveIn(Reg);
999       if (!isLiveIn && !MRI.isReserved(Reg))
1000         MBB.addLiveIn(Reg);
1001       // If NoGap is true, push consecutive registers and then leave the rest
1002       // for other instructions. e.g.
1003       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
1004       if (NoGap && LastReg && LastReg != Reg-1)
1005         break;
1006       LastReg = Reg;
1007       // Do not set a kill flag on values that are also marked as live-in. This
1008       // happens with the @llvm-returnaddress intrinsic and with arguments
1009       // passed in callee saved registers.
1010       // Omitting the kill flags is conservatively correct even if the live-in
1011       // is not used after all.
1012       Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
1013     }
1014 
1015     if (Regs.empty())
1016       continue;
1017 
1018     llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1019       return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1020     });
1021 
1022     if (Regs.size() > 1 || StrOpc== 0) {
1023       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1024                                     .addReg(ARM::SP)
1025                                     .setMIFlags(MIFlags)
1026                                     .add(predOps(ARMCC::AL));
1027       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1028         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
1029     } else if (Regs.size() == 1) {
1030       BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1031           .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1032           .addReg(ARM::SP)
1033           .setMIFlags(MIFlags)
1034           .addImm(-4)
1035           .add(predOps(ARMCC::AL));
1036     }
1037     Regs.clear();
1038 
1039     // Put any subsequent vpush instructions before this one: they will refer to
1040     // higher register numbers so need to be pushed first in order to preserve
1041     // monotonicity.
1042     if (MI != MBB.begin())
1043       --MI;
1044   }
1045 }
1046 
1047 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1048                                    MachineBasicBlock::iterator MI,
1049                                    MutableArrayRef<CalleeSavedInfo> CSI,
1050                                    unsigned LdmOpc, unsigned LdrOpc,
1051                                    bool isVarArg, bool NoGap,
1052                                    bool (*Func)(unsigned, bool),
1053                                    unsigned NumAlignedDPRCS2Regs) const {
1054   MachineFunction &MF = *MBB.getParent();
1055   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1056   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1057   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1058   DebugLoc DL;
1059   bool isTailCall = false;
1060   bool isInterrupt = false;
1061   bool isTrap = false;
1062   if (MBB.end() != MI) {
1063     DL = MI->getDebugLoc();
1064     unsigned RetOpcode = MI->getOpcode();
1065     isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1066     isInterrupt =
1067         RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1068     isTrap =
1069         RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1070         RetOpcode == ARM::tTRAP;
1071   }
1072 
1073   SmallVector<unsigned, 4> Regs;
1074   unsigned i = CSI.size();
1075   while (i != 0) {
1076     unsigned LastReg = 0;
1077     bool DeleteRet = false;
1078     for (; i != 0; --i) {
1079       CalleeSavedInfo &Info = CSI[i-1];
1080       unsigned Reg = Info.getReg();
1081       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
1082 
1083       // The aligned reloads from area DPRCS2 are not inserted here.
1084       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1085         continue;
1086 
1087       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1088           !isTrap && STI.hasV5TOps()) {
1089         if (MBB.succ_empty()) {
1090           Reg = ARM::PC;
1091           // Fold the return instruction into the LDM.
1092           DeleteRet = true;
1093           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1094           // We 'restore' LR into PC so it is not live out of the return block:
1095           // Clear Restored bit.
1096           Info.setRestored(false);
1097         } else
1098           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1099       }
1100 
1101       // If NoGap is true, pop consecutive registers and then leave the rest
1102       // for other instructions. e.g.
1103       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1104       if (NoGap && LastReg && LastReg != Reg-1)
1105         break;
1106 
1107       LastReg = Reg;
1108       Regs.push_back(Reg);
1109     }
1110 
1111     if (Regs.empty())
1112       continue;
1113 
1114     llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
1115       return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1116     });
1117 
1118     if (Regs.size() > 1 || LdrOpc == 0) {
1119       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1120                                     .addReg(ARM::SP)
1121                                     .add(predOps(ARMCC::AL));
1122       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1123         MIB.addReg(Regs[i], getDefRegState(true));
1124       if (DeleteRet) {
1125         if (MI != MBB.end()) {
1126           MIB.copyImplicitOps(*MI);
1127           MI->eraseFromParent();
1128         }
1129       }
1130       MI = MIB;
1131     } else if (Regs.size() == 1) {
1132       // If we adjusted the reg to PC from LR above, switch it back here. We
1133       // only do that for LDM.
1134       if (Regs[0] == ARM::PC)
1135         Regs[0] = ARM::LR;
1136       MachineInstrBuilder MIB =
1137         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1138           .addReg(ARM::SP, RegState::Define)
1139           .addReg(ARM::SP);
1140       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1141       // that refactoring is complete (eventually).
1142       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1143         MIB.addReg(0);
1144         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1145       } else
1146         MIB.addImm(4);
1147       MIB.add(predOps(ARMCC::AL));
1148     }
1149     Regs.clear();
1150 
1151     // Put any subsequent vpop instructions after this one: they will refer to
1152     // higher register numbers so need to be popped afterwards.
1153     if (MI != MBB.end())
1154       ++MI;
1155   }
1156 }
1157 
1158 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1159 /// starting from d8.  Also insert stack realignment code and leave the stack
1160 /// pointer pointing to the d8 spill slot.
1161 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1162                                     MachineBasicBlock::iterator MI,
1163                                     unsigned NumAlignedDPRCS2Regs,
1164                                     ArrayRef<CalleeSavedInfo> CSI,
1165                                     const TargetRegisterInfo *TRI) {
1166   MachineFunction &MF = *MBB.getParent();
1167   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1168   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1169   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1170   MachineFrameInfo &MFI = MF.getFrameInfo();
1171 
1172   // Mark the D-register spill slots as properly aligned.  Since MFI computes
1173   // stack slot layout backwards, this can actually mean that the d-reg stack
1174   // slot offsets can be wrong. The offset for d8 will always be correct.
1175   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1176     unsigned DNum = CSI[i].getReg() - ARM::D8;
1177     if (DNum > NumAlignedDPRCS2Regs - 1)
1178       continue;
1179     int FI = CSI[i].getFrameIdx();
1180     // The even-numbered registers will be 16-byte aligned, the odd-numbered
1181     // registers will be 8-byte aligned.
1182     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1183 
1184     // The stack slot for D8 needs to be maximally aligned because this is
1185     // actually the point where we align the stack pointer.  MachineFrameInfo
1186     // computes all offsets relative to the incoming stack pointer which is a
1187     // bit weird when realigning the stack.  Any extra padding for this
1188     // over-alignment is not realized because the code inserted below adjusts
1189     // the stack pointer by numregs * 8 before aligning the stack pointer.
1190     if (DNum == 0)
1191       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1192   }
1193 
1194   // Move the stack pointer to the d8 spill slot, and align it at the same
1195   // time. Leave the stack slot address in the scratch register r4.
1196   //
1197   //   sub r4, sp, #numregs * 8
1198   //   bic r4, r4, #align - 1
1199   //   mov sp, r4
1200   //
1201   bool isThumb = AFI->isThumbFunction();
1202   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1203   AFI->setShouldRestoreSPFromFP(true);
1204 
1205   // sub r4, sp, #numregs * 8
1206   // The immediate is <= 64, so it doesn't need any special encoding.
1207   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1208   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1209       .addReg(ARM::SP)
1210       .addImm(8 * NumAlignedDPRCS2Regs)
1211       .add(predOps(ARMCC::AL))
1212       .add(condCodeOp());
1213 
1214   unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
1215   // We must set parameter MustBeSingleInstruction to true, since
1216   // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1217   // stack alignment.  Luckily, this can always be done since all ARM
1218   // architecture versions that support Neon also support the BFC
1219   // instruction.
1220   emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1221 
1222   // mov sp, r4
1223   // The stack pointer must be adjusted before spilling anything, otherwise
1224   // the stack slots could be clobbered by an interrupt handler.
1225   // Leave r4 live, it is used below.
1226   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1227   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1228                                 .addReg(ARM::R4)
1229                                 .add(predOps(ARMCC::AL));
1230   if (!isThumb)
1231     MIB.add(condCodeOp());
1232 
1233   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1234   // r4 holds the stack slot address.
1235   unsigned NextReg = ARM::D8;
1236 
1237   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1238   // The writeback is only needed when emitting two vst1.64 instructions.
1239   if (NumAlignedDPRCS2Regs >= 6) {
1240     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1241                                                &ARM::QQPRRegClass);
1242     MBB.addLiveIn(SupReg);
1243     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1244         .addReg(ARM::R4, RegState::Kill)
1245         .addImm(16)
1246         .addReg(NextReg)
1247         .addReg(SupReg, RegState::ImplicitKill)
1248         .add(predOps(ARMCC::AL));
1249     NextReg += 4;
1250     NumAlignedDPRCS2Regs -= 4;
1251   }
1252 
1253   // We won't modify r4 beyond this point.  It currently points to the next
1254   // register to be spilled.
1255   unsigned R4BaseReg = NextReg;
1256 
1257   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1258   if (NumAlignedDPRCS2Regs >= 4) {
1259     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1260                                                &ARM::QQPRRegClass);
1261     MBB.addLiveIn(SupReg);
1262     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1263         .addReg(ARM::R4)
1264         .addImm(16)
1265         .addReg(NextReg)
1266         .addReg(SupReg, RegState::ImplicitKill)
1267         .add(predOps(ARMCC::AL));
1268     NextReg += 4;
1269     NumAlignedDPRCS2Regs -= 4;
1270   }
1271 
1272   // 16-byte aligned vst1.64 with 2 d-regs.
1273   if (NumAlignedDPRCS2Regs >= 2) {
1274     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1275                                                &ARM::QPRRegClass);
1276     MBB.addLiveIn(SupReg);
1277     BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1278         .addReg(ARM::R4)
1279         .addImm(16)
1280         .addReg(SupReg)
1281         .add(predOps(ARMCC::AL));
1282     NextReg += 2;
1283     NumAlignedDPRCS2Regs -= 2;
1284   }
1285 
1286   // Finally, use a vanilla vstr.64 for the odd last register.
1287   if (NumAlignedDPRCS2Regs) {
1288     MBB.addLiveIn(NextReg);
1289     // vstr.64 uses addrmode5 which has an offset scale of 4.
1290     BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1291         .addReg(NextReg)
1292         .addReg(ARM::R4)
1293         .addImm((NextReg - R4BaseReg) * 2)
1294         .add(predOps(ARMCC::AL));
1295   }
1296 
1297   // The last spill instruction inserted should kill the scratch register r4.
1298   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1299 }
1300 
1301 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1302 /// iterator to the following instruction.
1303 static MachineBasicBlock::iterator
1304 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1305                         unsigned NumAlignedDPRCS2Regs) {
1306   //   sub r4, sp, #numregs * 8
1307   //   bic r4, r4, #align - 1
1308   //   mov sp, r4
1309   ++MI; ++MI; ++MI;
1310   assert(MI->mayStore() && "Expecting spill instruction");
1311 
1312   // These switches all fall through.
1313   switch(NumAlignedDPRCS2Regs) {
1314   case 7:
1315     ++MI;
1316     assert(MI->mayStore() && "Expecting spill instruction");
1317     LLVM_FALLTHROUGH;
1318   default:
1319     ++MI;
1320     assert(MI->mayStore() && "Expecting spill instruction");
1321     LLVM_FALLTHROUGH;
1322   case 1:
1323   case 2:
1324   case 4:
1325     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1326     ++MI;
1327   }
1328   return MI;
1329 }
1330 
1331 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1332 /// starting from d8.  These instructions are assumed to execute while the
1333 /// stack is still aligned, unlike the code inserted by emitPopInst.
1334 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1335                                       MachineBasicBlock::iterator MI,
1336                                       unsigned NumAlignedDPRCS2Regs,
1337                                       ArrayRef<CalleeSavedInfo> CSI,
1338                                       const TargetRegisterInfo *TRI) {
1339   MachineFunction &MF = *MBB.getParent();
1340   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1341   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1342   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1343 
1344   // Find the frame index assigned to d8.
1345   int D8SpillFI = 0;
1346   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1347     if (CSI[i].getReg() == ARM::D8) {
1348       D8SpillFI = CSI[i].getFrameIdx();
1349       break;
1350     }
1351 
1352   // Materialize the address of the d8 spill slot into the scratch register r4.
1353   // This can be fairly complicated if the stack frame is large, so just use
1354   // the normal frame index elimination mechanism to do it.  This code runs as
1355   // the initial part of the epilog where the stack and base pointers haven't
1356   // been changed yet.
1357   bool isThumb = AFI->isThumbFunction();
1358   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1359 
1360   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1361   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1362       .addFrameIndex(D8SpillFI)
1363       .addImm(0)
1364       .add(predOps(ARMCC::AL))
1365       .add(condCodeOp());
1366 
1367   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1368   unsigned NextReg = ARM::D8;
1369 
1370   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1371   if (NumAlignedDPRCS2Regs >= 6) {
1372     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1373                                                &ARM::QQPRRegClass);
1374     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1375         .addReg(ARM::R4, RegState::Define)
1376         .addReg(ARM::R4, RegState::Kill)
1377         .addImm(16)
1378         .addReg(SupReg, RegState::ImplicitDefine)
1379         .add(predOps(ARMCC::AL));
1380     NextReg += 4;
1381     NumAlignedDPRCS2Regs -= 4;
1382   }
1383 
1384   // We won't modify r4 beyond this point.  It currently points to the next
1385   // register to be spilled.
1386   unsigned R4BaseReg = NextReg;
1387 
1388   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1389   if (NumAlignedDPRCS2Regs >= 4) {
1390     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1391                                                &ARM::QQPRRegClass);
1392     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1393         .addReg(ARM::R4)
1394         .addImm(16)
1395         .addReg(SupReg, RegState::ImplicitDefine)
1396         .add(predOps(ARMCC::AL));
1397     NextReg += 4;
1398     NumAlignedDPRCS2Regs -= 4;
1399   }
1400 
1401   // 16-byte aligned vld1.64 with 2 d-regs.
1402   if (NumAlignedDPRCS2Regs >= 2) {
1403     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1404                                                &ARM::QPRRegClass);
1405     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1406         .addReg(ARM::R4)
1407         .addImm(16)
1408         .add(predOps(ARMCC::AL));
1409     NextReg += 2;
1410     NumAlignedDPRCS2Regs -= 2;
1411   }
1412 
1413   // Finally, use a vanilla vldr.64 for the remaining odd register.
1414   if (NumAlignedDPRCS2Regs)
1415     BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1416         .addReg(ARM::R4)
1417         .addImm(2 * (NextReg - R4BaseReg))
1418         .add(predOps(ARMCC::AL));
1419 
1420   // Last store kills r4.
1421   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1422 }
1423 
1424 bool ARMFrameLowering::spillCalleeSavedRegisters(
1425     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1426     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1427   if (CSI.empty())
1428     return false;
1429 
1430   MachineFunction &MF = *MBB.getParent();
1431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1432 
1433   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1434   unsigned PushOneOpc = AFI->isThumbFunction() ?
1435     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1436   unsigned FltOpc = ARM::VSTMDDB_UPD;
1437   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1438   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1439                MachineInstr::FrameSetup);
1440   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1441                MachineInstr::FrameSetup);
1442   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1443                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1444 
1445   // The code above does not insert spill code for the aligned DPRCS2 registers.
1446   // The stack realignment code will be inserted between the push instructions
1447   // and these spills.
1448   if (NumAlignedDPRCS2Regs)
1449     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1450 
1451   return true;
1452 }
1453 
1454 bool ARMFrameLowering::restoreCalleeSavedRegisters(
1455     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1456     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1457   if (CSI.empty())
1458     return false;
1459 
1460   MachineFunction &MF = *MBB.getParent();
1461   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1462   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1463   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1464 
1465   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1466   // registers. Do that here instead.
1467   if (NumAlignedDPRCS2Regs)
1468     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1469 
1470   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1471   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1472   unsigned FltOpc = ARM::VLDMDIA_UPD;
1473   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1474               NumAlignedDPRCS2Regs);
1475   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1476               &isARMArea2Register, 0);
1477   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1478               &isARMArea1Register, 0);
1479 
1480   return true;
1481 }
1482 
1483 // FIXME: Make generic?
1484 static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
1485                                             const ARMBaseInstrInfo &TII) {
1486   unsigned FnSize = 0;
1487   for (auto &MBB : MF) {
1488     for (auto &MI : MBB)
1489       FnSize += TII.getInstSizeInBytes(MI);
1490   }
1491   if (MF.getJumpTableInfo())
1492     for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
1493       FnSize += Table.MBBs.size() * 4;
1494   FnSize += MF.getConstantPool()->getConstants().size() * 4;
1495   return FnSize;
1496 }
1497 
1498 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1499 /// frames and return the stack size limit beyond which some of these
1500 /// instructions will require a scratch register during their expansion later.
1501 // FIXME: Move to TII?
1502 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1503                                          const TargetFrameLowering *TFI,
1504                                          bool &HasNonSPFrameIndex) {
1505   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1506   const ARMBaseInstrInfo &TII =
1507       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1508   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1509   unsigned Limit = (1 << 12) - 1;
1510   for (auto &MBB : MF) {
1511     for (auto &MI : MBB) {
1512       if (MI.isDebugInstr())
1513         continue;
1514       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1515         if (!MI.getOperand(i).isFI())
1516           continue;
1517 
1518         // When using ADDri to get the address of a stack object, 255 is the
1519         // largest offset guaranteed to fit in the immediate offset.
1520         if (MI.getOpcode() == ARM::ADDri) {
1521           Limit = std::min(Limit, (1U << 8) - 1);
1522           break;
1523         }
1524         // t2ADDri will not require an extra register, it can reuse the
1525         // destination.
1526         if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
1527           break;
1528 
1529         const MCInstrDesc &MCID = MI.getDesc();
1530         const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
1531         if (RegClass && !RegClass->contains(ARM::SP))
1532           HasNonSPFrameIndex = true;
1533 
1534         // Otherwise check the addressing mode.
1535         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1536         case ARMII::AddrMode_i12:
1537         case ARMII::AddrMode2:
1538           // Default 12 bit limit.
1539           break;
1540         case ARMII::AddrMode3:
1541         case ARMII::AddrModeT2_i8:
1542           Limit = std::min(Limit, (1U << 8) - 1);
1543           break;
1544         case ARMII::AddrMode5FP16:
1545           Limit = std::min(Limit, ((1U << 8) - 1) * 2);
1546           break;
1547         case ARMII::AddrMode5:
1548         case ARMII::AddrModeT2_i8s4:
1549         case ARMII::AddrModeT2_ldrex:
1550           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1551           break;
1552         case ARMII::AddrModeT2_i12:
1553           // i12 supports only positive offset so these will be converted to
1554           // i8 opcodes. See llvm::rewriteT2FrameIndex.
1555           if (TFI->hasFP(MF) && AFI->hasStackFrame())
1556             Limit = std::min(Limit, (1U << 8) - 1);
1557           break;
1558         case ARMII::AddrMode4:
1559         case ARMII::AddrMode6:
1560           // Addressing modes 4 & 6 (load/store) instructions can't encode an
1561           // immediate offset for stack references.
1562           return 0;
1563         case ARMII::AddrModeT2_i7:
1564           Limit = std::min(Limit, ((1U << 7) - 1) * 1);
1565           break;
1566         case ARMII::AddrModeT2_i7s2:
1567           Limit = std::min(Limit, ((1U << 7) - 1) * 2);
1568           break;
1569         case ARMII::AddrModeT2_i7s4:
1570           Limit = std::min(Limit, ((1U << 7) - 1) * 4);
1571           break;
1572         default:
1573           llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
1574         }
1575         break; // At most one FI per instruction
1576       }
1577     }
1578   }
1579 
1580   return Limit;
1581 }
1582 
1583 // In functions that realign the stack, it can be an advantage to spill the
1584 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1585 // instructions take alignment hints that can improve performance.
1586 static void
1587 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1588   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1589   if (!SpillAlignedNEONRegs)
1590     return;
1591 
1592   // Naked functions don't spill callee-saved registers.
1593   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
1594     return;
1595 
1596   // We are planning to use NEON instructions vst1 / vld1.
1597   if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1598     return;
1599 
1600   // Don't bother if the default stack alignment is sufficiently high.
1601   if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1602     return;
1603 
1604   // Aligned spills require stack realignment.
1605   if (!static_cast<const ARMBaseRegisterInfo *>(
1606            MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1607     return;
1608 
1609   // We always spill contiguous d-registers starting from d8. Count how many
1610   // needs spilling.  The register allocator will almost always use the
1611   // callee-saved registers in order, but it can happen that there are holes in
1612   // the range.  Registers above the hole will be spilled to the standard DPRCS
1613   // area.
1614   unsigned NumSpills = 0;
1615   for (; NumSpills < 8; ++NumSpills)
1616     if (!SavedRegs.test(ARM::D8 + NumSpills))
1617       break;
1618 
1619   // Don't do this for just one d-register. It's not worth it.
1620   if (NumSpills < 2)
1621     return;
1622 
1623   // Spill the first NumSpills D-registers after realigning the stack.
1624   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1625 
1626   // A scratch register is required for the vst1 / vld1 instructions.
1627   SavedRegs.set(ARM::R4);
1628 }
1629 
1630 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1631                                             BitVector &SavedRegs,
1632                                             RegScavenger *RS) const {
1633   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1634   // This tells PEI to spill the FP as if it is any other callee-save register
1635   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1636   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1637   // to combine multiple loads / stores.
1638   bool CanEliminateFrame = true;
1639   bool CS1Spilled = false;
1640   bool LRSpilled = false;
1641   unsigned NumGPRSpills = 0;
1642   unsigned NumFPRSpills = 0;
1643   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1644   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1645   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1646       MF.getSubtarget().getRegisterInfo());
1647   const ARMBaseInstrInfo &TII =
1648       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1649   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1650   MachineFrameInfo &MFI = MF.getFrameInfo();
1651   MachineRegisterInfo &MRI = MF.getRegInfo();
1652   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1653   (void)TRI;  // Silence unused warning in non-assert builds.
1654   Register FramePtr = RegInfo->getFrameRegister(MF);
1655 
1656   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1657   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1658   // since it's not always possible to restore sp from fp in a single
1659   // instruction.
1660   // FIXME: It will be better just to find spare register here.
1661   if (AFI->isThumb2Function() &&
1662       (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1663     SavedRegs.set(ARM::R4);
1664 
1665   // If a stack probe will be emitted, spill R4 and LR, since they are
1666   // clobbered by the stack probe call.
1667   // This estimate should be a safe, conservative estimate. The actual
1668   // stack probe is enabled based on the size of the local objects;
1669   // this estimate also includes the varargs store size.
1670   if (STI.isTargetWindows() &&
1671       WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
1672     SavedRegs.set(ARM::R4);
1673     SavedRegs.set(ARM::LR);
1674   }
1675 
1676   if (AFI->isThumb1OnlyFunction()) {
1677     // Spill LR if Thumb1 function uses variable length argument lists.
1678     if (AFI->getArgRegsSaveSize() > 0)
1679       SavedRegs.set(ARM::LR);
1680 
1681     // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1682     // requires stack alignment.  We don't know for sure what the stack size
1683     // will be, but for this, an estimate is good enough. If there anything
1684     // changes it, it'll be a spill, which implies we've used all the registers
1685     // and so R4 is already used, so not marking it here will be OK.
1686     // FIXME: It will be better just to find spare register here.
1687     if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
1688         MFI.estimateStackSize(MF) > 508)
1689       SavedRegs.set(ARM::R4);
1690   }
1691 
1692   // See if we can spill vector registers to aligned stack.
1693   checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1694 
1695   // Spill the BasePtr if it's used.
1696   if (RegInfo->hasBasePointer(MF))
1697     SavedRegs.set(RegInfo->getBaseRegister());
1698 
1699   // Don't spill FP if the frame can be eliminated. This is determined
1700   // by scanning the callee-save registers to see if any is modified.
1701   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1702   for (unsigned i = 0; CSRegs[i]; ++i) {
1703     unsigned Reg = CSRegs[i];
1704     bool Spilled = false;
1705     if (SavedRegs.test(Reg)) {
1706       Spilled = true;
1707       CanEliminateFrame = false;
1708     }
1709 
1710     if (!ARM::GPRRegClass.contains(Reg)) {
1711       if (Spilled) {
1712         if (ARM::SPRRegClass.contains(Reg))
1713           NumFPRSpills++;
1714         else if (ARM::DPRRegClass.contains(Reg))
1715           NumFPRSpills += 2;
1716         else if (ARM::QPRRegClass.contains(Reg))
1717           NumFPRSpills += 4;
1718       }
1719       continue;
1720     }
1721 
1722     if (Spilled) {
1723       NumGPRSpills++;
1724 
1725       if (!STI.splitFramePushPop(MF)) {
1726         if (Reg == ARM::LR)
1727           LRSpilled = true;
1728         CS1Spilled = true;
1729         continue;
1730       }
1731 
1732       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1733       switch (Reg) {
1734       case ARM::LR:
1735         LRSpilled = true;
1736         LLVM_FALLTHROUGH;
1737       case ARM::R0: case ARM::R1:
1738       case ARM::R2: case ARM::R3:
1739       case ARM::R4: case ARM::R5:
1740       case ARM::R6: case ARM::R7:
1741         CS1Spilled = true;
1742         break;
1743       default:
1744         break;
1745       }
1746     } else {
1747       if (!STI.splitFramePushPop(MF)) {
1748         UnspilledCS1GPRs.push_back(Reg);
1749         continue;
1750       }
1751 
1752       switch (Reg) {
1753       case ARM::R0: case ARM::R1:
1754       case ARM::R2: case ARM::R3:
1755       case ARM::R4: case ARM::R5:
1756       case ARM::R6: case ARM::R7:
1757       case ARM::LR:
1758         UnspilledCS1GPRs.push_back(Reg);
1759         break;
1760       default:
1761         UnspilledCS2GPRs.push_back(Reg);
1762         break;
1763       }
1764     }
1765   }
1766 
1767   bool ForceLRSpill = false;
1768   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1769     unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
1770     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1771     // use of BL to implement far jump.
1772     if (FnSize >= (1 << 11)) {
1773       CanEliminateFrame = false;
1774       ForceLRSpill = true;
1775     }
1776   }
1777 
1778   // If any of the stack slot references may be out of range of an immediate
1779   // offset, make sure a register (or a spill slot) is available for the
1780   // register scavenger. Note that if we're indexing off the frame pointer, the
1781   // effective stack size is 4 bytes larger since the FP points to the stack
1782   // slot of the previous FP. Also, if we have variable sized objects in the
1783   // function, stack slot references will often be negative, and some of
1784   // our instructions are positive-offset only, so conservatively consider
1785   // that case to want a spill slot (or register) as well. Similarly, if
1786   // the function adjusts the stack pointer during execution and the
1787   // adjustments aren't already part of our stack size estimate, our offset
1788   // calculations may be off, so be conservative.
1789   // FIXME: We could add logic to be more precise about negative offsets
1790   //        and which instructions will need a scratch register for them. Is it
1791   //        worth the effort and added fragility?
1792   unsigned EstimatedStackSize =
1793       MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
1794 
1795   // Determine biggest (positive) SP offset in MachineFrameInfo.
1796   int MaxFixedOffset = 0;
1797   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1798     int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1799     MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1800   }
1801 
1802   bool HasFP = hasFP(MF);
1803   if (HasFP) {
1804     if (AFI->hasStackFrame())
1805       EstimatedStackSize += 4;
1806   } else {
1807     // If FP is not used, SP will be used to access arguments, so count the
1808     // size of arguments into the estimation.
1809     EstimatedStackSize += MaxFixedOffset;
1810   }
1811   EstimatedStackSize += 16; // For possible paddings.
1812 
1813   unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
1814   bool HasNonSPFrameIndex = false;
1815   if (AFI->isThumb1OnlyFunction()) {
1816     // For Thumb1, don't bother to iterate over the function. The only
1817     // instruction that requires an emergency spill slot is a store to a
1818     // frame index.
1819     //
1820     // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
1821     // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
1822     // a 5-bit unsigned immediate.
1823     //
1824     // We could try to check if the function actually contains a tSTRspi
1825     // that might need the spill slot, but it's not really important.
1826     // Functions with VLAs or extremely large call frames are rare, and
1827     // if a function is allocating more than 1KB of stack, an extra 4-byte
1828     // slot probably isn't relevant.
1829     if (RegInfo->hasBasePointer(MF))
1830       EstimatedRSStackSizeLimit = (1U << 5) * 4;
1831     else
1832       EstimatedRSStackSizeLimit = (1U << 8) * 4;
1833     EstimatedRSFixedSizeLimit = (1U << 5) * 4;
1834   } else {
1835     EstimatedRSStackSizeLimit =
1836         estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
1837     EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
1838   }
1839   // Final estimate of whether sp or bp-relative accesses might require
1840   // scavenging.
1841   bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
1842 
1843   // If the stack pointer moves and we don't have a base pointer, the
1844   // estimate logic doesn't work. The actual offsets might be larger when
1845   // we're constructing a call frame, or we might need to use negative
1846   // offsets from fp.
1847   bool HasMovingSP = MFI.hasVarSizedObjects() ||
1848     (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
1849   bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
1850 
1851   // If we have a frame pointer, we assume arguments will be accessed
1852   // relative to the frame pointer. Check whether fp-relative accesses to
1853   // arguments require scavenging.
1854   //
1855   // We could do slightly better on Thumb1; in some cases, an sp-relative
1856   // offset would be legal even though an fp-relative offset is not.
1857   int MaxFPOffset = getMaxFPOffset(MF.getFunction(), *AFI);
1858   bool HasLargeArgumentList =
1859       HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
1860 
1861   bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
1862                          HasLargeArgumentList || HasNonSPFrameIndex;
1863   LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
1864                     << "; EstimatedStack: " << EstimatedStackSize
1865                     << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
1866                     << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
1867   if (BigFrameOffsets ||
1868       !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1869     AFI->setHasStackFrame(true);
1870 
1871     if (HasFP) {
1872       SavedRegs.set(FramePtr);
1873       // If the frame pointer is required by the ABI, also spill LR so that we
1874       // emit a complete frame record.
1875       if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1876         SavedRegs.set(ARM::LR);
1877         LRSpilled = true;
1878         NumGPRSpills++;
1879         auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
1880         if (LRPos != UnspilledCS1GPRs.end())
1881           UnspilledCS1GPRs.erase(LRPos);
1882       }
1883       auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
1884       if (FPPos != UnspilledCS1GPRs.end())
1885         UnspilledCS1GPRs.erase(FPPos);
1886       NumGPRSpills++;
1887       if (FramePtr == ARM::R7)
1888         CS1Spilled = true;
1889     }
1890 
1891     // This is true when we inserted a spill for a callee-save GPR which is
1892     // not otherwise used by the function. This guaranteees it is possible
1893     // to scavenge a register to hold the address of a stack slot. On Thumb1,
1894     // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
1895     // subtargets, this is any GPR, i.e. r4-r11 or lr.
1896     //
1897     // If we don't insert a spill, we instead allocate an emergency spill
1898     // slot, which can be used by scavenging to spill an arbitrary register.
1899     //
1900     // We currently don't try to figure out whether any specific instruction
1901     // requires scavening an additional register.
1902     bool ExtraCSSpill = false;
1903 
1904     if (AFI->isThumb1OnlyFunction()) {
1905       // For Thumb1-only targets, we need some low registers when we save and
1906       // restore the high registers (which aren't allocatable, but could be
1907       // used by inline assembly) because the push/pop instructions can not
1908       // access high registers. If necessary, we might need to push more low
1909       // registers to ensure that there is at least one free that can be used
1910       // for the saving & restoring, and preferably we should ensure that as
1911       // many as are needed are available so that fewer push/pop instructions
1912       // are required.
1913 
1914       // Low registers which are not currently pushed, but could be (r4-r7).
1915       SmallVector<unsigned, 4> AvailableRegs;
1916 
1917       // Unused argument registers (r0-r3) can be clobbered in the prologue for
1918       // free.
1919       int EntryRegDeficit = 0;
1920       for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1921         if (!MF.getRegInfo().isLiveIn(Reg)) {
1922           --EntryRegDeficit;
1923           LLVM_DEBUG(dbgs()
1924                      << printReg(Reg, TRI)
1925                      << " is unused argument register, EntryRegDeficit = "
1926                      << EntryRegDeficit << "\n");
1927         }
1928       }
1929 
1930       // Unused return registers can be clobbered in the epilogue for free.
1931       int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1932       LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
1933                         << " return regs used, ExitRegDeficit = "
1934                         << ExitRegDeficit << "\n");
1935 
1936       int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1937       LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1938 
1939       // r4-r6 can be used in the prologue if they are pushed by the first push
1940       // instruction.
1941       for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1942         if (SavedRegs.test(Reg)) {
1943           --RegDeficit;
1944           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1945                             << " is saved low register, RegDeficit = "
1946                             << RegDeficit << "\n");
1947         } else {
1948           AvailableRegs.push_back(Reg);
1949           LLVM_DEBUG(
1950               dbgs()
1951               << printReg(Reg, TRI)
1952               << " is non-saved low register, adding to AvailableRegs\n");
1953         }
1954       }
1955 
1956       // r7 can be used if it is not being used as the frame pointer.
1957       if (!HasFP) {
1958         if (SavedRegs.test(ARM::R7)) {
1959           --RegDeficit;
1960           LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
1961                             << RegDeficit << "\n");
1962         } else {
1963           AvailableRegs.push_back(ARM::R7);
1964           LLVM_DEBUG(
1965               dbgs()
1966               << "%r7 is non-saved low register, adding to AvailableRegs\n");
1967         }
1968       }
1969 
1970       // Each of r8-r11 needs to be copied to a low register, then pushed.
1971       for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1972         if (SavedRegs.test(Reg)) {
1973           ++RegDeficit;
1974           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1975                             << " is saved high register, RegDeficit = "
1976                             << RegDeficit << "\n");
1977         }
1978       }
1979 
1980       // LR can only be used by PUSH, not POP, and can't be used at all if the
1981       // llvm.returnaddress intrinsic is used. This is only worth doing if we
1982       // are more limited at function entry than exit.
1983       if ((EntryRegDeficit > ExitRegDeficit) &&
1984           !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1985             MF.getFrameInfo().isReturnAddressTaken())) {
1986         if (SavedRegs.test(ARM::LR)) {
1987           --RegDeficit;
1988           LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
1989                             << RegDeficit << "\n");
1990         } else {
1991           AvailableRegs.push_back(ARM::LR);
1992           LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
1993         }
1994       }
1995 
1996       // If there are more high registers that need pushing than low registers
1997       // available, push some more low registers so that we can use fewer push
1998       // instructions. This might not reduce RegDeficit all the way to zero,
1999       // because we can only guarantee that r4-r6 are available, but r8-r11 may
2000       // need saving.
2001       LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
2002       for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
2003         unsigned Reg = AvailableRegs.pop_back_val();
2004         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2005                           << " to make up reg deficit\n");
2006         SavedRegs.set(Reg);
2007         NumGPRSpills++;
2008         CS1Spilled = true;
2009         assert(!MRI.isReserved(Reg) && "Should not be reserved");
2010         if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
2011           ExtraCSSpill = true;
2012         UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
2013         if (Reg == ARM::LR)
2014           LRSpilled = true;
2015       }
2016       LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
2017                         << "\n");
2018     }
2019 
2020     // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
2021     // restore LR in that case.
2022     bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
2023 
2024     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
2025     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
2026     if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
2027       SavedRegs.set(ARM::LR);
2028       NumGPRSpills++;
2029       SmallVectorImpl<unsigned>::iterator LRPos;
2030       LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
2031       if (LRPos != UnspilledCS1GPRs.end())
2032         UnspilledCS1GPRs.erase(LRPos);
2033 
2034       ForceLRSpill = false;
2035       if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
2036           !AFI->isThumb1OnlyFunction())
2037         ExtraCSSpill = true;
2038     }
2039 
2040     // If stack and double are 8-byte aligned and we are spilling an odd number
2041     // of GPRs, spill one extra callee save GPR so we won't have to pad between
2042     // the integer and double callee save areas.
2043     LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
2044     unsigned TargetAlign = getStackAlignment();
2045     if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
2046       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
2047         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
2048           unsigned Reg = UnspilledCS1GPRs[i];
2049           // Don't spill high register if the function is thumb.  In the case of
2050           // Windows on ARM, accept R11 (frame pointer)
2051           if (!AFI->isThumbFunction() ||
2052               (STI.isTargetWindows() && Reg == ARM::R11) ||
2053               isARMLowRegister(Reg) ||
2054               (Reg == ARM::LR && !ExpensiveLRRestore)) {
2055             SavedRegs.set(Reg);
2056             LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2057                               << " to make up alignment\n");
2058             if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
2059                 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
2060               ExtraCSSpill = true;
2061             break;
2062           }
2063         }
2064       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
2065         unsigned Reg = UnspilledCS2GPRs.front();
2066         SavedRegs.set(Reg);
2067         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2068                           << " to make up alignment\n");
2069         if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
2070           ExtraCSSpill = true;
2071       }
2072     }
2073 
2074     // Estimate if we might need to scavenge a register at some point in order
2075     // to materialize a stack offset. If so, either spill one additional
2076     // callee-saved register or reserve a special spill slot to facilitate
2077     // register scavenging. Thumb1 needs a spill slot for stack pointer
2078     // adjustments also, even when the frame itself is small.
2079     if (BigFrameOffsets && !ExtraCSSpill) {
2080       // If any non-reserved CS register isn't spilled, just spill one or two
2081       // extra. That should take care of it!
2082       unsigned NumExtras = TargetAlign / 4;
2083       SmallVector<unsigned, 2> Extras;
2084       while (NumExtras && !UnspilledCS1GPRs.empty()) {
2085         unsigned Reg = UnspilledCS1GPRs.back();
2086         UnspilledCS1GPRs.pop_back();
2087         if (!MRI.isReserved(Reg) &&
2088             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
2089           Extras.push_back(Reg);
2090           NumExtras--;
2091         }
2092       }
2093       // For non-Thumb1 functions, also check for hi-reg CS registers
2094       if (!AFI->isThumb1OnlyFunction()) {
2095         while (NumExtras && !UnspilledCS2GPRs.empty()) {
2096           unsigned Reg = UnspilledCS2GPRs.back();
2097           UnspilledCS2GPRs.pop_back();
2098           if (!MRI.isReserved(Reg)) {
2099             Extras.push_back(Reg);
2100             NumExtras--;
2101           }
2102         }
2103       }
2104       if (NumExtras == 0) {
2105         for (unsigned Reg : Extras) {
2106           SavedRegs.set(Reg);
2107           if (!MRI.isPhysRegUsed(Reg))
2108             ExtraCSSpill = true;
2109         }
2110       }
2111       if (!ExtraCSSpill && RS) {
2112         // Reserve a slot closest to SP or frame pointer.
2113         LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
2114         const TargetRegisterClass &RC = ARM::GPRRegClass;
2115         unsigned Size = TRI->getSpillSize(RC);
2116         unsigned Align = TRI->getSpillAlignment(RC);
2117         RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
2118       }
2119     }
2120   }
2121 
2122   if (ForceLRSpill)
2123     SavedRegs.set(ARM::LR);
2124   AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
2125 }
2126 
2127 void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
2128                                       BitVector &SavedRegs) const {
2129   TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
2130 
2131   // If we have the "returned" parameter attribute which guarantees that we
2132   // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
2133   // record that fact for IPRA.
2134   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2135   if (AFI->getPreservesR0())
2136     SavedRegs.set(ARM::R0);
2137 }
2138 
2139 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
2140     MachineFunction &MF, MachineBasicBlock &MBB,
2141     MachineBasicBlock::iterator I) const {
2142   const ARMBaseInstrInfo &TII =
2143       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2144   if (!hasReservedCallFrame(MF)) {
2145     // If we have alloca, convert as follows:
2146     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2147     // ADJCALLSTACKUP   -> add, sp, sp, amount
2148     MachineInstr &Old = *I;
2149     DebugLoc dl = Old.getDebugLoc();
2150     unsigned Amount = TII.getFrameSize(Old);
2151     if (Amount != 0) {
2152       // We need to keep the stack aligned properly.  To do this, we round the
2153       // amount of space needed for the outgoing arguments up to the next
2154       // alignment boundary.
2155       Amount = alignSPAdjust(Amount);
2156 
2157       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2158       assert(!AFI->isThumb1OnlyFunction() &&
2159              "This eliminateCallFramePseudoInstr does not support Thumb1!");
2160       bool isARM = !AFI->isThumbFunction();
2161 
2162       // Replace the pseudo instruction with a new instruction...
2163       unsigned Opc = Old.getOpcode();
2164       int PIdx = Old.findFirstPredOperandIdx();
2165       ARMCC::CondCodes Pred =
2166           (PIdx == -1) ? ARMCC::AL
2167                        : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
2168       unsigned PredReg = TII.getFramePred(Old);
2169       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
2170         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2171                      Pred, PredReg);
2172       } else {
2173         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2174         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2175                      Pred, PredReg);
2176       }
2177     }
2178   }
2179   return MBB.erase(I);
2180 }
2181 
2182 /// Get the minimum constant for ARM that is greater than or equal to the
2183 /// argument. In ARM, constants can have any value that can be produced by
2184 /// rotating an 8-bit value to the right by an even number of bits within a
2185 /// 32-bit word.
2186 static uint32_t alignToARMConstant(uint32_t Value) {
2187   unsigned Shifted = 0;
2188 
2189   if (Value == 0)
2190       return 0;
2191 
2192   while (!(Value & 0xC0000000)) {
2193       Value = Value << 2;
2194       Shifted += 2;
2195   }
2196 
2197   bool Carry = (Value & 0x00FFFFFF);
2198   Value = ((Value & 0xFF000000) >> 24) + Carry;
2199 
2200   if (Value & 0x0000100)
2201       Value = Value & 0x000001FC;
2202 
2203   if (Shifted > 24)
2204       Value = Value >> (Shifted - 24);
2205   else
2206       Value = Value << (24 - Shifted);
2207 
2208   return Value;
2209 }
2210 
2211 // The stack limit in the TCB is set to this many bytes above the actual
2212 // stack limit.
2213 static const uint64_t kSplitStackAvailable = 256;
2214 
2215 // Adjust the function prologue to enable split stacks. This currently only
2216 // supports android and linux.
2217 //
2218 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2219 // must be well defined in order to allow for consistent implementations of the
2220 // __morestack helper function. The ABI is also not a normal ABI in that it
2221 // doesn't follow the normal calling conventions because this allows the
2222 // prologue of each function to be optimized further.
2223 //
2224 // Currently, the ABI looks like (when calling __morestack)
2225 //
2226 //  * r4 holds the minimum stack size requested for this function call
2227 //  * r5 holds the stack size of the arguments to the function
2228 //  * the beginning of the function is 3 instructions after the call to
2229 //    __morestack
2230 //
2231 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
2232 // place the arguments on to the new stack, and the 3-instruction knowledge to
2233 // jump directly to the body of the function when working on the new stack.
2234 //
2235 // An old (and possibly no longer compatible) implementation of __morestack for
2236 // ARM can be found at [1].
2237 //
2238 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
2239 void ARMFrameLowering::adjustForSegmentedStacks(
2240     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2241   unsigned Opcode;
2242   unsigned CFIIndex;
2243   const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
2244   bool Thumb = ST->isThumb();
2245 
2246   // Sadly, this currently doesn't support varargs, platforms other than
2247   // android/linux. Note that thumb1/thumb2 are support for android/linux.
2248   if (MF.getFunction().isVarArg())
2249     report_fatal_error("Segmented stacks do not support vararg functions.");
2250   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
2251     report_fatal_error("Segmented stacks not supported on this platform.");
2252 
2253   MachineFrameInfo &MFI = MF.getFrameInfo();
2254   MachineModuleInfo &MMI = MF.getMMI();
2255   MCContext &Context = MMI.getContext();
2256   const MCRegisterInfo *MRI = Context.getRegisterInfo();
2257   const ARMBaseInstrInfo &TII =
2258       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2259   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2260   DebugLoc DL;
2261 
2262   uint64_t StackSize = MFI.getStackSize();
2263 
2264   // Do not generate a prologue for leaf functions with a stack of size zero.
2265   // For non-leaf functions we have to allow for the possibility that the
2266   // callis to a non-split function, as in PR37807. This function could also
2267   // take the address of a non-split function. When the linker tries to adjust
2268   // its non-existent prologue, it would fail with an error. Mark the object
2269   // file so that such failures are not errors. See this Go language bug-report
2270   // https://go-review.googlesource.com/c/go/+/148819/
2271   if (StackSize == 0 && !MFI.hasTailCall()) {
2272     MF.getMMI().setHasNosplitStack(true);
2273     return;
2274   }
2275 
2276   // Use R4 and R5 as scratch registers.
2277   // We save R4 and R5 before use and restore them before leaving the function.
2278   unsigned ScratchReg0 = ARM::R4;
2279   unsigned ScratchReg1 = ARM::R5;
2280   uint64_t AlignedStackSize;
2281 
2282   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2283   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2284   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2285   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2286   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2287 
2288   // Grab everything that reaches PrologueMBB to update there liveness as well.
2289   SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2290   SmallVector<MachineBasicBlock *, 2> WalkList;
2291   WalkList.push_back(&PrologueMBB);
2292 
2293   do {
2294     MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2295     for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2296       if (BeforePrologueRegion.insert(PredBB).second)
2297         WalkList.push_back(PredBB);
2298     }
2299   } while (!WalkList.empty());
2300 
2301   // The order in that list is important.
2302   // The blocks will all be inserted before PrologueMBB using that order.
2303   // Therefore the block that should appear first in the CFG should appear
2304   // first in the list.
2305   MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2306                                       PostStackMBB};
2307 
2308   for (MachineBasicBlock *B : AddedBlocks)
2309     BeforePrologueRegion.insert(B);
2310 
2311   for (const auto &LI : PrologueMBB.liveins()) {
2312     for (MachineBasicBlock *PredBB : BeforePrologueRegion)
2313       PredBB->addLiveIn(LI);
2314   }
2315 
2316   // Remove the newly added blocks from the list, since we know
2317   // we do not have to do the following updates for them.
2318   for (MachineBasicBlock *B : AddedBlocks) {
2319     BeforePrologueRegion.erase(B);
2320     MF.insert(PrologueMBB.getIterator(), B);
2321   }
2322 
2323   for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2324     // Make sure the LiveIns are still sorted and unique.
2325     MBB->sortUniqueLiveIns();
2326     // Replace the edges to PrologueMBB by edges to the sequences
2327     // we are about to add.
2328     MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2329   }
2330 
2331   // The required stack size that is aligned to ARM constant criterion.
2332   AlignedStackSize = alignToARMConstant(StackSize);
2333 
2334   // When the frame size is less than 256 we just compare the stack
2335   // boundary directly to the value of the stack pointer, per gcc.
2336   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2337 
2338   // We will use two of the callee save registers as scratch registers so we
2339   // need to save those registers onto the stack.
2340   // We will use SR0 to hold stack limit and SR1 to hold the stack size
2341   // requested and arguments for __morestack().
2342   // SR0: Scratch Register #0
2343   // SR1: Scratch Register #1
2344   // push {SR0, SR1}
2345   if (Thumb) {
2346     BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2347         .add(predOps(ARMCC::AL))
2348         .addReg(ScratchReg0)
2349         .addReg(ScratchReg1);
2350   } else {
2351     BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2352         .addReg(ARM::SP, RegState::Define)
2353         .addReg(ARM::SP)
2354         .add(predOps(ARMCC::AL))
2355         .addReg(ScratchReg0)
2356         .addReg(ScratchReg1);
2357   }
2358 
2359   // Emit the relevant DWARF information about the change in stack pointer as
2360   // well as where to find both r4 and r5 (the callee-save registers)
2361   CFIIndex =
2362       MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
2363   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2364       .addCFIIndex(CFIIndex);
2365   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2366       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2367   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2368       .addCFIIndex(CFIIndex);
2369   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2370       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2371   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2372       .addCFIIndex(CFIIndex);
2373 
2374   // mov SR1, sp
2375   if (Thumb) {
2376     BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2377         .addReg(ARM::SP)
2378         .add(predOps(ARMCC::AL));
2379   } else if (CompareStackPointer) {
2380     BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2381         .addReg(ARM::SP)
2382         .add(predOps(ARMCC::AL))
2383         .add(condCodeOp());
2384   }
2385 
2386   // sub SR1, sp, #StackSize
2387   if (!CompareStackPointer && Thumb) {
2388     BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2389         .add(condCodeOp())
2390         .addReg(ScratchReg1)
2391         .addImm(AlignedStackSize)
2392         .add(predOps(ARMCC::AL));
2393   } else if (!CompareStackPointer) {
2394     BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2395         .addReg(ARM::SP)
2396         .addImm(AlignedStackSize)
2397         .add(predOps(ARMCC::AL))
2398         .add(condCodeOp());
2399   }
2400 
2401   if (Thumb && ST->isThumb1Only()) {
2402     unsigned PCLabelId = ARMFI->createPICLabelUId();
2403     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
2404         MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
2405     MachineConstantPool *MCP = MF.getConstantPool();
2406     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
2407 
2408     // ldr SR0, [pc, offset(STACK_LIMIT)]
2409     BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2410         .addConstantPoolIndex(CPI)
2411         .add(predOps(ARMCC::AL));
2412 
2413     // ldr SR0, [SR0]
2414     BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2415         .addReg(ScratchReg0)
2416         .addImm(0)
2417         .add(predOps(ARMCC::AL));
2418   } else {
2419     // Get TLS base address from the coprocessor
2420     // mrc p15, #0, SR0, c13, c0, #3
2421     BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
2422             ScratchReg0)
2423         .addImm(15)
2424         .addImm(0)
2425         .addImm(13)
2426         .addImm(0)
2427         .addImm(3)
2428         .add(predOps(ARMCC::AL));
2429 
2430     // Use the last tls slot on android and a private field of the TCP on linux.
2431     assert(ST->isTargetAndroid() || ST->isTargetLinux());
2432     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2433 
2434     // Get the stack limit from the right offset
2435     // ldr SR0, [sr0, #4 * TlsOffset]
2436     BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
2437             ScratchReg0)
2438         .addReg(ScratchReg0)
2439         .addImm(4 * TlsOffset)
2440         .add(predOps(ARMCC::AL));
2441   }
2442 
2443   // Compare stack limit with stack size requested.
2444   // cmp SR0, SR1
2445   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2446   BuildMI(GetMBB, DL, TII.get(Opcode))
2447       .addReg(ScratchReg0)
2448       .addReg(ScratchReg1)
2449       .add(predOps(ARMCC::AL));
2450 
2451   // This jump is taken if StackLimit < SP - stack required.
2452   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2453   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2454        .addImm(ARMCC::LO)
2455        .addReg(ARM::CPSR);
2456 
2457 
2458   // Calling __morestack(StackSize, Size of stack arguments).
2459   // __morestack knows that the stack size requested is in SR0(r4)
2460   // and amount size of stack arguments is in SR1(r5).
2461 
2462   // Pass first argument for the __morestack by Scratch Register #0.
2463   //   The amount size of stack required
2464   if (Thumb) {
2465     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2466         .add(condCodeOp())
2467         .addImm(AlignedStackSize)
2468         .add(predOps(ARMCC::AL));
2469   } else {
2470     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2471         .addImm(AlignedStackSize)
2472         .add(predOps(ARMCC::AL))
2473         .add(condCodeOp());
2474   }
2475   // Pass second argument for the __morestack by Scratch Register #1.
2476   //   The amount size of stack consumed to save function arguments.
2477   if (Thumb) {
2478     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2479         .add(condCodeOp())
2480         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2481         .add(predOps(ARMCC::AL));
2482   } else {
2483     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2484         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2485         .add(predOps(ARMCC::AL))
2486         .add(condCodeOp());
2487   }
2488 
2489   // push {lr} - Save return address of this function.
2490   if (Thumb) {
2491     BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2492         .add(predOps(ARMCC::AL))
2493         .addReg(ARM::LR);
2494   } else {
2495     BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2496         .addReg(ARM::SP, RegState::Define)
2497         .addReg(ARM::SP)
2498         .add(predOps(ARMCC::AL))
2499         .addReg(ARM::LR);
2500   }
2501 
2502   // Emit the DWARF info about the change in stack as well as where to find the
2503   // previous link register
2504   CFIIndex =
2505       MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2506   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2507       .addCFIIndex(CFIIndex);
2508   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2509         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2510   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2511       .addCFIIndex(CFIIndex);
2512 
2513   // Call __morestack().
2514   if (Thumb) {
2515     BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2516         .add(predOps(ARMCC::AL))
2517         .addExternalSymbol("__morestack");
2518   } else {
2519     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2520         .addExternalSymbol("__morestack");
2521   }
2522 
2523   // pop {lr} - Restore return address of this original function.
2524   if (Thumb) {
2525     if (ST->isThumb1Only()) {
2526       BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2527           .add(predOps(ARMCC::AL))
2528           .addReg(ScratchReg0);
2529       BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2530           .addReg(ScratchReg0)
2531           .add(predOps(ARMCC::AL));
2532     } else {
2533       BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2534           .addReg(ARM::LR, RegState::Define)
2535           .addReg(ARM::SP, RegState::Define)
2536           .addReg(ARM::SP)
2537           .addImm(4)
2538           .add(predOps(ARMCC::AL));
2539     }
2540   } else {
2541     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2542         .addReg(ARM::SP, RegState::Define)
2543         .addReg(ARM::SP)
2544         .add(predOps(ARMCC::AL))
2545         .addReg(ARM::LR);
2546   }
2547 
2548   // Restore SR0 and SR1 in case of __morestack() was called.
2549   // __morestack() will skip PostStackMBB block so we need to restore
2550   // scratch registers from here.
2551   // pop {SR0, SR1}
2552   if (Thumb) {
2553     BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2554         .add(predOps(ARMCC::AL))
2555         .addReg(ScratchReg0)
2556         .addReg(ScratchReg1);
2557   } else {
2558     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2559         .addReg(ARM::SP, RegState::Define)
2560         .addReg(ARM::SP)
2561         .add(predOps(ARMCC::AL))
2562         .addReg(ScratchReg0)
2563         .addReg(ScratchReg1);
2564   }
2565 
2566   // Update the CFA offset now that we've popped
2567   CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2568   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2569       .addCFIIndex(CFIIndex);
2570 
2571   // Return from this function.
2572   BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
2573 
2574   // Restore SR0 and SR1 in case of __morestack() was not called.
2575   // pop {SR0, SR1}
2576   if (Thumb) {
2577     BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2578         .add(predOps(ARMCC::AL))
2579         .addReg(ScratchReg0)
2580         .addReg(ScratchReg1);
2581   } else {
2582     BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2583         .addReg(ARM::SP, RegState::Define)
2584         .addReg(ARM::SP)
2585         .add(predOps(ARMCC::AL))
2586         .addReg(ScratchReg0)
2587         .addReg(ScratchReg1);
2588   }
2589 
2590   // Update the CFA offset now that we've popped
2591   CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2592   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2593       .addCFIIndex(CFIIndex);
2594 
2595   // Tell debuggers that r4 and r5 are now the same as they were in the
2596   // previous function, that they're the "Same Value".
2597   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2598       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2599   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2600       .addCFIIndex(CFIIndex);
2601   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2602       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2603   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2604       .addCFIIndex(CFIIndex);
2605 
2606   // Organizing MBB lists
2607   PostStackMBB->addSuccessor(&PrologueMBB);
2608 
2609   AllocMBB->addSuccessor(PostStackMBB);
2610 
2611   GetMBB->addSuccessor(PostStackMBB);
2612   GetMBB->addSuccessor(AllocMBB);
2613 
2614   McrMBB->addSuccessor(GetMBB);
2615 
2616   PrevStackMBB->addSuccessor(McrMBB);
2617 
2618 #ifdef EXPENSIVE_CHECKS
2619   MF.verify();
2620 #endif
2621 }
2622