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