4bb7cd34a919fe236c98b02a60ef838cb4d7c5de
[oota-llvm.git] / lib / Target / XCore / XCoreFrameLowering.cpp
1 //===-- XCoreFrameLowering.cpp - Frame info for XCore Target --------------===//
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 XCore frame information that doesn't fit anywhere else
11 // cleanly...
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "XCoreFrameLowering.h"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.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/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include <algorithm>    // std::sort
32
33 using namespace llvm;
34
35 static const unsigned FramePtr = XCore::R10;
36 static const int MaxImmU16 = (1<<16) - 1;
37
38 // helper functions. FIXME: Eliminate.
39 static inline bool isImmU6(unsigned val) {
40   return val < (1 << 6);
41 }
42
43 static inline bool isImmU16(unsigned val) {
44   return val < (1 << 16);
45 }
46
47 // Helper structure with compare function for handling stack slots.
48 namespace {
49 struct StackSlotInfo {
50   int FI;
51   int Offset;
52   unsigned Reg;
53   StackSlotInfo(int f, int o, int r) : FI(f), Offset(o), Reg(r){};
54 };
55 }  // end anonymous namespace
56
57 static bool CompareSSIOffset(const StackSlotInfo& a, const StackSlotInfo& b) {
58   return a.Offset < b.Offset;
59 }
60
61
62 static void EmitDefCfaRegister(MachineBasicBlock &MBB,
63                                MachineBasicBlock::iterator MBBI, DebugLoc dl,
64                                const TargetInstrInfo &TII,
65                                MachineModuleInfo *MMI, unsigned DRegNum) {
66   unsigned CFIIndex = MMI->addFrameInst(
67       MCCFIInstruction::createDefCfaRegister(nullptr, DRegNum));
68   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
69       .addCFIIndex(CFIIndex);
70 }
71
72 static void EmitDefCfaOffset(MachineBasicBlock &MBB,
73                              MachineBasicBlock::iterator MBBI, DebugLoc dl,
74                              const TargetInstrInfo &TII,
75                              MachineModuleInfo *MMI, int Offset) {
76   unsigned CFIIndex =
77       MMI->addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
78   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
79       .addCFIIndex(CFIIndex);
80 }
81
82 static void EmitCfiOffset(MachineBasicBlock &MBB,
83                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
84                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
85                           unsigned DRegNum, int Offset) {
86   unsigned CFIIndex = MMI->addFrameInst(
87       MCCFIInstruction::createOffset(nullptr, DRegNum, Offset));
88   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
89       .addCFIIndex(CFIIndex);
90 }
91
92 /// The SP register is moved in steps of 'MaxImmU16' towards the bottom of the
93 /// frame. During these steps, it may be necessary to spill registers.
94 /// IfNeededExtSP emits the necessary EXTSP instructions to move the SP only
95 /// as far as to make 'OffsetFromBottom' reachable using an STWSP_lru6.
96 /// \param OffsetFromTop the spill offset from the top of the frame.
97 /// \param [in,out] Adjusted the current SP offset from the top of the frame.
98 static void IfNeededExtSP(MachineBasicBlock &MBB,
99                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
100                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
101                           int OffsetFromTop, int &Adjusted, int FrameSize,
102                           bool emitFrameMoves) {
103   while (OffsetFromTop > Adjusted) {
104     assert(Adjusted < FrameSize && "OffsetFromTop is beyond FrameSize");
105     int remaining = FrameSize - Adjusted;
106     int OpImm = (remaining > MaxImmU16) ? MaxImmU16 : remaining;
107     int Opcode = isImmU6(OpImm) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
108     BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(OpImm);
109     Adjusted += OpImm;
110     if (emitFrameMoves)
111       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
112   }
113 }
114
115 /// The SP register is moved in steps of 'MaxImmU16' towards the top of the
116 /// frame. During these steps, it may be necessary to re-load registers.
117 /// IfNeededLDAWSP emits the necessary LDAWSP instructions to move the SP only
118 /// as far as to make 'OffsetFromTop' reachable using an LDAWSP_lru6.
119 /// \param OffsetFromTop the spill offset from the top of the frame.
120 /// \param [in,out] RemainingAdj the current SP offset from the top of the
121 /// frame.
122 static void IfNeededLDAWSP(MachineBasicBlock &MBB,
123                            MachineBasicBlock::iterator MBBI, DebugLoc dl,
124                            const TargetInstrInfo &TII, int OffsetFromTop,
125                            int &RemainingAdj) {
126   while (OffsetFromTop < RemainingAdj - MaxImmU16) {
127     assert(RemainingAdj && "OffsetFromTop is beyond FrameSize");
128     int OpImm = (RemainingAdj > MaxImmU16) ? MaxImmU16 : RemainingAdj;
129     int Opcode = isImmU6(OpImm) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
130     BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(OpImm);
131     RemainingAdj -= OpImm;
132   }
133 }
134
135 /// Creates an ordered list of registers that are spilled
136 /// during the emitPrologue/emitEpilogue.
137 /// Registers are ordered according to their frame offset.
138 /// As offsets are negative, the largest offsets will be first.
139 static void GetSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
140                          MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
141                          bool fetchLR, bool fetchFP) {
142   if (fetchLR) {
143     int Offset = MFI->getObjectOffset(XFI->getLRSpillSlot());
144     SpillList.push_back(StackSlotInfo(XFI->getLRSpillSlot(),
145                                       Offset,
146                                       XCore::LR));
147   }
148   if (fetchFP) {
149     int Offset = MFI->getObjectOffset(XFI->getFPSpillSlot());
150     SpillList.push_back(StackSlotInfo(XFI->getFPSpillSlot(),
151                                       Offset,
152                                       FramePtr));
153   }
154   std::sort(SpillList.begin(), SpillList.end(), CompareSSIOffset);
155 }
156
157 /// Creates an ordered list of EH info register 'spills'.
158 /// These slots are only used by the unwinder and calls to llvm.eh.return().
159 /// Registers are ordered according to their frame offset.
160 /// As offsets are negative, the largest offsets will be first.
161 static void GetEHSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
162                            MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
163                            const TargetLowering *TL) {
164   assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
165   const int* EHSlot = XFI->getEHSpillSlot();
166   SpillList.push_back(StackSlotInfo(EHSlot[0],
167                                     MFI->getObjectOffset(EHSlot[0]),
168                                     TL->getExceptionPointerRegister()));
169   SpillList.push_back(StackSlotInfo(EHSlot[0],
170                                     MFI->getObjectOffset(EHSlot[1]),
171                                     TL->getExceptionSelectorRegister()));
172   std::sort(SpillList.begin(), SpillList.end(), CompareSSIOffset);
173 }
174
175
176 static MachineMemOperand *
177 getFrameIndexMMO(MachineBasicBlock &MBB, int FrameIndex, unsigned flags) {
178   MachineFunction *MF = MBB.getParent();
179   const MachineFrameInfo &MFI = *MF->getFrameInfo();
180   MachineMemOperand *MMO =
181     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex),
182                              flags, MFI.getObjectSize(FrameIndex),
183                              MFI.getObjectAlignment(FrameIndex));
184   return MMO;
185 }
186
187
188 /// Restore clobbered registers with their spill slot value.
189 /// The SP will be adjusted at the same time, thus the SpillList must be ordered
190 /// with the largest (negative) offsets first.
191 static void
192 RestoreSpillList(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
193                  DebugLoc dl, const TargetInstrInfo &TII, int &RemainingAdj,
194                  SmallVectorImpl<StackSlotInfo> &SpillList) {
195   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
196     assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
197     assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
198     int OffsetFromTop = - SpillList[i].Offset/4;
199     IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
200     int Offset = RemainingAdj - OffsetFromTop;
201     int Opcode = isImmU6(Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
202     BuildMI(MBB, MBBI, dl, TII.get(Opcode), SpillList[i].Reg)
203       .addImm(Offset)
204       .addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
205                                       MachineMemOperand::MOLoad));
206   }
207 }
208
209 //===----------------------------------------------------------------------===//
210 // XCoreFrameLowering:
211 //===----------------------------------------------------------------------===//
212
213 XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
214   : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 4, 0) {
215   // Do nothing
216 }
217
218 bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
219   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
220          MF.getFrameInfo()->hasVarSizedObjects();
221 }
222
223 void XCoreFrameLowering::emitPrologue(MachineFunction &MF) const {
224   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
225   MachineBasicBlock::iterator MBBI = MBB.begin();
226   MachineFrameInfo *MFI = MF.getFrameInfo();
227   MachineModuleInfo *MMI = &MF.getMMI();
228   const MCRegisterInfo *MRI = MMI->getContext().getRegisterInfo();
229   const XCoreInstrInfo &TII =
230       *static_cast<const XCoreInstrInfo *>(
231           MF.getTarget().getSubtargetImpl()->getInstrInfo());
232   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
233   // Debug location must be unknown since the first debug location is used
234   // to determine the end of the prologue.
235   DebugLoc dl;
236
237   if (MFI->getMaxAlignment() > getStackAlignment())
238     report_fatal_error("emitPrologue unsupported alignment: "
239                        + Twine(MFI->getMaxAlignment()));
240
241   const AttributeSet &PAL = MF.getFunction()->getAttributes();
242   if (PAL.hasAttrSomewhere(Attribute::Nest))
243     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDWSP_ru6), XCore::R11).addImm(0);
244     // FIX: Needs addMemOperand() but can't use getFixedStack() or getStack().
245
246   // Work out frame sizes.
247   // We will adjust the SP in stages towards the final FrameSize.
248   assert(MFI->getStackSize()%4 == 0 && "Misaligned frame size");
249   const int FrameSize = MFI->getStackSize() / 4;
250   int Adjusted = 0;
251
252   bool saveLR = XFI->hasLRSpillSlot();
253   bool UseENTSP = saveLR && FrameSize
254                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
255   if (UseENTSP)
256     saveLR = false;
257   bool FP = hasFP(MF);
258   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
259
260   if (UseENTSP) {
261     // Allocate space on the stack at the same time as saving LR.
262     Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
263     int Opcode = isImmU6(Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
264     MBB.addLiveIn(XCore::LR);
265     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode));
266     MIB.addImm(Adjusted);
267     MIB->addRegisterKilled(
268         XCore::LR, MF.getTarget().getSubtargetImpl()->getRegisterInfo(), true);
269     if (emitFrameMoves) {
270       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
271       unsigned DRegNum = MRI->getDwarfRegNum(XCore::LR, true);
272       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, 0);
273     }
274   }
275
276   // If necessary, save LR and FP to the stack, as we EXTSP.
277   SmallVector<StackSlotInfo,2> SpillList;
278   GetSpillList(SpillList, MFI, XFI, saveLR, FP);
279   // We want the nearest (negative) offsets first, so reverse list.
280   std::reverse(SpillList.begin(), SpillList.end());
281   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
282     assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
283     assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
284     int OffsetFromTop = - SpillList[i].Offset/4;
285     IfNeededExtSP(MBB, MBBI, dl, TII, MMI, OffsetFromTop, Adjusted, FrameSize,
286                   emitFrameMoves);
287     int Offset = Adjusted - OffsetFromTop;
288     int Opcode = isImmU6(Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
289     MBB.addLiveIn(SpillList[i].Reg);
290     BuildMI(MBB, MBBI, dl, TII.get(Opcode))
291       .addReg(SpillList[i].Reg, RegState::Kill)
292       .addImm(Offset)
293       .addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
294                                       MachineMemOperand::MOStore));
295     if (emitFrameMoves) {
296       unsigned DRegNum = MRI->getDwarfRegNum(SpillList[i].Reg, true);
297       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, SpillList[i].Offset);
298     }
299   }
300
301   // Complete any remaining Stack adjustment.
302   IfNeededExtSP(MBB, MBBI, dl, TII, MMI, FrameSize, Adjusted, FrameSize,
303                 emitFrameMoves);
304   assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
305
306   if (FP) {
307     // Set the FP from the SP.
308     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr).addImm(0);
309     if (emitFrameMoves)
310       EmitDefCfaRegister(MBB, MBBI, dl, TII, MMI,
311                          MRI->getDwarfRegNum(FramePtr, true));
312   }
313
314   if (emitFrameMoves) {
315     // Frame moves for callee saved.
316     auto SpillLabels = XFI->getSpillLabels();
317     for (unsigned I = 0, E = SpillLabels.size(); I != E; ++I) {
318       MachineBasicBlock::iterator Pos = SpillLabels[I].first;
319       ++Pos;
320       CalleeSavedInfo &CSI = SpillLabels[I].second;
321       int Offset = MFI->getObjectOffset(CSI.getFrameIdx());
322       unsigned DRegNum = MRI->getDwarfRegNum(CSI.getReg(), true);
323       EmitCfiOffset(MBB, Pos, dl, TII, MMI, DRegNum, Offset);
324     }
325     if (XFI->hasEHSpillSlot()) {
326       // The unwinder requires stack slot & CFI offsets for the exception info.
327       // We do not save/spill these registers.
328       SmallVector<StackSlotInfo,2> SpillList;
329       GetEHSpillList(SpillList, MFI, XFI,
330                      MF.getTarget().getSubtargetImpl()->getTargetLowering());
331       assert(SpillList.size()==2 && "Unexpected SpillList size");
332       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
333                     MRI->getDwarfRegNum(SpillList[0].Reg, true),
334                     SpillList[0].Offset);
335       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
336                     MRI->getDwarfRegNum(SpillList[1].Reg, true),
337                     SpillList[1].Offset);
338     }
339   }
340 }
341
342 void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
343                                      MachineBasicBlock &MBB) const {
344   MachineFrameInfo *MFI = MF.getFrameInfo();
345   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
346   const XCoreInstrInfo &TII =
347       *static_cast<const XCoreInstrInfo *>(
348           MF.getTarget().getSubtargetImpl()->getInstrInfo());
349   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
350   DebugLoc dl = MBBI->getDebugLoc();
351   unsigned RetOpcode = MBBI->getOpcode();
352
353   // Work out frame sizes.
354   // We will adjust the SP in stages towards the final FrameSize.
355   int RemainingAdj = MFI->getStackSize();
356   assert(RemainingAdj%4 == 0 && "Misaligned frame size");
357   RemainingAdj /= 4;
358
359   if (RetOpcode == XCore::EH_RETURN) {
360     // 'Restore' the exception info the unwinder has placed into the stack
361     // slots.
362     SmallVector<StackSlotInfo,2> SpillList;
363     GetEHSpillList(SpillList, MFI, XFI,
364                    MF.getTarget().getSubtargetImpl()->getTargetLowering());
365     RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
366
367     // Return to the landing pad.
368     unsigned EhStackReg = MBBI->getOperand(0).getReg();
369     unsigned EhHandlerReg = MBBI->getOperand(1).getReg();
370     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(EhStackReg);
371     BuildMI(MBB, MBBI, dl, TII.get(XCore::BAU_1r)).addReg(EhHandlerReg);
372     MBB.erase(MBBI);  // Erase the previous return instruction.
373     return;
374   }
375
376   bool restoreLR = XFI->hasLRSpillSlot();
377   bool UseRETSP = restoreLR && RemainingAdj
378                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
379   if (UseRETSP)
380     restoreLR = false;
381   bool FP = hasFP(MF);
382
383   if (FP) // Restore the stack pointer.
384     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(FramePtr);
385
386   // If necessary, restore LR and FP from the stack, as we EXTSP.
387   SmallVector<StackSlotInfo,2> SpillList;
388   GetSpillList(SpillList, MFI, XFI, restoreLR, FP);
389   RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
390
391   if (RemainingAdj) {
392     // Complete all but one of the remaining Stack adjustments.
393     IfNeededLDAWSP(MBB, MBBI, dl, TII, 0, RemainingAdj);
394     if (UseRETSP) {
395       // Fold prologue into return instruction
396       assert(RetOpcode == XCore::RETSP_u6
397              || RetOpcode == XCore::RETSP_lu6);
398       int Opcode = isImmU6(RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
399       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode))
400                                   .addImm(RemainingAdj);
401       for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
402         MIB->addOperand(MBBI->getOperand(i)); // copy any variadic operands
403       MBB.erase(MBBI);  // Erase the previous return instruction.
404     } else {
405       int Opcode = isImmU6(RemainingAdj) ? XCore::LDAWSP_ru6 :
406                                            XCore::LDAWSP_lru6;
407       BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(RemainingAdj);
408       // Don't erase the return instruction.
409     }
410   } // else Don't erase the return instruction.
411 }
412
413 bool XCoreFrameLowering::
414 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
415                           MachineBasicBlock::iterator MI,
416                           const std::vector<CalleeSavedInfo> &CSI,
417                           const TargetRegisterInfo *TRI) const {
418   if (CSI.empty())
419     return true;
420
421   MachineFunction *MF = MBB.getParent();
422   const TargetInstrInfo &TII =
423       *MF->getTarget().getSubtargetImpl()->getInstrInfo();
424   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
425   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
426
427   DebugLoc DL;
428   if (MI != MBB.end() && !MI->isDebugValue())
429     DL = MI->getDebugLoc();
430
431   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
432                                                     it != CSI.end(); ++it) {
433     unsigned Reg = it->getReg();
434     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
435            "LR & FP are always handled in emitPrologue");
436
437     // Add the callee-saved register as live-in. It's killed at the spill.
438     MBB.addLiveIn(Reg);
439     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
440     TII.storeRegToStackSlot(MBB, MI, Reg, true, it->getFrameIdx(), RC, TRI);
441     if (emitFrameMoves) {
442       auto Store = MI;
443       --Store;
444       XFI->getSpillLabels().push_back(std::make_pair(Store, *it));
445     }
446   }
447   return true;
448 }
449
450 bool XCoreFrameLowering::
451 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
452                             MachineBasicBlock::iterator MI,
453                             const std::vector<CalleeSavedInfo> &CSI,
454                             const TargetRegisterInfo *TRI) const{
455   MachineFunction *MF = MBB.getParent();
456   const TargetInstrInfo &TII =
457       *MF->getTarget().getSubtargetImpl()->getInstrInfo();
458   bool AtStart = MI == MBB.begin();
459   MachineBasicBlock::iterator BeforeI = MI;
460   if (!AtStart)
461     --BeforeI;
462   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
463                                                     it != CSI.end(); ++it) {
464     unsigned Reg = it->getReg();
465     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
466            "LR & FP are always handled in emitEpilogue");
467
468     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
469     TII.loadRegFromStackSlot(MBB, MI, Reg, it->getFrameIdx(), RC, TRI);
470     assert(MI != MBB.begin() &&
471            "loadRegFromStackSlot didn't insert any code!");
472     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
473     // instructions.
474     if (AtStart)
475       MI = MBB.begin();
476     else {
477       MI = BeforeI;
478       ++MI;
479     }
480   }
481   return true;
482 }
483
484 // This function eliminates ADJCALLSTACKDOWN,
485 // ADJCALLSTACKUP pseudo instructions
486 void XCoreFrameLowering::
487 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
488                               MachineBasicBlock::iterator I) const {
489   const XCoreInstrInfo &TII =
490       *static_cast<const XCoreInstrInfo *>(
491           MF.getTarget().getSubtargetImpl()->getInstrInfo());
492   if (!hasReservedCallFrame(MF)) {
493     // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
494     // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
495     MachineInstr *Old = I;
496     uint64_t Amount = Old->getOperand(0).getImm();
497     if (Amount != 0) {
498       // We need to keep the stack aligned properly.  To do this, we round the
499       // amount of space needed for the outgoing arguments up to the next
500       // alignment boundary.
501       unsigned Align = getStackAlignment();
502       Amount = (Amount+Align-1)/Align*Align;
503
504       assert(Amount%4 == 0);
505       Amount /= 4;
506
507       bool isU6 = isImmU6(Amount);
508       if (!isU6 && !isImmU16(Amount)) {
509         // FIX could emit multiple instructions in this case.
510 #ifndef NDEBUG
511         errs() << "eliminateCallFramePseudoInstr size too big: "
512                << Amount << "\n";
513 #endif
514         llvm_unreachable(nullptr);
515       }
516
517       MachineInstr *New;
518       if (Old->getOpcode() == XCore::ADJCALLSTACKDOWN) {
519         int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
520         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode))
521           .addImm(Amount);
522       } else {
523         assert(Old->getOpcode() == XCore::ADJCALLSTACKUP);
524         int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
525         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode), XCore::SP)
526           .addImm(Amount);
527       }
528
529       // Replace the pseudo instruction with a new instruction...
530       MBB.insert(I, New);
531     }
532   }
533
534   MBB.erase(I);
535 }
536
537 void XCoreFrameLowering::
538 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
539                                      RegScavenger *RS) const {
540   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
541
542   bool LRUsed = MF.getRegInfo().isPhysRegUsed(XCore::LR);
543
544   if (!LRUsed && !MF.getFunction()->isVarArg() &&
545       MF.getFrameInfo()->estimateStackSize(MF))
546     // If we need to extend the stack it is more efficient to use entsp / retsp.
547     // We force the LR to be saved so these instructions are used.
548     LRUsed = true;
549
550   if (MF.getMMI().callsUnwindInit() || MF.getMMI().callsEHReturn()) {
551     // The unwinder expects to find spill slots for the exception info regs R0
552     // & R1. These are used during llvm.eh.return() to 'restore' the exception
553     // info. N.B. we do not spill or restore R0, R1 during normal operation.
554     XFI->createEHSpillSlot(MF);
555     // As we will  have a stack, we force the LR to be saved.
556     LRUsed = true;
557   }
558
559   if (LRUsed) {
560     // We will handle the LR in the prologue/epilogue
561     // and allocate space on the stack ourselves.
562     MF.getRegInfo().setPhysRegUnused(XCore::LR);
563     XFI->createLRSpillSlot(MF);
564   }
565
566   if (hasFP(MF))
567     // A callee save register is used to hold the FP.
568     // This needs saving / restoring in the epilogue / prologue.
569     XFI->createFPSpillSlot(MF);
570 }
571
572 void XCoreFrameLowering::
573 processFunctionBeforeFrameFinalized(MachineFunction &MF,
574                                     RegScavenger *RS) const {
575   assert(RS && "requiresRegisterScavenging failed");
576   MachineFrameInfo *MFI = MF.getFrameInfo();
577   const TargetRegisterClass *RC = &XCore::GRRegsRegClass;
578   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
579   // Reserve slots close to SP or frame pointer for Scavenging spills.
580   // When using SP for small frames, we don't need any scratch registers.
581   // When using SP for large frames, we may need 2 scratch registers.
582   // When using FP, for large or small frames, we may need 1 scratch register.
583   if (XFI->isLargeFrame(MF) || hasFP(MF))
584     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
585                                                        RC->getAlignment(),
586                                                        false));
587   if (XFI->isLargeFrame(MF) && !hasFP(MF))
588     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
589                                                        RC->getAlignment(),
590                                                        false));
591 }