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