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