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