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