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