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