ARM: refactor .cfi_def_cfa_offset emission.
[oota-llvm.git] / lib / Target / ARM / ARMFrameLowering.cpp
1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the ARM implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMFrameLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "MCTargetDesc/ARMAddressingModes.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Target/TargetOptions.h"
31
32 using namespace llvm;
33
34 static cl::opt<bool>
35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36                      cl::desc("Align ARM NEON spills in prolog and epilog"));
37
38 static MachineBasicBlock::iterator
39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40                         unsigned NumAlignedDPRCS2Regs);
41
42 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
44       STI(sti) {}
45
46 /// hasFP - Return true if the specified function should have a dedicated frame
47 /// pointer register.  This is true if the function has variable sized allocas
48 /// or if frame pointer elimination is disabled.
49 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
50   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
51
52   // iOS requires FP not to be clobbered for backtracing purpose.
53   if (STI.isTargetIOS())
54     return true;
55
56   const MachineFrameInfo *MFI = MF.getFrameInfo();
57   // Always eliminate non-leaf frame pointers.
58   return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
59            MFI->hasCalls()) ||
60           RegInfo->needsStackRealignment(MF) ||
61           MFI->hasVarSizedObjects() ||
62           MFI->isFrameAddressTaken());
63 }
64
65 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66 /// not required, we reserve argument space for call sites in the function
67 /// immediately on entry to the current function.  This eliminates the need for
68 /// add/sub sp brackets around call sites.  Returns true if the call frame is
69 /// included as part of the stack frame.
70 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
71   const MachineFrameInfo *FFI = MF.getFrameInfo();
72   unsigned CFSize = FFI->getMaxCallFrameSize();
73   // It's not always a good idea to include the call frame as part of the
74   // stack frame. ARM (especially Thumb) has small immediate offset to
75   // address the stack frame. So a large call frame can cause poor codegen
76   // and may even makes it impossible to scavenge a register.
77   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
78     return false;
79
80   return !MF.getFrameInfo()->hasVarSizedObjects();
81 }
82
83 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
85 /// is not sufficient here since we still may reference some objects via SP
86 /// even when FP is available in Thumb2 mode.
87 bool
88 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
89   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
90 }
91
92 static bool isCSRestore(MachineInstr *MI,
93                         const ARMBaseInstrInfo &TII,
94                         const MCPhysReg *CSRegs) {
95   // Integer spill area is handled with "pop".
96   if (isPopOpcode(MI->getOpcode())) {
97     // The first two operands are predicates. The last two are
98     // imp-def and imp-use of SP. Check everything in between.
99     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
101         return false;
102     return true;
103   }
104   if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105        MI->getOpcode() == ARM::LDR_POST_REG ||
106        MI->getOpcode() == ARM::t2LDR_POST) &&
107       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108       MI->getOperand(1).getReg() == ARM::SP)
109     return true;
110
111   return false;
112 }
113
114 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115                                  MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116                                  const ARMBaseInstrInfo &TII, unsigned DestReg,
117                                  unsigned SrcReg, int NumBytes,
118                                  unsigned MIFlags = MachineInstr::NoFlags,
119                                  ARMCC::CondCodes Pred = ARMCC::AL,
120                                  unsigned PredReg = 0) {
121   if (isARM)
122     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123                             Pred, PredReg, TII, MIFlags);
124   else
125     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126                            Pred, PredReg, TII, MIFlags);
127 }
128
129 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130                          MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131                          const ARMBaseInstrInfo &TII, int NumBytes,
132                          unsigned MIFlags = MachineInstr::NoFlags,
133                          ARMCC::CondCodes Pred = ARMCC::AL,
134                          unsigned PredReg = 0) {
135   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136                        MIFlags, Pred, PredReg);
137 }
138
139 static int sizeOfSPAdjustment(const MachineInstr *MI) {
140   int RegSize;
141   switch (MI->getOpcode()) {
142   case ARM::VSTMDDB_UPD:
143     RegSize = 8;
144     break;
145   case ARM::STMDB_UPD:
146   case ARM::t2STMDB_UPD:
147     RegSize = 4;
148     break;
149   case ARM::t2STR_PRE:
150   case ARM::STR_PRE_IMM:
151     return 4;
152   default:
153     llvm_unreachable("Unknown push or pop like instruction");
154   }
155
156   int count = 0;
157   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
158   // pred) so the list starts at 4.
159   for (int i = MI->getNumOperands() - 1; i >= 4; --i)
160     count += RegSize;
161   return count;
162 }
163
164 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
165                                       size_t StackSizeInBytes) {
166   const MachineFrameInfo *MFI = MF.getFrameInfo();
167   if (MFI->getStackProtectorIndex() > 0)
168     return StackSizeInBytes >= 4080;
169   return StackSizeInBytes >= 4096;
170 }
171
172 namespace {
173 struct StackAdjustingInsts {
174   struct InstInfo {
175     MachineBasicBlock::iterator I;
176     unsigned SPAdjust;
177     bool BeforeFPSet;
178   };
179
180   SmallVector<InstInfo, 4> Insts;
181
182   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
183                bool BeforeFPSet = false) {
184     InstInfo Info = {I, SPAdjust, BeforeFPSet};
185     Insts.push_back(Info);
186   }
187
188   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
189     auto Info = std::find_if(Insts.begin(), Insts.end(),
190                              [&](InstInfo &Info) { return Info.I == I; });
191     assert(Info != Insts.end() && "invalid sp adjusting instruction");
192     Info->SPAdjust += ExtraBytes;
193   }
194
195   void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
196                          DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
197     unsigned CFAOffset = 0;
198     for (auto &Info : Insts) {
199       if (HasFP && !Info.BeforeFPSet)
200         return;
201
202       CFAOffset -= Info.SPAdjust;
203       unsigned CFIIndex = MMI.addFrameInst(
204           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
205       BuildMI(MBB, std::next(Info.I), dl,
206               TII.get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(CFIIndex);
207     }
208   }
209 };
210 }
211
212 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
213   MachineBasicBlock &MBB = MF.front();
214   MachineBasicBlock::iterator MBBI = MBB.begin();
215   MachineFrameInfo  *MFI = MF.getFrameInfo();
216   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
217   MachineModuleInfo &MMI = MF.getMMI();
218   MCContext &Context = MMI.getContext();
219   const TargetMachine &TM = MF.getTarget();
220   const MCRegisterInfo *MRI = Context.getRegisterInfo();
221   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
222       TM.getSubtargetImpl()->getRegisterInfo());
223   const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
224                                     TM.getSubtargetImpl()->getInstrInfo());
225   assert(!AFI->isThumb1OnlyFunction() &&
226          "This emitPrologue does not support Thumb1!");
227   bool isARM = !AFI->isThumbFunction();
228   unsigned Align =
229       TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
230   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
231   unsigned NumBytes = MFI->getStackSize();
232   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
233   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
234   unsigned FramePtr = RegInfo->getFrameRegister(MF);
235
236   // Determine the sizes of each callee-save spill areas and record which frame
237   // belongs to which callee-save spill areas.
238   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
239   int FramePtrSpillFI = 0;
240   int D8SpillFI = 0;
241
242   // All calls are tail calls in GHC calling conv, and functions have no
243   // prologue/epilogue.
244   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
245     return;
246
247   StackAdjustingInsts DefCFAOffsetCandidates;
248
249   // Allocate the vararg register save area.
250   if (ArgRegsSaveSize) {
251     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
252                  MachineInstr::FrameSetup);
253     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
254   }
255
256   if (!AFI->hasStackFrame() &&
257       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
258     if (NumBytes - ArgRegsSaveSize != 0) {
259       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
260                    MachineInstr::FrameSetup);
261       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
262                                      NumBytes - ArgRegsSaveSize, true);
263     }
264     return;
265   }
266
267   // Determine spill area sizes.
268   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
269     unsigned Reg = CSI[i].getReg();
270     int FI = CSI[i].getFrameIdx();
271     switch (Reg) {
272     case ARM::R8:
273     case ARM::R9:
274     case ARM::R10:
275     case ARM::R11:
276     case ARM::R12:
277       if (STI.isTargetDarwin()) {
278         GPRCS2Size += 4;
279         break;
280       }
281       // fallthrough
282     case ARM::R0:
283     case ARM::R1:
284     case ARM::R2:
285     case ARM::R3:
286     case ARM::R4:
287     case ARM::R5:
288     case ARM::R6:
289     case ARM::R7:
290     case ARM::LR:
291       if (Reg == FramePtr)
292         FramePtrSpillFI = FI;
293       GPRCS1Size += 4;
294       break;
295     default:
296       // This is a DPR. Exclude the aligned DPRCS2 spills.
297       if (Reg == ARM::D8)
298         D8SpillFI = FI;
299       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
300         DPRCSSize += 8;
301     }
302   }
303
304   // Move past area 1.
305   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
306   if (GPRCS1Size > 0) {
307     GPRCS1Push = LastPush = MBBI++;
308     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
309   }
310
311   // Determine starting offsets of spill areas.
312   bool HasFP = hasFP(MF);
313   unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
314   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
315   unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
316   unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
317   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
318   int FramePtrOffsetInPush = 0;
319   if (HasFP) {
320     FramePtrOffsetInPush =
321         MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
322     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
323                                 NumBytes);
324   }
325   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
326   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
327   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
328
329   // Move past area 2.
330   if (GPRCS2Size > 0) {
331     GPRCS2Push = LastPush = MBBI++;
332     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
333   }
334
335   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
336   // .cfi_offset operations will reflect that.
337   if (DPRGapSize) {
338     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
339     if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
340       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
341     else {
342       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
343                    MachineInstr::FrameSetup);
344       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
345     }
346   }
347
348   // Move past area 3.
349   if (DPRCSSize > 0) {
350     // Since vpush register list cannot have gaps, there may be multiple vpush
351     // instructions in the prologue.
352     while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
353       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
354       LastPush = MBBI++;
355     }
356   }
357
358   // Move past the aligned DPRCS2 area.
359   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
360     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
361     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
362     // leaves the stack pointer pointing to the DPRCS2 area.
363     //
364     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
365     NumBytes += MFI->getObjectOffset(D8SpillFI);
366   } else
367     NumBytes = DPRCSOffset;
368
369   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
370     uint32_t NumWords = NumBytes >> 2;
371
372     if (NumWords < 65536)
373       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
374                      .addImm(NumWords)
375                      .setMIFlags(MachineInstr::FrameSetup));
376     else
377       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
378         .addImm(NumWords)
379         .setMIFlags(MachineInstr::FrameSetup);
380
381     switch (TM.getCodeModel()) {
382     case CodeModel::Small:
383     case CodeModel::Medium:
384     case CodeModel::Default:
385     case CodeModel::Kernel:
386       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
387         .addImm((unsigned)ARMCC::AL).addReg(0)
388         .addExternalSymbol("__chkstk")
389         .addReg(ARM::R4, RegState::Implicit)
390         .setMIFlags(MachineInstr::FrameSetup);
391       break;
392     case CodeModel::Large:
393     case CodeModel::JITDefault:
394       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
395         .addExternalSymbol("__chkstk")
396         .setMIFlags(MachineInstr::FrameSetup);
397
398       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
399         .addImm((unsigned)ARMCC::AL).addReg(0)
400         .addReg(ARM::R12, RegState::Kill)
401         .addReg(ARM::R4, RegState::Implicit)
402         .setMIFlags(MachineInstr::FrameSetup);
403       break;
404     }
405
406     AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
407                                         ARM::SP)
408                                 .addReg(ARM::SP, RegState::Define)
409                                 .addReg(ARM::R4, RegState::Kill)
410                                 .setMIFlags(MachineInstr::FrameSetup)));
411     NumBytes = 0;
412   }
413
414   if (NumBytes) {
415     // Adjust SP after all the callee-save spills.
416     if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
417       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
418     else {
419       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
420                    MachineInstr::FrameSetup);
421       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
422     }
423
424     if (HasFP && isARM)
425       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
426       // Note it's not safe to do this in Thumb2 mode because it would have
427       // taken two instructions:
428       // mov sp, r7
429       // sub sp, #24
430       // If an interrupt is taken between the two instructions, then sp is in
431       // an inconsistent state (pointing to the middle of callee-saved area).
432       // The interrupt handler can end up clobbering the registers.
433       AFI->setShouldRestoreSPFromFP(true);
434   }
435
436   // Set FP to point to the stack slot that contains the previous FP.
437   // For iOS, FP is R7, which has now been stored in spill area 1.
438   // Otherwise, if this is not iOS, all the callee-saved registers go
439   // into spill area 1, including the FP in R11.  In either case, it
440   // is in area one and the adjustment needs to take place just after
441   // that push.
442   if (HasFP) {
443     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
444     unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
445     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
446                          dl, TII, FramePtr, ARM::SP,
447                          PushSize + FramePtrOffsetInPush,
448                          MachineInstr::FrameSetup);
449     if (FramePtrOffsetInPush + PushSize != 0) {
450       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
451           nullptr, MRI->getDwarfRegNum(FramePtr, true),
452           -(ArgRegsSaveSize - FramePtrOffsetInPush)));
453       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
454           .addCFIIndex(CFIIndex);
455     } else {
456       unsigned CFIIndex =
457           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
458               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
459       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
460           .addCFIIndex(CFIIndex);
461     }
462   }
463
464   // Now that the prologue's actual instructions are finalised, we can insert
465   // the necessary DWARF cf instructions to describe the situation. Start by
466   // recording where each register ended up:
467   if (GPRCS1Size > 0) {
468     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
469     int CFIIndex;
470     for (const auto &Entry : CSI) {
471       unsigned Reg = Entry.getReg();
472       int FI = Entry.getFrameIdx();
473       switch (Reg) {
474       case ARM::R8:
475       case ARM::R9:
476       case ARM::R10:
477       case ARM::R11:
478       case ARM::R12:
479         if (STI.isTargetDarwin())
480           break;
481         // fallthrough
482       case ARM::R0:
483       case ARM::R1:
484       case ARM::R2:
485       case ARM::R3:
486       case ARM::R4:
487       case ARM::R5:
488       case ARM::R6:
489       case ARM::R7:
490       case ARM::LR:
491         CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
492             nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
493         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
494             .addCFIIndex(CFIIndex);
495         break;
496       }
497     }
498   }
499
500   if (GPRCS2Size > 0) {
501     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
502     for (const auto &Entry : CSI) {
503       unsigned Reg = Entry.getReg();
504       int FI = Entry.getFrameIdx();
505       switch (Reg) {
506       case ARM::R8:
507       case ARM::R9:
508       case ARM::R10:
509       case ARM::R11:
510       case ARM::R12:
511         if (STI.isTargetDarwin()) {
512           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
513           unsigned Offset = MFI->getObjectOffset(FI);
514           unsigned CFIIndex = MMI.addFrameInst(
515               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
516           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
517               .addCFIIndex(CFIIndex);
518         }
519         break;
520       }
521     }
522   }
523
524   if (DPRCSSize > 0) {
525     // Since vpush register list cannot have gaps, there may be multiple vpush
526     // instructions in the prologue.
527     MachineBasicBlock::iterator Pos = std::next(LastPush);
528     for (const auto &Entry : CSI) {
529       unsigned Reg = Entry.getReg();
530       int FI = Entry.getFrameIdx();
531       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
532           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
533         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
534         unsigned Offset = MFI->getObjectOffset(FI);
535         unsigned CFIIndex = MMI.addFrameInst(
536             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
537         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
538             .addCFIIndex(CFIIndex);
539       }
540     }
541   }
542
543   // Now we can emit descriptions of where the canonical frame address was
544   // throughout the process. If we have a frame pointer, it takes over the job
545   // half-way through, so only the first few .cfi_def_cfa_offset instructions
546   // actually get emitted.
547   DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
548
549   if (STI.isTargetELF() && hasFP(MF))
550     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
551                              AFI->getFramePtrSpillOffset());
552
553   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
554   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
555   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
556   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
557
558   // If we need dynamic stack realignment, do it here. Be paranoid and make
559   // sure if we also have VLAs, we have a base pointer for frame access.
560   // If aligned NEON registers were spilled, the stack has already been
561   // realigned.
562   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
563     unsigned MaxAlign = MFI->getMaxAlignment();
564     assert (!AFI->isThumb1OnlyFunction());
565     if (!AFI->isThumbFunction()) {
566       // Emit bic sp, sp, MaxAlign
567       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
568                                           TII.get(ARM::BICri), ARM::SP)
569                                   .addReg(ARM::SP, RegState::Kill)
570                                   .addImm(MaxAlign-1)));
571     } else {
572       // We cannot use sp as source/dest register here, thus we're emitting the
573       // following sequence:
574       // mov r4, sp
575       // bic r4, r4, MaxAlign
576       // mov sp, r4
577       // FIXME: It will be better just to find spare register here.
578       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
579         .addReg(ARM::SP, RegState::Kill));
580       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
581                                           TII.get(ARM::t2BICri), ARM::R4)
582                                   .addReg(ARM::R4, RegState::Kill)
583                                   .addImm(MaxAlign-1)));
584       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
585         .addReg(ARM::R4, RegState::Kill));
586     }
587
588     AFI->setShouldRestoreSPFromFP(true);
589   }
590
591   // If we need a base pointer, set it up here. It's whatever the value
592   // of the stack pointer is at this point. Any variable size objects
593   // will be allocated after this, so we can still use the base pointer
594   // to reference locals.
595   // FIXME: Clarify FrameSetup flags here.
596   if (RegInfo->hasBasePointer(MF)) {
597     if (isARM)
598       BuildMI(MBB, MBBI, dl,
599               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
600         .addReg(ARM::SP)
601         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
602     else
603       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
604                              RegInfo->getBaseRegister())
605         .addReg(ARM::SP));
606   }
607
608   // If the frame has variable sized objects then the epilogue must restore
609   // the sp from fp. We can assume there's an FP here since hasFP already
610   // checks for hasVarSizedObjects.
611   if (MFI->hasVarSizedObjects())
612     AFI->setShouldRestoreSPFromFP(true);
613 }
614
615 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
616                                     MachineBasicBlock &MBB) const {
617   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
618   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
619   unsigned RetOpcode = MBBI->getOpcode();
620   DebugLoc dl = MBBI->getDebugLoc();
621   MachineFrameInfo *MFI = MF.getFrameInfo();
622   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
623   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
624   const ARMBaseInstrInfo &TII =
625       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
626   assert(!AFI->isThumb1OnlyFunction() &&
627          "This emitEpilogue does not support Thumb1!");
628   bool isARM = !AFI->isThumbFunction();
629
630   unsigned Align = MF.getTarget()
631                        .getSubtargetImpl()
632                        ->getFrameLowering()
633                        ->getStackAlignment();
634   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
635   int NumBytes = (int)MFI->getStackSize();
636   unsigned FramePtr = RegInfo->getFrameRegister(MF);
637
638   // All calls are tail calls in GHC calling conv, and functions have no
639   // prologue/epilogue.
640   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
641     return;
642
643   if (!AFI->hasStackFrame()) {
644     if (NumBytes - ArgRegsSaveSize != 0)
645       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
646   } else {
647     // Unwind MBBI to point to first LDR / VLDRD.
648     const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
649     if (MBBI != MBB.begin()) {
650       do {
651         --MBBI;
652       } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
653       if (!isCSRestore(MBBI, TII, CSRegs))
654         ++MBBI;
655     }
656
657     // Move SP to start of FP callee save spill area.
658     NumBytes -= (ArgRegsSaveSize +
659                  AFI->getGPRCalleeSavedArea1Size() +
660                  AFI->getGPRCalleeSavedArea2Size() +
661                  AFI->getDPRCalleeSavedGapSize() +
662                  AFI->getDPRCalleeSavedAreaSize());
663
664     // Reset SP based on frame pointer only if the stack frame extends beyond
665     // frame pointer stack slot or target is ELF and the function has FP.
666     if (AFI->shouldRestoreSPFromFP()) {
667       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
668       if (NumBytes) {
669         if (isARM)
670           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
671                                   ARMCC::AL, 0, TII);
672         else {
673           // It's not possible to restore SP from FP in a single instruction.
674           // For iOS, this looks like:
675           // mov sp, r7
676           // sub sp, #24
677           // This is bad, if an interrupt is taken after the mov, sp is in an
678           // inconsistent state.
679           // Use the first callee-saved register as a scratch register.
680           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
681                  "No scratch register to restore SP from FP!");
682           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
683                                  ARMCC::AL, 0, TII);
684           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
685                                  ARM::SP)
686             .addReg(ARM::R4));
687         }
688       } else {
689         // Thumb2 or ARM.
690         if (isARM)
691           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
692             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
693         else
694           AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
695                                  ARM::SP)
696             .addReg(FramePtr));
697       }
698     } else if (NumBytes &&
699                !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
700         emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
701
702     // Increment past our save areas.
703     if (AFI->getDPRCalleeSavedAreaSize()) {
704       MBBI++;
705       // Since vpop register list cannot have gaps, there may be multiple vpop
706       // instructions in the epilogue.
707       while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
708         MBBI++;
709     }
710     if (AFI->getDPRCalleeSavedGapSize()) {
711       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
712              "unexpected DPR alignment gap");
713       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
714     }
715
716     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
717     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
718   }
719
720   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
721     // Tail call return: adjust the stack pointer and jump to callee.
722     MBBI = MBB.getLastNonDebugInstr();
723     MachineOperand &JumpTarget = MBBI->getOperand(0);
724
725     // Jump to label or value in register.
726     if (RetOpcode == ARM::TCRETURNdi) {
727       unsigned TCOpcode = STI.isThumb() ?
728                (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
729                ARM::TAILJMPd;
730       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
731       if (JumpTarget.isGlobal())
732         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
733                              JumpTarget.getTargetFlags());
734       else {
735         assert(JumpTarget.isSymbol());
736         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
737                               JumpTarget.getTargetFlags());
738       }
739
740       // Add the default predicate in Thumb mode.
741       if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
742     } else if (RetOpcode == ARM::TCRETURNri) {
743       BuildMI(MBB, MBBI, dl,
744               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
745         addReg(JumpTarget.getReg(), RegState::Kill);
746     }
747
748     MachineInstr *NewMI = std::prev(MBBI);
749     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
750       NewMI->addOperand(MBBI->getOperand(i));
751
752     // Delete the pseudo instruction TCRETURN.
753     MBB.erase(MBBI);
754     MBBI = NewMI;
755   }
756
757   if (ArgRegsSaveSize)
758     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
759 }
760
761 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
762 /// debug info.  It's the same as what we use for resolving the code-gen
763 /// references for now.  FIXME: This can go wrong when references are
764 /// SP-relative and simple call frames aren't used.
765 int
766 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
767                                          unsigned &FrameReg) const {
768   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
769 }
770
771 int
772 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
773                                              int FI, unsigned &FrameReg,
774                                              int SPAdj) const {
775   const MachineFrameInfo *MFI = MF.getFrameInfo();
776   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
777       MF.getSubtarget().getRegisterInfo());
778   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
779   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
780   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
781   bool isFixed = MFI->isFixedObjectIndex(FI);
782
783   FrameReg = ARM::SP;
784   Offset += SPAdj;
785
786   // SP can move around if there are allocas.  We may also lose track of SP
787   // when emergency spilling inside a non-reserved call frame setup.
788   bool hasMovingSP = !hasReservedCallFrame(MF);
789
790   // When dynamically realigning the stack, use the frame pointer for
791   // parameters, and the stack/base pointer for locals.
792   if (RegInfo->needsStackRealignment(MF)) {
793     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
794     if (isFixed) {
795       FrameReg = RegInfo->getFrameRegister(MF);
796       Offset = FPOffset;
797     } else if (hasMovingSP) {
798       assert(RegInfo->hasBasePointer(MF) &&
799              "VLAs and dynamic stack alignment, but missing base pointer!");
800       FrameReg = RegInfo->getBaseRegister();
801     }
802     return Offset;
803   }
804
805   // If there is a frame pointer, use it when we can.
806   if (hasFP(MF) && AFI->hasStackFrame()) {
807     // Use frame pointer to reference fixed objects. Use it for locals if
808     // there are VLAs (and thus the SP isn't reliable as a base).
809     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
810       FrameReg = RegInfo->getFrameRegister(MF);
811       return FPOffset;
812     } else if (hasMovingSP) {
813       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
814       if (AFI->isThumb2Function()) {
815         // Try to use the frame pointer if we can, else use the base pointer
816         // since it's available. This is handy for the emergency spill slot, in
817         // particular.
818         if (FPOffset >= -255 && FPOffset < 0) {
819           FrameReg = RegInfo->getFrameRegister(MF);
820           return FPOffset;
821         }
822       }
823     } else if (AFI->isThumb2Function()) {
824       // Use  add <rd>, sp, #<imm8>
825       //      ldr <rd>, [sp, #<imm8>]
826       // if at all possible to save space.
827       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
828         return Offset;
829       // In Thumb2 mode, the negative offset is very limited. Try to avoid
830       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
831       if (FPOffset >= -255 && FPOffset < 0) {
832         FrameReg = RegInfo->getFrameRegister(MF);
833         return FPOffset;
834       }
835     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
836       // Otherwise, use SP or FP, whichever is closer to the stack slot.
837       FrameReg = RegInfo->getFrameRegister(MF);
838       return FPOffset;
839     }
840   }
841   // Use the base pointer if we have one.
842   if (RegInfo->hasBasePointer(MF))
843     FrameReg = RegInfo->getBaseRegister();
844   return Offset;
845 }
846
847 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
848                                           int FI) const {
849   unsigned FrameReg;
850   return getFrameIndexReference(MF, FI, FrameReg);
851 }
852
853 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
854                                     MachineBasicBlock::iterator MI,
855                                     const std::vector<CalleeSavedInfo> &CSI,
856                                     unsigned StmOpc, unsigned StrOpc,
857                                     bool NoGap,
858                                     bool(*Func)(unsigned, bool),
859                                     unsigned NumAlignedDPRCS2Regs,
860                                     unsigned MIFlags) const {
861   MachineFunction &MF = *MBB.getParent();
862   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
863
864   DebugLoc DL;
865   if (MI != MBB.end()) DL = MI->getDebugLoc();
866
867   SmallVector<std::pair<unsigned,bool>, 4> Regs;
868   unsigned i = CSI.size();
869   while (i != 0) {
870     unsigned LastReg = 0;
871     for (; i != 0; --i) {
872       unsigned Reg = CSI[i-1].getReg();
873       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
874
875       // D-registers in the aligned area DPRCS2 are NOT spilled here.
876       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
877         continue;
878
879       // Add the callee-saved register as live-in unless it's LR and
880       // @llvm.returnaddress is called. If LR is returned for
881       // @llvm.returnaddress then it's already added to the function and
882       // entry block live-in sets.
883       bool isKill = true;
884       if (Reg == ARM::LR) {
885         if (MF.getFrameInfo()->isReturnAddressTaken() &&
886             MF.getRegInfo().isLiveIn(Reg))
887           isKill = false;
888       }
889
890       if (isKill)
891         MBB.addLiveIn(Reg);
892
893       // If NoGap is true, push consecutive registers and then leave the rest
894       // for other instructions. e.g.
895       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
896       if (NoGap && LastReg && LastReg != Reg-1)
897         break;
898       LastReg = Reg;
899       Regs.push_back(std::make_pair(Reg, isKill));
900     }
901
902     if (Regs.empty())
903       continue;
904     if (Regs.size() > 1 || StrOpc== 0) {
905       MachineInstrBuilder MIB =
906         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
907                        .addReg(ARM::SP).setMIFlags(MIFlags));
908       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
909         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
910     } else if (Regs.size() == 1) {
911       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
912                                         ARM::SP)
913         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
914         .addReg(ARM::SP).setMIFlags(MIFlags)
915         .addImm(-4);
916       AddDefaultPred(MIB);
917     }
918     Regs.clear();
919
920     // Put any subsequent vpush instructions before this one: they will refer to
921     // higher register numbers so need to be pushed first in order to preserve
922     // monotonicity.
923     --MI;
924   }
925 }
926
927 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
928                                    MachineBasicBlock::iterator MI,
929                                    const std::vector<CalleeSavedInfo> &CSI,
930                                    unsigned LdmOpc, unsigned LdrOpc,
931                                    bool isVarArg, bool NoGap,
932                                    bool(*Func)(unsigned, bool),
933                                    unsigned NumAlignedDPRCS2Regs) const {
934   MachineFunction &MF = *MBB.getParent();
935   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
936   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
937   DebugLoc DL = MI->getDebugLoc();
938   unsigned RetOpcode = MI->getOpcode();
939   bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
940                      RetOpcode == ARM::TCRETURNri);
941   bool isInterrupt =
942       RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
943
944   SmallVector<unsigned, 4> Regs;
945   unsigned i = CSI.size();
946   while (i != 0) {
947     unsigned LastReg = 0;
948     bool DeleteRet = false;
949     for (; i != 0; --i) {
950       unsigned Reg = CSI[i-1].getReg();
951       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
952
953       // The aligned reloads from area DPRCS2 are not inserted here.
954       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
955         continue;
956
957       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
958           STI.hasV5TOps()) {
959         Reg = ARM::PC;
960         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
961         // Fold the return instruction into the LDM.
962         DeleteRet = true;
963       }
964
965       // If NoGap is true, pop consecutive registers and then leave the rest
966       // for other instructions. e.g.
967       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
968       if (NoGap && LastReg && LastReg != Reg-1)
969         break;
970
971       LastReg = Reg;
972       Regs.push_back(Reg);
973     }
974
975     if (Regs.empty())
976       continue;
977     if (Regs.size() > 1 || LdrOpc == 0) {
978       MachineInstrBuilder MIB =
979         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
980                        .addReg(ARM::SP));
981       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
982         MIB.addReg(Regs[i], getDefRegState(true));
983       if (DeleteRet) {
984         MIB.copyImplicitOps(&*MI);
985         MI->eraseFromParent();
986       }
987       MI = MIB;
988     } else if (Regs.size() == 1) {
989       // If we adjusted the reg to PC from LR above, switch it back here. We
990       // only do that for LDM.
991       if (Regs[0] == ARM::PC)
992         Regs[0] = ARM::LR;
993       MachineInstrBuilder MIB =
994         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
995           .addReg(ARM::SP, RegState::Define)
996           .addReg(ARM::SP);
997       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
998       // that refactoring is complete (eventually).
999       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1000         MIB.addReg(0);
1001         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1002       } else
1003         MIB.addImm(4);
1004       AddDefaultPred(MIB);
1005     }
1006     Regs.clear();
1007
1008     // Put any subsequent vpop instructions after this one: they will refer to
1009     // higher register numbers so need to be popped afterwards.
1010     ++MI;
1011   }
1012 }
1013
1014 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1015 /// starting from d8.  Also insert stack realignment code and leave the stack
1016 /// pointer pointing to the d8 spill slot.
1017 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1018                                     MachineBasicBlock::iterator MI,
1019                                     unsigned NumAlignedDPRCS2Regs,
1020                                     const std::vector<CalleeSavedInfo> &CSI,
1021                                     const TargetRegisterInfo *TRI) {
1022   MachineFunction &MF = *MBB.getParent();
1023   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1024   DebugLoc DL = MI->getDebugLoc();
1025   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1026   MachineFrameInfo &MFI = *MF.getFrameInfo();
1027
1028   // Mark the D-register spill slots as properly aligned.  Since MFI computes
1029   // stack slot layout backwards, this can actually mean that the d-reg stack
1030   // slot offsets can be wrong. The offset for d8 will always be correct.
1031   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1032     unsigned DNum = CSI[i].getReg() - ARM::D8;
1033     if (DNum >= 8)
1034       continue;
1035     int FI = CSI[i].getFrameIdx();
1036     // The even-numbered registers will be 16-byte aligned, the odd-numbered
1037     // registers will be 8-byte aligned.
1038     MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1039
1040     // The stack slot for D8 needs to be maximally aligned because this is
1041     // actually the point where we align the stack pointer.  MachineFrameInfo
1042     // computes all offsets relative to the incoming stack pointer which is a
1043     // bit weird when realigning the stack.  Any extra padding for this
1044     // over-alignment is not realized because the code inserted below adjusts
1045     // the stack pointer by numregs * 8 before aligning the stack pointer.
1046     if (DNum == 0)
1047       MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1048   }
1049
1050   // Move the stack pointer to the d8 spill slot, and align it at the same
1051   // time. Leave the stack slot address in the scratch register r4.
1052   //
1053   //   sub r4, sp, #numregs * 8
1054   //   bic r4, r4, #align - 1
1055   //   mov sp, r4
1056   //
1057   bool isThumb = AFI->isThumbFunction();
1058   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1059   AFI->setShouldRestoreSPFromFP(true);
1060
1061   // sub r4, sp, #numregs * 8
1062   // The immediate is <= 64, so it doesn't need any special encoding.
1063   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1064   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1065                               .addReg(ARM::SP)
1066                               .addImm(8 * NumAlignedDPRCS2Regs)));
1067
1068   // bic r4, r4, #align-1
1069   Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1070   unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1071   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1072                               .addReg(ARM::R4, RegState::Kill)
1073                               .addImm(MaxAlign - 1)));
1074
1075   // mov sp, r4
1076   // The stack pointer must be adjusted before spilling anything, otherwise
1077   // the stack slots could be clobbered by an interrupt handler.
1078   // Leave r4 live, it is used below.
1079   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1080   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1081                             .addReg(ARM::R4);
1082   MIB = AddDefaultPred(MIB);
1083   if (!isThumb)
1084     AddDefaultCC(MIB);
1085
1086   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1087   // r4 holds the stack slot address.
1088   unsigned NextReg = ARM::D8;
1089
1090   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1091   // The writeback is only needed when emitting two vst1.64 instructions.
1092   if (NumAlignedDPRCS2Regs >= 6) {
1093     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1094                                                &ARM::QQPRRegClass);
1095     MBB.addLiveIn(SupReg);
1096     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1097                            ARM::R4)
1098                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1099                    .addReg(NextReg)
1100                    .addReg(SupReg, RegState::ImplicitKill));
1101     NextReg += 4;
1102     NumAlignedDPRCS2Regs -= 4;
1103   }
1104
1105   // We won't modify r4 beyond this point.  It currently points to the next
1106   // register to be spilled.
1107   unsigned R4BaseReg = NextReg;
1108
1109   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1110   if (NumAlignedDPRCS2Regs >= 4) {
1111     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1112                                                &ARM::QQPRRegClass);
1113     MBB.addLiveIn(SupReg);
1114     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1115                    .addReg(ARM::R4).addImm(16).addReg(NextReg)
1116                    .addReg(SupReg, RegState::ImplicitKill));
1117     NextReg += 4;
1118     NumAlignedDPRCS2Regs -= 4;
1119   }
1120
1121   // 16-byte aligned vst1.64 with 2 d-regs.
1122   if (NumAlignedDPRCS2Regs >= 2) {
1123     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1124                                                &ARM::QPRRegClass);
1125     MBB.addLiveIn(SupReg);
1126     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1127                    .addReg(ARM::R4).addImm(16).addReg(SupReg));
1128     NextReg += 2;
1129     NumAlignedDPRCS2Regs -= 2;
1130   }
1131
1132   // Finally, use a vanilla vstr.64 for the odd last register.
1133   if (NumAlignedDPRCS2Regs) {
1134     MBB.addLiveIn(NextReg);
1135     // vstr.64 uses addrmode5 which has an offset scale of 4.
1136     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1137                    .addReg(NextReg)
1138                    .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1139   }
1140
1141   // The last spill instruction inserted should kill the scratch register r4.
1142   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1143 }
1144
1145 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1146 /// iterator to the following instruction.
1147 static MachineBasicBlock::iterator
1148 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1149                         unsigned NumAlignedDPRCS2Regs) {
1150   //   sub r4, sp, #numregs * 8
1151   //   bic r4, r4, #align - 1
1152   //   mov sp, r4
1153   ++MI; ++MI; ++MI;
1154   assert(MI->mayStore() && "Expecting spill instruction");
1155
1156   // These switches all fall through.
1157   switch(NumAlignedDPRCS2Regs) {
1158   case 7:
1159     ++MI;
1160     assert(MI->mayStore() && "Expecting spill instruction");
1161   default:
1162     ++MI;
1163     assert(MI->mayStore() && "Expecting spill instruction");
1164   case 1:
1165   case 2:
1166   case 4:
1167     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1168     ++MI;
1169   }
1170   return MI;
1171 }
1172
1173 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1174 /// starting from d8.  These instructions are assumed to execute while the
1175 /// stack is still aligned, unlike the code inserted by emitPopInst.
1176 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1177                                       MachineBasicBlock::iterator MI,
1178                                       unsigned NumAlignedDPRCS2Regs,
1179                                       const std::vector<CalleeSavedInfo> &CSI,
1180                                       const TargetRegisterInfo *TRI) {
1181   MachineFunction &MF = *MBB.getParent();
1182   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1183   DebugLoc DL = MI->getDebugLoc();
1184   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1185
1186   // Find the frame index assigned to d8.
1187   int D8SpillFI = 0;
1188   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1189     if (CSI[i].getReg() == ARM::D8) {
1190       D8SpillFI = CSI[i].getFrameIdx();
1191       break;
1192     }
1193
1194   // Materialize the address of the d8 spill slot into the scratch register r4.
1195   // This can be fairly complicated if the stack frame is large, so just use
1196   // the normal frame index elimination mechanism to do it.  This code runs as
1197   // the initial part of the epilog where the stack and base pointers haven't
1198   // been changed yet.
1199   bool isThumb = AFI->isThumbFunction();
1200   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1201
1202   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1203   AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1204                               .addFrameIndex(D8SpillFI).addImm(0)));
1205
1206   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1207   unsigned NextReg = ARM::D8;
1208
1209   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1210   if (NumAlignedDPRCS2Regs >= 6) {
1211     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1212                                                &ARM::QQPRRegClass);
1213     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1214                    .addReg(ARM::R4, RegState::Define)
1215                    .addReg(ARM::R4, RegState::Kill).addImm(16)
1216                    .addReg(SupReg, RegState::ImplicitDefine));
1217     NextReg += 4;
1218     NumAlignedDPRCS2Regs -= 4;
1219   }
1220
1221   // We won't modify r4 beyond this point.  It currently points to the next
1222   // register to be spilled.
1223   unsigned R4BaseReg = NextReg;
1224
1225   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1226   if (NumAlignedDPRCS2Regs >= 4) {
1227     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1228                                                &ARM::QQPRRegClass);
1229     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1230                    .addReg(ARM::R4).addImm(16)
1231                    .addReg(SupReg, RegState::ImplicitDefine));
1232     NextReg += 4;
1233     NumAlignedDPRCS2Regs -= 4;
1234   }
1235
1236   // 16-byte aligned vld1.64 with 2 d-regs.
1237   if (NumAlignedDPRCS2Regs >= 2) {
1238     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1239                                                &ARM::QPRRegClass);
1240     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1241                    .addReg(ARM::R4).addImm(16));
1242     NextReg += 2;
1243     NumAlignedDPRCS2Regs -= 2;
1244   }
1245
1246   // Finally, use a vanilla vldr.64 for the remaining odd register.
1247   if (NumAlignedDPRCS2Regs)
1248     AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1249                    .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1250
1251   // Last store kills r4.
1252   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1253 }
1254
1255 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1256                                         MachineBasicBlock::iterator MI,
1257                                         const std::vector<CalleeSavedInfo> &CSI,
1258                                         const TargetRegisterInfo *TRI) const {
1259   if (CSI.empty())
1260     return false;
1261
1262   MachineFunction &MF = *MBB.getParent();
1263   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1264
1265   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1266   unsigned PushOneOpc = AFI->isThumbFunction() ?
1267     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1268   unsigned FltOpc = ARM::VSTMDDB_UPD;
1269   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1270   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1271                MachineInstr::FrameSetup);
1272   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1273                MachineInstr::FrameSetup);
1274   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1275                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1276
1277   // The code above does not insert spill code for the aligned DPRCS2 registers.
1278   // The stack realignment code will be inserted between the push instructions
1279   // and these spills.
1280   if (NumAlignedDPRCS2Regs)
1281     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1282
1283   return true;
1284 }
1285
1286 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1287                                         MachineBasicBlock::iterator MI,
1288                                         const std::vector<CalleeSavedInfo> &CSI,
1289                                         const TargetRegisterInfo *TRI) const {
1290   if (CSI.empty())
1291     return false;
1292
1293   MachineFunction &MF = *MBB.getParent();
1294   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1295   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1296   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1297
1298   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1299   // registers. Do that here instead.
1300   if (NumAlignedDPRCS2Regs)
1301     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1302
1303   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1304   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1305   unsigned FltOpc = ARM::VLDMDIA_UPD;
1306   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1307               NumAlignedDPRCS2Regs);
1308   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1309               &isARMArea2Register, 0);
1310   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1311               &isARMArea1Register, 0);
1312
1313   return true;
1314 }
1315
1316 // FIXME: Make generic?
1317 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1318                                        const ARMBaseInstrInfo &TII) {
1319   unsigned FnSize = 0;
1320   for (auto &MBB : MF) {
1321     for (auto &MI : MBB)
1322       FnSize += TII.GetInstSizeInBytes(&MI);
1323   }
1324   return FnSize;
1325 }
1326
1327 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1328 /// frames and return the stack size limit beyond which some of these
1329 /// instructions will require a scratch register during their expansion later.
1330 // FIXME: Move to TII?
1331 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1332                                          const TargetFrameLowering *TFI) {
1333   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1334   unsigned Limit = (1 << 12) - 1;
1335   for (auto &MBB : MF) {
1336     for (auto &MI : MBB) {
1337       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1338         if (!MI.getOperand(i).isFI())
1339           continue;
1340
1341         // When using ADDri to get the address of a stack object, 255 is the
1342         // largest offset guaranteed to fit in the immediate offset.
1343         if (MI.getOpcode() == ARM::ADDri) {
1344           Limit = std::min(Limit, (1U << 8) - 1);
1345           break;
1346         }
1347
1348         // Otherwise check the addressing mode.
1349         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1350         case ARMII::AddrMode3:
1351         case ARMII::AddrModeT2_i8:
1352           Limit = std::min(Limit, (1U << 8) - 1);
1353           break;
1354         case ARMII::AddrMode5:
1355         case ARMII::AddrModeT2_i8s4:
1356           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1357           break;
1358         case ARMII::AddrModeT2_i12:
1359           // i12 supports only positive offset so these will be converted to
1360           // i8 opcodes. See llvm::rewriteT2FrameIndex.
1361           if (TFI->hasFP(MF) && AFI->hasStackFrame())
1362             Limit = std::min(Limit, (1U << 8) - 1);
1363           break;
1364         case ARMII::AddrMode4:
1365         case ARMII::AddrMode6:
1366           // Addressing modes 4 & 6 (load/store) instructions can't encode an
1367           // immediate offset for stack references.
1368           return 0;
1369         default:
1370           break;
1371         }
1372         break; // At most one FI per instruction
1373       }
1374     }
1375   }
1376
1377   return Limit;
1378 }
1379
1380 // In functions that realign the stack, it can be an advantage to spill the
1381 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1382 // instructions take alignment hints that can improve performance.
1383 //
1384 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1385   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1386   if (!SpillAlignedNEONRegs)
1387     return;
1388
1389   // Naked functions don't spill callee-saved registers.
1390   if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1391                                                      Attribute::Naked))
1392     return;
1393
1394   // We are planning to use NEON instructions vst1 / vld1.
1395   if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1396     return;
1397
1398   // Don't bother if the default stack alignment is sufficiently high.
1399   if (MF.getTarget()
1400           .getSubtargetImpl()
1401           ->getFrameLowering()
1402           ->getStackAlignment() >= 8)
1403     return;
1404
1405   // Aligned spills require stack realignment.
1406   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1407       MF.getSubtarget().getRegisterInfo());
1408   if (!RegInfo->canRealignStack(MF))
1409     return;
1410
1411   // We always spill contiguous d-registers starting from d8. Count how many
1412   // needs spilling.  The register allocator will almost always use the
1413   // callee-saved registers in order, but it can happen that there are holes in
1414   // the range.  Registers above the hole will be spilled to the standard DPRCS
1415   // area.
1416   MachineRegisterInfo &MRI = MF.getRegInfo();
1417   unsigned NumSpills = 0;
1418   for (; NumSpills < 8; ++NumSpills)
1419     if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1420       break;
1421
1422   // Don't do this for just one d-register. It's not worth it.
1423   if (NumSpills < 2)
1424     return;
1425
1426   // Spill the first NumSpills D-registers after realigning the stack.
1427   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1428
1429   // A scratch register is required for the vst1 / vld1 instructions.
1430   MF.getRegInfo().setPhysRegUsed(ARM::R4);
1431 }
1432
1433 void
1434 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1435                                                        RegScavenger *RS) const {
1436   // This tells PEI to spill the FP as if it is any other callee-save register
1437   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1438   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1439   // to combine multiple loads / stores.
1440   bool CanEliminateFrame = true;
1441   bool CS1Spilled = false;
1442   bool LRSpilled = false;
1443   unsigned NumGPRSpills = 0;
1444   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1445   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1446   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1447       MF.getSubtarget().getRegisterInfo());
1448   const ARMBaseInstrInfo &TII =
1449       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1450   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1451   MachineFrameInfo *MFI = MF.getFrameInfo();
1452   MachineRegisterInfo &MRI = MF.getRegInfo();
1453   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1454
1455   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1456   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1457   // since it's not always possible to restore sp from fp in a single
1458   // instruction.
1459   // FIXME: It will be better just to find spare register here.
1460   if (AFI->isThumb2Function() &&
1461       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1462     MRI.setPhysRegUsed(ARM::R4);
1463
1464   if (AFI->isThumb1OnlyFunction()) {
1465     // Spill LR if Thumb1 function uses variable length argument lists.
1466     if (AFI->getArgRegsSaveSize() > 0)
1467       MRI.setPhysRegUsed(ARM::LR);
1468
1469     // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1470     // for sure what the stack size will be, but for this, an estimate is good
1471     // enough. If there anything changes it, it'll be a spill, which implies
1472     // we've used all the registers and so R4 is already used, so not marking
1473     // it here will be OK.
1474     // FIXME: It will be better just to find spare register here.
1475     unsigned StackSize = MFI->estimateStackSize(MF);
1476     if (MFI->hasVarSizedObjects() || StackSize > 508)
1477       MRI.setPhysRegUsed(ARM::R4);
1478   }
1479
1480   // See if we can spill vector registers to aligned stack.
1481   checkNumAlignedDPRCS2Regs(MF);
1482
1483   // Spill the BasePtr if it's used.
1484   if (RegInfo->hasBasePointer(MF))
1485     MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1486
1487   // Don't spill FP if the frame can be eliminated. This is determined
1488   // by scanning the callee-save registers to see if any is used.
1489   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1490   for (unsigned i = 0; CSRegs[i]; ++i) {
1491     unsigned Reg = CSRegs[i];
1492     bool Spilled = false;
1493     if (MRI.isPhysRegUsed(Reg)) {
1494       Spilled = true;
1495       CanEliminateFrame = false;
1496     }
1497
1498     if (!ARM::GPRRegClass.contains(Reg))
1499       continue;
1500
1501     if (Spilled) {
1502       NumGPRSpills++;
1503
1504       if (!STI.isTargetDarwin()) {
1505         if (Reg == ARM::LR)
1506           LRSpilled = true;
1507         CS1Spilled = true;
1508         continue;
1509       }
1510
1511       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1512       switch (Reg) {
1513       case ARM::LR:
1514         LRSpilled = true;
1515         // Fallthrough
1516       case ARM::R0: case ARM::R1:
1517       case ARM::R2: case ARM::R3:
1518       case ARM::R4: case ARM::R5:
1519       case ARM::R6: case ARM::R7:
1520         CS1Spilled = true;
1521         break;
1522       default:
1523         break;
1524       }
1525     } else {
1526       if (!STI.isTargetDarwin()) {
1527         UnspilledCS1GPRs.push_back(Reg);
1528         continue;
1529       }
1530
1531       switch (Reg) {
1532       case ARM::R0: case ARM::R1:
1533       case ARM::R2: case ARM::R3:
1534       case ARM::R4: case ARM::R5:
1535       case ARM::R6: case ARM::R7:
1536       case ARM::LR:
1537         UnspilledCS1GPRs.push_back(Reg);
1538         break;
1539       default:
1540         UnspilledCS2GPRs.push_back(Reg);
1541         break;
1542       }
1543     }
1544   }
1545
1546   bool ForceLRSpill = false;
1547   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1548     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1549     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1550     // use of BL to implement far jump. If it turns out that it's not needed
1551     // then the branch fix up path will undo it.
1552     if (FnSize >= (1 << 11)) {
1553       CanEliminateFrame = false;
1554       ForceLRSpill = true;
1555     }
1556   }
1557
1558   // If any of the stack slot references may be out of range of an immediate
1559   // offset, make sure a register (or a spill slot) is available for the
1560   // register scavenger. Note that if we're indexing off the frame pointer, the
1561   // effective stack size is 4 bytes larger since the FP points to the stack
1562   // slot of the previous FP. Also, if we have variable sized objects in the
1563   // function, stack slot references will often be negative, and some of
1564   // our instructions are positive-offset only, so conservatively consider
1565   // that case to want a spill slot (or register) as well. Similarly, if
1566   // the function adjusts the stack pointer during execution and the
1567   // adjustments aren't already part of our stack size estimate, our offset
1568   // calculations may be off, so be conservative.
1569   // FIXME: We could add logic to be more precise about negative offsets
1570   //        and which instructions will need a scratch register for them. Is it
1571   //        worth the effort and added fragility?
1572   bool BigStack =
1573     (RS &&
1574      (MFI->estimateStackSize(MF) +
1575       ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1576       estimateRSStackSizeLimit(MF, this)))
1577     || MFI->hasVarSizedObjects()
1578     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1579
1580   bool ExtraCSSpill = false;
1581   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1582     AFI->setHasStackFrame(true);
1583
1584     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1585     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1586     if (!LRSpilled && CS1Spilled) {
1587       MRI.setPhysRegUsed(ARM::LR);
1588       NumGPRSpills++;
1589       SmallVectorImpl<unsigned>::iterator LRPos;
1590       LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1591                         (unsigned)ARM::LR);
1592       if (LRPos != UnspilledCS1GPRs.end())
1593         UnspilledCS1GPRs.erase(LRPos);
1594
1595       ForceLRSpill = false;
1596       ExtraCSSpill = true;
1597     }
1598
1599     if (hasFP(MF)) {
1600       MRI.setPhysRegUsed(FramePtr);
1601       auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1602                              FramePtr);
1603       if (FPPos != UnspilledCS1GPRs.end())
1604         UnspilledCS1GPRs.erase(FPPos);
1605       NumGPRSpills++;
1606     }
1607
1608     // If stack and double are 8-byte aligned and we are spilling an odd number
1609     // of GPRs, spill one extra callee save GPR so we won't have to pad between
1610     // the integer and double callee save areas.
1611     unsigned TargetAlign = getStackAlignment();
1612     if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1613       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1614         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1615           unsigned Reg = UnspilledCS1GPRs[i];
1616           // Don't spill high register if the function is thumb1
1617           if (!AFI->isThumb1OnlyFunction() ||
1618               isARMLowRegister(Reg) || Reg == ARM::LR) {
1619             MRI.setPhysRegUsed(Reg);
1620             if (!MRI.isReserved(Reg))
1621               ExtraCSSpill = true;
1622             break;
1623           }
1624         }
1625       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1626         unsigned Reg = UnspilledCS2GPRs.front();
1627         MRI.setPhysRegUsed(Reg);
1628         if (!MRI.isReserved(Reg))
1629           ExtraCSSpill = true;
1630       }
1631     }
1632
1633     // Estimate if we might need to scavenge a register at some point in order
1634     // to materialize a stack offset. If so, either spill one additional
1635     // callee-saved register or reserve a special spill slot to facilitate
1636     // register scavenging. Thumb1 needs a spill slot for stack pointer
1637     // adjustments also, even when the frame itself is small.
1638     if (BigStack && !ExtraCSSpill) {
1639       // If any non-reserved CS register isn't spilled, just spill one or two
1640       // extra. That should take care of it!
1641       unsigned NumExtras = TargetAlign / 4;
1642       SmallVector<unsigned, 2> Extras;
1643       while (NumExtras && !UnspilledCS1GPRs.empty()) {
1644         unsigned Reg = UnspilledCS1GPRs.back();
1645         UnspilledCS1GPRs.pop_back();
1646         if (!MRI.isReserved(Reg) &&
1647             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1648              Reg == ARM::LR)) {
1649           Extras.push_back(Reg);
1650           NumExtras--;
1651         }
1652       }
1653       // For non-Thumb1 functions, also check for hi-reg CS registers
1654       if (!AFI->isThumb1OnlyFunction()) {
1655         while (NumExtras && !UnspilledCS2GPRs.empty()) {
1656           unsigned Reg = UnspilledCS2GPRs.back();
1657           UnspilledCS2GPRs.pop_back();
1658           if (!MRI.isReserved(Reg)) {
1659             Extras.push_back(Reg);
1660             NumExtras--;
1661           }
1662         }
1663       }
1664       if (Extras.size() && NumExtras == 0) {
1665         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1666           MRI.setPhysRegUsed(Extras[i]);
1667         }
1668       } else if (!AFI->isThumb1OnlyFunction()) {
1669         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
1670         // closest to SP or frame pointer.
1671         const TargetRegisterClass *RC = &ARM::GPRRegClass;
1672         RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1673                                                            RC->getAlignment(),
1674                                                            false));
1675       }
1676     }
1677   }
1678
1679   if (ForceLRSpill) {
1680     MRI.setPhysRegUsed(ARM::LR);
1681     AFI->setLRIsSpilledForFarJump(true);
1682   }
1683 }
1684
1685
1686 void ARMFrameLowering::
1687 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1688                               MachineBasicBlock::iterator I) const {
1689   const ARMBaseInstrInfo &TII =
1690       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1691   if (!hasReservedCallFrame(MF)) {
1692     // If we have alloca, convert as follows:
1693     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1694     // ADJCALLSTACKUP   -> add, sp, sp, amount
1695     MachineInstr *Old = I;
1696     DebugLoc dl = Old->getDebugLoc();
1697     unsigned Amount = Old->getOperand(0).getImm();
1698     if (Amount != 0) {
1699       // We need to keep the stack aligned properly.  To do this, we round the
1700       // amount of space needed for the outgoing arguments up to the next
1701       // alignment boundary.
1702       unsigned Align = getStackAlignment();
1703       Amount = (Amount+Align-1)/Align*Align;
1704
1705       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1706       assert(!AFI->isThumb1OnlyFunction() &&
1707              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1708       bool isARM = !AFI->isThumbFunction();
1709
1710       // Replace the pseudo instruction with a new instruction...
1711       unsigned Opc = Old->getOpcode();
1712       int PIdx = Old->findFirstPredOperandIdx();
1713       ARMCC::CondCodes Pred = (PIdx == -1)
1714         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1715       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1716         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1717         unsigned PredReg = Old->getOperand(2).getReg();
1718         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1719                      Pred, PredReg);
1720       } else {
1721         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1722         unsigned PredReg = Old->getOperand(3).getReg();
1723         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1724         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1725                      Pred, PredReg);
1726       }
1727     }
1728   }
1729   MBB.erase(I);
1730 }
1731
1732 /// Get the minimum constant for ARM that is greater than or equal to the
1733 /// argument. In ARM, constants can have any value that can be produced by
1734 /// rotating an 8-bit value to the right by an even number of bits within a
1735 /// 32-bit word.
1736 static uint32_t alignToARMConstant(uint32_t Value) {
1737   unsigned Shifted = 0;
1738
1739   if (Value == 0)
1740       return 0;
1741
1742   while (!(Value & 0xC0000000)) {
1743       Value = Value << 2;
1744       Shifted += 2;
1745   }
1746
1747   bool Carry = (Value & 0x00FFFFFF);
1748   Value = ((Value & 0xFF000000) >> 24) + Carry;
1749
1750   if (Value & 0x0000100)
1751       Value = Value & 0x000001FC;
1752
1753   if (Shifted > 24)
1754       Value = Value >> (Shifted - 24);
1755   else
1756       Value = Value << (24 - Shifted);
1757
1758   return Value;
1759 }
1760
1761 // The stack limit in the TCB is set to this many bytes above the actual
1762 // stack limit.
1763 static const uint64_t kSplitStackAvailable = 256;
1764
1765 // Adjust the function prologue to enable split stacks. This currently only
1766 // supports android and linux.
1767 //
1768 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1769 // must be well defined in order to allow for consistent implementations of the
1770 // __morestack helper function. The ABI is also not a normal ABI in that it
1771 // doesn't follow the normal calling conventions because this allows the
1772 // prologue of each function to be optimized further.
1773 //
1774 // Currently, the ABI looks like (when calling __morestack)
1775 //
1776 //  * r4 holds the minimum stack size requested for this function call
1777 //  * r5 holds the stack size of the arguments to the function
1778 //  * the beginning of the function is 3 instructions after the call to
1779 //    __morestack
1780 //
1781 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1782 // place the arguments on to the new stack, and the 3-instruction knowledge to
1783 // jump directly to the body of the function when working on the new stack.
1784 //
1785 // An old (and possibly no longer compatible) implementation of __morestack for
1786 // ARM can be found at [1].
1787 //
1788 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1789 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1790   unsigned Opcode;
1791   unsigned CFIIndex;
1792   const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1793   bool Thumb = ST->isThumb();
1794
1795   // Sadly, this currently doesn't support varargs, platforms other than
1796   // android/linux. Note that thumb1/thumb2 are support for android/linux.
1797   if (MF.getFunction()->isVarArg())
1798     report_fatal_error("Segmented stacks do not support vararg functions.");
1799   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1800     report_fatal_error("Segmented stacks not supported on this platform.");
1801
1802   MachineBasicBlock &prologueMBB = MF.front();
1803   MachineFrameInfo *MFI = MF.getFrameInfo();
1804   MachineModuleInfo &MMI = MF.getMMI();
1805   MCContext &Context = MMI.getContext();
1806   const MCRegisterInfo *MRI = Context.getRegisterInfo();
1807   const ARMBaseInstrInfo &TII =
1808       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1809   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1810   DebugLoc DL;
1811
1812   uint64_t StackSize = MFI->getStackSize();
1813
1814   // Do not generate a prologue for functions with a stack of size zero
1815   if (StackSize == 0)
1816     return;
1817
1818   // Use R4 and R5 as scratch registers.
1819   // We save R4 and R5 before use and restore them before leaving the function.
1820   unsigned ScratchReg0 = ARM::R4;
1821   unsigned ScratchReg1 = ARM::R5;
1822   uint64_t AlignedStackSize;
1823
1824   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1825   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1826   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1827   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1828   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1829
1830   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1831                                           e = prologueMBB.livein_end();
1832        i != e; ++i) {
1833     AllocMBB->addLiveIn(*i);
1834     GetMBB->addLiveIn(*i);
1835     McrMBB->addLiveIn(*i);
1836     PrevStackMBB->addLiveIn(*i);
1837     PostStackMBB->addLiveIn(*i);
1838   }
1839
1840   MF.push_front(PostStackMBB);
1841   MF.push_front(AllocMBB);
1842   MF.push_front(GetMBB);
1843   MF.push_front(McrMBB);
1844   MF.push_front(PrevStackMBB);
1845
1846   // The required stack size that is aligned to ARM constant criterion.
1847   AlignedStackSize = alignToARMConstant(StackSize);
1848
1849   // When the frame size is less than 256 we just compare the stack
1850   // boundary directly to the value of the stack pointer, per gcc.
1851   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1852
1853   // We will use two of the callee save registers as scratch registers so we
1854   // need to save those registers onto the stack.
1855   // We will use SR0 to hold stack limit and SR1 to hold the stack size
1856   // requested and arguments for __morestack().
1857   // SR0: Scratch Register #0
1858   // SR1: Scratch Register #1
1859   // push {SR0, SR1}
1860   if (Thumb) {
1861     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1862         .addReg(ScratchReg0).addReg(ScratchReg1);
1863   } else {
1864     AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1865                    .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1866         .addReg(ScratchReg0).addReg(ScratchReg1);
1867   }
1868
1869   // Emit the relevant DWARF information about the change in stack pointer as
1870   // well as where to find both r4 and r5 (the callee-save registers)
1871   CFIIndex =
1872       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1873   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1874       .addCFIIndex(CFIIndex);
1875   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1876       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1877   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1878       .addCFIIndex(CFIIndex);
1879   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1880       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1881   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1882       .addCFIIndex(CFIIndex);
1883
1884   // mov SR1, sp
1885   if (Thumb) {
1886     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1887                       .addReg(ARM::SP));
1888   } else if (CompareStackPointer) {
1889     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1890                       .addReg(ARM::SP)).addReg(0);
1891   }
1892
1893   // sub SR1, sp, #StackSize
1894   if (!CompareStackPointer && Thumb) {
1895     AddDefaultPred(
1896         AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1897             .addReg(ScratchReg1).addImm(AlignedStackSize));
1898   } else if (!CompareStackPointer) {
1899     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1900                       .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1901   }
1902
1903   if (Thumb && ST->isThumb1Only()) {
1904     unsigned PCLabelId = ARMFI->createPICLabelUId();
1905     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1906         MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1907     MachineConstantPool *MCP = MF.getConstantPool();
1908     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1909
1910     // ldr SR0, [pc, offset(STACK_LIMIT)]
1911     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1912                       .addConstantPoolIndex(CPI));
1913
1914     // ldr SR0, [SR0]
1915     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1916                       .addReg(ScratchReg0).addImm(0));
1917   } else {
1918     // Get TLS base address from the coprocessor
1919     // mrc p15, #0, SR0, c13, c0, #3
1920     AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1921                      .addImm(15)
1922                      .addImm(0)
1923                      .addImm(13)
1924                      .addImm(0)
1925                      .addImm(3));
1926
1927     // Use the last tls slot on android and a private field of the TCP on linux.
1928     assert(ST->isTargetAndroid() || ST->isTargetLinux());
1929     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1930
1931     // Get the stack limit from the right offset
1932     // ldr SR0, [sr0, #4 * TlsOffset]
1933     AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1934                       .addReg(ScratchReg0).addImm(4 * TlsOffset));
1935   }
1936
1937   // Compare stack limit with stack size requested.
1938   // cmp SR0, SR1
1939   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1940   AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1941                     .addReg(ScratchReg0)
1942                     .addReg(ScratchReg1));
1943
1944   // This jump is taken if StackLimit < SP - stack required.
1945   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1946   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1947        .addImm(ARMCC::LO)
1948        .addReg(ARM::CPSR);
1949
1950
1951   // Calling __morestack(StackSize, Size of stack arguments).
1952   // __morestack knows that the stack size requested is in SR0(r4)
1953   // and amount size of stack arguments is in SR1(r5).
1954
1955   // Pass first argument for the __morestack by Scratch Register #0.
1956   //   The amount size of stack required
1957   if (Thumb) {
1958     AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1959                                         ScratchReg0)).addImm(AlignedStackSize));
1960   } else {
1961     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1962                       .addImm(AlignedStackSize)).addReg(0);
1963   }
1964   // Pass second argument for the __morestack by Scratch Register #1.
1965   //   The amount size of stack consumed to save function arguments.
1966   if (Thumb) {
1967     AddDefaultPred(
1968         AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1969             .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1970   } else {
1971     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1972                    .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1973                    .addReg(0);
1974   }
1975
1976   // push {lr} - Save return address of this function.
1977   if (Thumb) {
1978     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1979         .addReg(ARM::LR);
1980   } else {
1981     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1982                    .addReg(ARM::SP, RegState::Define)
1983                    .addReg(ARM::SP))
1984         .addReg(ARM::LR);
1985   }
1986
1987   // Emit the DWARF info about the change in stack as well as where to find the
1988   // previous link register
1989   CFIIndex =
1990       MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1991   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1992       .addCFIIndex(CFIIndex);
1993   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1994         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1995   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1996       .addCFIIndex(CFIIndex);
1997
1998   // Call __morestack().
1999   if (Thumb) {
2000     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2001         .addExternalSymbol("__morestack");
2002   } else {
2003     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2004         .addExternalSymbol("__morestack");
2005   }
2006
2007   // pop {lr} - Restore return address of this original function.
2008   if (Thumb) {
2009     if (ST->isThumb1Only()) {
2010       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2011                      .addReg(ScratchReg0);
2012       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2013                      .addReg(ScratchReg0));
2014     } else {
2015       AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2016                      .addReg(ARM::LR, RegState::Define)
2017                      .addReg(ARM::SP, RegState::Define)
2018                      .addReg(ARM::SP)
2019                      .addImm(4));
2020     }
2021   } else {
2022     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2023                    .addReg(ARM::SP, RegState::Define)
2024                    .addReg(ARM::SP))
2025       .addReg(ARM::LR);
2026   }
2027
2028   // Restore SR0 and SR1 in case of __morestack() was called.
2029   // __morestack() will skip PostStackMBB block so we need to restore
2030   // scratch registers from here.
2031   // pop {SR0, SR1}
2032   if (Thumb) {
2033     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2034       .addReg(ScratchReg0)
2035       .addReg(ScratchReg1);
2036   } else {
2037     AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2038                    .addReg(ARM::SP, RegState::Define)
2039                    .addReg(ARM::SP))
2040       .addReg(ScratchReg0)
2041       .addReg(ScratchReg1);
2042   }
2043
2044   // Update the CFA offset now that we've popped
2045   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2046   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2047       .addCFIIndex(CFIIndex);
2048
2049   // bx lr - Return from this function.
2050   Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2051   AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2052
2053   // Restore SR0 and SR1 in case of __morestack() was not called.
2054   // pop {SR0, SR1}
2055   if (Thumb) {
2056     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2057       .addReg(ScratchReg0)
2058       .addReg(ScratchReg1);
2059   } else {
2060     AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2061                    .addReg(ARM::SP, RegState::Define)
2062                    .addReg(ARM::SP))
2063       .addReg(ScratchReg0)
2064       .addReg(ScratchReg1);
2065   }
2066
2067   // Update the CFA offset now that we've popped
2068   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2069   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2070       .addCFIIndex(CFIIndex);
2071
2072   // Tell debuggers that r4 and r5 are now the same as they were in the
2073   // previous function, that they're the "Same Value".
2074   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2075       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2076   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2077       .addCFIIndex(CFIIndex);
2078   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2079       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2080   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2081       .addCFIIndex(CFIIndex);
2082
2083   // Organizing MBB lists
2084   PostStackMBB->addSuccessor(&prologueMBB);
2085
2086   AllocMBB->addSuccessor(PostStackMBB);
2087
2088   GetMBB->addSuccessor(PostStackMBB);
2089   GetMBB->addSuccessor(AllocMBB);
2090
2091   McrMBB->addSuccessor(GetMBB);
2092
2093   PrevStackMBB->addSuccessor(McrMBB);
2094
2095 #ifdef XDEBUG
2096   MF.verify();
2097 #endif
2098 }