Have MachineFunction cache a pointer to the subtarget to make lookups
[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 *>(MF.getSubtarget().getInstrInfo());
231   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
232   // Debug location must be unknown since the first debug location is used
233   // to determine the end of the prologue.
234   DebugLoc dl;
235
236   if (MFI->getMaxAlignment() > getStackAlignment())
237     report_fatal_error("emitPrologue unsupported alignment: "
238                        + Twine(MFI->getMaxAlignment()));
239
240   const AttributeSet &PAL = MF.getFunction()->getAttributes();
241   if (PAL.hasAttrSomewhere(Attribute::Nest))
242     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDWSP_ru6), XCore::R11).addImm(0);
243     // FIX: Needs addMemOperand() but can't use getFixedStack() or getStack().
244
245   // Work out frame sizes.
246   // We will adjust the SP in stages towards the final FrameSize.
247   assert(MFI->getStackSize()%4 == 0 && "Misaligned frame size");
248   const int FrameSize = MFI->getStackSize() / 4;
249   int Adjusted = 0;
250
251   bool saveLR = XFI->hasLRSpillSlot();
252   bool UseENTSP = saveLR && FrameSize
253                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
254   if (UseENTSP)
255     saveLR = false;
256   bool FP = hasFP(MF);
257   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
258
259   if (UseENTSP) {
260     // Allocate space on the stack at the same time as saving LR.
261     Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
262     int Opcode = isImmU6(Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
263     MBB.addLiveIn(XCore::LR);
264     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode));
265     MIB.addImm(Adjusted);
266     MIB->addRegisterKilled(XCore::LR, MF.getSubtarget().getRegisterInfo(),
267                            true);
268     if (emitFrameMoves) {
269       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
270       unsigned DRegNum = MRI->getDwarfRegNum(XCore::LR, true);
271       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, 0);
272     }
273   }
274
275   // If necessary, save LR and FP to the stack, as we EXTSP.
276   SmallVector<StackSlotInfo,2> SpillList;
277   GetSpillList(SpillList, MFI, XFI, saveLR, FP);
278   // We want the nearest (negative) offsets first, so reverse list.
279   std::reverse(SpillList.begin(), SpillList.end());
280   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
281     assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
282     assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
283     int OffsetFromTop = - SpillList[i].Offset/4;
284     IfNeededExtSP(MBB, MBBI, dl, TII, MMI, OffsetFromTop, Adjusted, FrameSize,
285                   emitFrameMoves);
286     int Offset = Adjusted - OffsetFromTop;
287     int Opcode = isImmU6(Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
288     MBB.addLiveIn(SpillList[i].Reg);
289     BuildMI(MBB, MBBI, dl, TII.get(Opcode))
290       .addReg(SpillList[i].Reg, RegState::Kill)
291       .addImm(Offset)
292       .addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
293                                       MachineMemOperand::MOStore));
294     if (emitFrameMoves) {
295       unsigned DRegNum = MRI->getDwarfRegNum(SpillList[i].Reg, true);
296       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, SpillList[i].Offset);
297     }
298   }
299
300   // Complete any remaining Stack adjustment.
301   IfNeededExtSP(MBB, MBBI, dl, TII, MMI, FrameSize, Adjusted, FrameSize,
302                 emitFrameMoves);
303   assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
304
305   if (FP) {
306     // Set the FP from the SP.
307     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr).addImm(0);
308     if (emitFrameMoves)
309       EmitDefCfaRegister(MBB, MBBI, dl, TII, MMI,
310                          MRI->getDwarfRegNum(FramePtr, true));
311   }
312
313   if (emitFrameMoves) {
314     // Frame moves for callee saved.
315     auto SpillLabels = XFI->getSpillLabels();
316     for (unsigned I = 0, E = SpillLabels.size(); I != E; ++I) {
317       MachineBasicBlock::iterator Pos = SpillLabels[I].first;
318       ++Pos;
319       CalleeSavedInfo &CSI = SpillLabels[I].second;
320       int Offset = MFI->getObjectOffset(CSI.getFrameIdx());
321       unsigned DRegNum = MRI->getDwarfRegNum(CSI.getReg(), true);
322       EmitCfiOffset(MBB, Pos, dl, TII, MMI, DRegNum, Offset);
323     }
324     if (XFI->hasEHSpillSlot()) {
325       // The unwinder requires stack slot & CFI offsets for the exception info.
326       // We do not save/spill these registers.
327       SmallVector<StackSlotInfo,2> SpillList;
328       GetEHSpillList(SpillList, MFI, XFI,
329                      MF.getSubtarget().getTargetLowering());
330       assert(SpillList.size()==2 && "Unexpected SpillList size");
331       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
332                     MRI->getDwarfRegNum(SpillList[0].Reg, true),
333                     SpillList[0].Offset);
334       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
335                     MRI->getDwarfRegNum(SpillList[1].Reg, true),
336                     SpillList[1].Offset);
337     }
338   }
339 }
340
341 void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
342                                      MachineBasicBlock &MBB) const {
343   MachineFrameInfo *MFI = MF.getFrameInfo();
344   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
345   const XCoreInstrInfo &TII =
346       *static_cast<const XCoreInstrInfo *>(MF.getSubtarget().getInstrInfo());
347   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
348   DebugLoc dl = MBBI->getDebugLoc();
349   unsigned RetOpcode = MBBI->getOpcode();
350
351   // Work out frame sizes.
352   // We will adjust the SP in stages towards the final FrameSize.
353   int RemainingAdj = MFI->getStackSize();
354   assert(RemainingAdj%4 == 0 && "Misaligned frame size");
355   RemainingAdj /= 4;
356
357   if (RetOpcode == XCore::EH_RETURN) {
358     // 'Restore' the exception info the unwinder has placed into the stack
359     // slots.
360     SmallVector<StackSlotInfo,2> SpillList;
361     GetEHSpillList(SpillList, MFI, XFI, MF.getSubtarget().getTargetLowering());
362     RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
363
364     // Return to the landing pad.
365     unsigned EhStackReg = MBBI->getOperand(0).getReg();
366     unsigned EhHandlerReg = MBBI->getOperand(1).getReg();
367     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(EhStackReg);
368     BuildMI(MBB, MBBI, dl, TII.get(XCore::BAU_1r)).addReg(EhHandlerReg);
369     MBB.erase(MBBI);  // Erase the previous return instruction.
370     return;
371   }
372
373   bool restoreLR = XFI->hasLRSpillSlot();
374   bool UseRETSP = restoreLR && RemainingAdj
375                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
376   if (UseRETSP)
377     restoreLR = false;
378   bool FP = hasFP(MF);
379
380   if (FP) // Restore the stack pointer.
381     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(FramePtr);
382
383   // If necessary, restore LR and FP from the stack, as we EXTSP.
384   SmallVector<StackSlotInfo,2> SpillList;
385   GetSpillList(SpillList, MFI, XFI, restoreLR, FP);
386   RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
387
388   if (RemainingAdj) {
389     // Complete all but one of the remaining Stack adjustments.
390     IfNeededLDAWSP(MBB, MBBI, dl, TII, 0, RemainingAdj);
391     if (UseRETSP) {
392       // Fold prologue into return instruction
393       assert(RetOpcode == XCore::RETSP_u6
394              || RetOpcode == XCore::RETSP_lu6);
395       int Opcode = isImmU6(RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
396       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode))
397                                   .addImm(RemainingAdj);
398       for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
399         MIB->addOperand(MBBI->getOperand(i)); // copy any variadic operands
400       MBB.erase(MBBI);  // Erase the previous return instruction.
401     } else {
402       int Opcode = isImmU6(RemainingAdj) ? XCore::LDAWSP_ru6 :
403                                            XCore::LDAWSP_lru6;
404       BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(RemainingAdj);
405       // Don't erase the return instruction.
406     }
407   } // else Don't erase the return instruction.
408 }
409
410 bool XCoreFrameLowering::
411 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
412                           MachineBasicBlock::iterator MI,
413                           const std::vector<CalleeSavedInfo> &CSI,
414                           const TargetRegisterInfo *TRI) const {
415   if (CSI.empty())
416     return true;
417
418   MachineFunction *MF = MBB.getParent();
419   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
420   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
421   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
422
423   DebugLoc DL;
424   if (MI != MBB.end() && !MI->isDebugValue())
425     DL = MI->getDebugLoc();
426
427   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
428                                                     it != CSI.end(); ++it) {
429     unsigned Reg = it->getReg();
430     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
431            "LR & FP are always handled in emitPrologue");
432
433     // Add the callee-saved register as live-in. It's killed at the spill.
434     MBB.addLiveIn(Reg);
435     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
436     TII.storeRegToStackSlot(MBB, MI, Reg, true, it->getFrameIdx(), RC, TRI);
437     if (emitFrameMoves) {
438       auto Store = MI;
439       --Store;
440       XFI->getSpillLabels().push_back(std::make_pair(Store, *it));
441     }
442   }
443   return true;
444 }
445
446 bool XCoreFrameLowering::
447 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
448                             MachineBasicBlock::iterator MI,
449                             const std::vector<CalleeSavedInfo> &CSI,
450                             const TargetRegisterInfo *TRI) const{
451   MachineFunction *MF = MBB.getParent();
452   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
453   bool AtStart = MI == MBB.begin();
454   MachineBasicBlock::iterator BeforeI = MI;
455   if (!AtStart)
456     --BeforeI;
457   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
458                                                     it != CSI.end(); ++it) {
459     unsigned Reg = it->getReg();
460     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
461            "LR & FP are always handled in emitEpilogue");
462
463     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
464     TII.loadRegFromStackSlot(MBB, MI, Reg, it->getFrameIdx(), RC, TRI);
465     assert(MI != MBB.begin() &&
466            "loadRegFromStackSlot didn't insert any code!");
467     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
468     // instructions.
469     if (AtStart)
470       MI = MBB.begin();
471     else {
472       MI = BeforeI;
473       ++MI;
474     }
475   }
476   return true;
477 }
478
479 // This function eliminates ADJCALLSTACKDOWN,
480 // ADJCALLSTACKUP pseudo instructions
481 void XCoreFrameLowering::
482 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
483                               MachineBasicBlock::iterator I) const {
484   const XCoreInstrInfo &TII =
485       *static_cast<const XCoreInstrInfo *>(MF.getSubtarget().getInstrInfo());
486   if (!hasReservedCallFrame(MF)) {
487     // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
488     // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
489     MachineInstr *Old = I;
490     uint64_t Amount = Old->getOperand(0).getImm();
491     if (Amount != 0) {
492       // We need to keep the stack aligned properly.  To do this, we round the
493       // amount of space needed for the outgoing arguments up to the next
494       // alignment boundary.
495       unsigned Align = getStackAlignment();
496       Amount = (Amount+Align-1)/Align*Align;
497
498       assert(Amount%4 == 0);
499       Amount /= 4;
500
501       bool isU6 = isImmU6(Amount);
502       if (!isU6 && !isImmU16(Amount)) {
503         // FIX could emit multiple instructions in this case.
504 #ifndef NDEBUG
505         errs() << "eliminateCallFramePseudoInstr size too big: "
506                << Amount << "\n";
507 #endif
508         llvm_unreachable(nullptr);
509       }
510
511       MachineInstr *New;
512       if (Old->getOpcode() == XCore::ADJCALLSTACKDOWN) {
513         int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
514         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode))
515           .addImm(Amount);
516       } else {
517         assert(Old->getOpcode() == XCore::ADJCALLSTACKUP);
518         int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
519         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode), XCore::SP)
520           .addImm(Amount);
521       }
522
523       // Replace the pseudo instruction with a new instruction...
524       MBB.insert(I, New);
525     }
526   }
527
528   MBB.erase(I);
529 }
530
531 void XCoreFrameLowering::
532 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
533                                      RegScavenger *RS) const {
534   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
535
536   bool LRUsed = MF.getRegInfo().isPhysRegUsed(XCore::LR);
537
538   if (!LRUsed && !MF.getFunction()->isVarArg() &&
539       MF.getFrameInfo()->estimateStackSize(MF))
540     // If we need to extend the stack it is more efficient to use entsp / retsp.
541     // We force the LR to be saved so these instructions are used.
542     LRUsed = true;
543
544   if (MF.getMMI().callsUnwindInit() || MF.getMMI().callsEHReturn()) {
545     // The unwinder expects to find spill slots for the exception info regs R0
546     // & R1. These are used during llvm.eh.return() to 'restore' the exception
547     // info. N.B. we do not spill or restore R0, R1 during normal operation.
548     XFI->createEHSpillSlot(MF);
549     // As we will  have a stack, we force the LR to be saved.
550     LRUsed = true;
551   }
552
553   if (LRUsed) {
554     // We will handle the LR in the prologue/epilogue
555     // and allocate space on the stack ourselves.
556     MF.getRegInfo().setPhysRegUnused(XCore::LR);
557     XFI->createLRSpillSlot(MF);
558   }
559
560   if (hasFP(MF))
561     // A callee save register is used to hold the FP.
562     // This needs saving / restoring in the epilogue / prologue.
563     XFI->createFPSpillSlot(MF);
564 }
565
566 void XCoreFrameLowering::
567 processFunctionBeforeFrameFinalized(MachineFunction &MF,
568                                     RegScavenger *RS) const {
569   assert(RS && "requiresRegisterScavenging failed");
570   MachineFrameInfo *MFI = MF.getFrameInfo();
571   const TargetRegisterClass *RC = &XCore::GRRegsRegClass;
572   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
573   // Reserve slots close to SP or frame pointer for Scavenging spills.
574   // When using SP for small frames, we don't need any scratch registers.
575   // When using SP for large frames, we may need 2 scratch registers.
576   // When using FP, for large or small frames, we may need 1 scratch register.
577   if (XFI->isLargeFrame(MF) || hasFP(MF))
578     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
579                                                        RC->getAlignment(),
580                                                        false));
581   if (XFI->isLargeFrame(MF) && !hasFP(MF))
582     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
583                                                        RC->getAlignment(),
584                                                        false));
585 }