1//===-- XCoreFrameLowering.cpp - Frame info for XCore Target --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains XCore frame information that doesn't fit anywhere else
10// cleanly...
11//
12//===----------------------------------------------------------------------===//
13
14#include "XCoreFrameLowering.h"
15#include "XCoreInstrInfo.h"
16#include "XCoreMachineFunctionInfo.h"
17#include "XCoreSubtarget.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/RegisterScavenging.h"
24#include "llvm/CodeGen/TargetLowering.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Support/ErrorHandling.h"
28#include <algorithm>
29
30using namespace llvm;
31
32static const unsigned FramePtr = XCore::R10;
33static const int MaxImmU16 = (1<<16) - 1;
34
35// helper functions. FIXME: Eliminate.
36static inline bool isImmU6(unsigned val) {
37 return val < (1 << 6);
38}
39
40static inline bool isImmU16(unsigned val) {
41 return val < (1 << 16);
42}
43
44// Helper structure with compare function for handling stack slots.
45namespace {
46struct StackSlotInfo {
47 int FI;
48 int Offset;
49 unsigned Reg;
50 StackSlotInfo(int f, int o, int r) : FI(f), Offset(o), Reg(r){};
51};
52} // end anonymous namespace
53
54static bool CompareSSIOffset(const StackSlotInfo& a, const StackSlotInfo& b) {
55 return a.Offset < b.Offset;
56}
57
58static void EmitDefCfaRegister(MachineBasicBlock &MBB,
59 MachineBasicBlock::iterator MBBI,
60 const DebugLoc &dl, const TargetInstrInfo &TII,
61 MachineFunction &MF, unsigned DRegNum) {
62 unsigned CFIIndex = MF.addFrameInst(
63 Inst: MCCFIInstruction::createDefCfaRegister(L: nullptr, Register: DRegNum));
64 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
65 .addCFIIndex(CFIIndex);
66}
67
68static void EmitDefCfaOffset(MachineBasicBlock &MBB,
69 MachineBasicBlock::iterator MBBI,
70 const DebugLoc &dl, const TargetInstrInfo &TII,
71 int Offset) {
72 MachineFunction &MF = *MBB.getParent();
73 unsigned CFIIndex =
74 MF.addFrameInst(Inst: MCCFIInstruction::cfiDefCfaOffset(L: nullptr, Offset));
75 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
76 .addCFIIndex(CFIIndex);
77}
78
79static void EmitCfiOffset(MachineBasicBlock &MBB,
80 MachineBasicBlock::iterator MBBI, const DebugLoc &dl,
81 const TargetInstrInfo &TII, unsigned DRegNum,
82 int Offset) {
83 MachineFunction &MF = *MBB.getParent();
84 unsigned CFIIndex = MF.addFrameInst(
85 Inst: MCCFIInstruction::createOffset(L: nullptr, Register: DRegNum, Offset));
86 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
87 .addCFIIndex(CFIIndex);
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.
96static void IfNeededExtSP(MachineBasicBlock &MBB,
97 MachineBasicBlock::iterator MBBI, const DebugLoc &dl,
98 const TargetInstrInfo &TII, int OffsetFromTop,
99 int &Adjusted, int FrameSize, bool emitFrameMoves) {
100 while (OffsetFromTop > Adjusted) {
101 assert(Adjusted < FrameSize && "OffsetFromTop is beyond FrameSize");
102 int remaining = FrameSize - Adjusted;
103 int OpImm = (remaining > MaxImmU16) ? MaxImmU16 : remaining;
104 int Opcode = isImmU6(val: OpImm) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
105 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode)).addImm(Val: OpImm);
106 Adjusted += OpImm;
107 if (emitFrameMoves)
108 EmitDefCfaOffset(MBB, MBBI, dl, TII, Offset: Adjusted*4);
109 }
110}
111
112/// The SP register is moved in steps of 'MaxImmU16' towards the top of the
113/// frame. During these steps, it may be necessary to re-load registers.
114/// IfNeededLDAWSP emits the necessary LDAWSP instructions to move the SP only
115/// as far as to make 'OffsetFromTop' reachable using an LDAWSP_lru6.
116/// \param OffsetFromTop the spill offset from the top of the frame.
117/// \param [in,out] RemainingAdj the current SP offset from the top of the
118/// frame.
119static void IfNeededLDAWSP(MachineBasicBlock &MBB,
120 MachineBasicBlock::iterator MBBI, const 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(val: OpImm) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
127 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode), DestReg: XCore::SP).addImm(Val: 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.
136static void GetSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
137 MachineFrameInfo &MFI, XCoreFunctionInfo *XFI,
138 bool fetchLR, bool fetchFP) {
139 if (fetchLR) {
140 int Offset = MFI.getObjectOffset(ObjectIdx: XFI->getLRSpillSlot());
141 SpillList.push_back(Elt: StackSlotInfo(XFI->getLRSpillSlot(),
142 Offset,
143 XCore::LR));
144 }
145 if (fetchFP) {
146 int Offset = MFI.getObjectOffset(ObjectIdx: XFI->getFPSpillSlot());
147 SpillList.push_back(Elt: StackSlotInfo(XFI->getFPSpillSlot(),
148 Offset,
149 FramePtr));
150 }
151 llvm::sort(C&: SpillList, Comp: 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.
158static void GetEHSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
159 MachineFrameInfo &MFI, XCoreFunctionInfo *XFI,
160 const Module &M, const Constant *PersonalityFn,
161 const TargetLowering *TL) {
162 assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
163 const int *EHSlot = XFI->getEHSpillSlot();
164 // Prefer the "exception-model" module flag, else the TargetOptions default.
165 ExceptionHandling EH = M.getExceptionModel();
166 if (EH == ExceptionHandling::Default)
167 EH = TL->getTargetMachine().getExceptionModel();
168 SpillList.push_back(
169 Elt: StackSlotInfo(EHSlot[0], MFI.getObjectOffset(ObjectIdx: EHSlot[0]),
170 TL->getExceptionPointerRegister(EH, PersonalityFn)));
171 SpillList.push_back(
172 Elt: StackSlotInfo(EHSlot[0], MFI.getObjectOffset(ObjectIdx: EHSlot[1]),
173 TL->getExceptionSelectorRegister(EH, PersonalityFn)));
174 llvm::sort(C&: SpillList, Comp: CompareSSIOffset);
175}
176
177static MachineMemOperand *getFrameIndexMMO(MachineBasicBlock &MBB,
178 int FrameIndex,
179 MachineMemOperand::Flags flags) {
180 MachineFunction *MF = MBB.getParent();
181 const MachineFrameInfo &MFI = MF->getFrameInfo();
182 MachineMemOperand *MMO = MF->getMachineMemOperand(
183 PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI: FrameIndex), F: flags,
184 Size: MFI.getObjectSize(ObjectIdx: FrameIndex), BaseAlignment: MFI.getObjectAlign(ObjectIdx: FrameIndex));
185 return MMO;
186}
187
188
189/// Restore clobbered registers with their spill slot value.
190/// The SP will be adjusted at the same time, thus the SpillList must be ordered
191/// with the largest (negative) offsets first.
192static void RestoreSpillList(MachineBasicBlock &MBB,
193 MachineBasicBlock::iterator MBBI,
194 const DebugLoc &dl, const TargetInstrInfo &TII,
195 int &RemainingAdj,
196 SmallVectorImpl<StackSlotInfo> &SpillList) {
197 for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
198 assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
199 assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
200 int OffsetFromTop = - SpillList[i].Offset/4;
201 IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
202 int Offset = RemainingAdj - OffsetFromTop;
203 int Opcode = isImmU6(val: Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
204 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode), DestReg: SpillList[i].Reg)
205 .addImm(Val: Offset)
206 .addMemOperand(MMO: getFrameIndexMMO(MBB, FrameIndex: SpillList[i].FI,
207 flags: MachineMemOperand::MOLoad));
208 }
209}
210
211//===----------------------------------------------------------------------===//
212// XCoreFrameLowering:
213//===----------------------------------------------------------------------===//
214
215XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
216 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(4), 0) {
217 // Do nothing
218}
219
220bool XCoreFrameLowering::hasFPImpl(const MachineFunction &MF) const {
221 return MF.disableFramePointerElim() || MF.getFrameInfo().hasVarSizedObjects();
222}
223
224void XCoreFrameLowering::emitPrologue(MachineFunction &MF,
225 MachineBasicBlock &MBB) const {
226 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
227 MachineBasicBlock::iterator MBBI = MBB.begin();
228 MachineFrameInfo &MFI = MF.getFrameInfo();
229 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
230 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().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.getMaxAlign() > getStackAlign())
237 report_fatal_error(reason: "emitPrologue unsupported alignment: " +
238 Twine(MFI.getMaxAlign().value()));
239
240 const AttributeList &PAL = MF.getFunction().getAttributes();
241 if (PAL.hasAttrSomewhere(Kind: Attribute::Nest))
242 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::LDWSP_ru6), DestReg: XCore::R11).addImm(Val: 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(ObjectIdx: 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(val: Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
263 MBB.addLiveIn(PhysReg: XCore::LR);
264 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode));
265 MIB.addImm(Val: Adjusted);
266 MIB->addRegisterKilled(IncomingReg: XCore::LR, RegInfo: MF.getSubtarget().getRegisterInfo(),
267 AddIfNotFound: true);
268 if (emitFrameMoves) {
269 EmitDefCfaOffset(MBB, MBBI, dl, TII, Offset: Adjusted*4);
270 unsigned DRegNum = MRI->getDwarfRegNum(Reg: XCore::LR, isEH: true);
271 EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, Offset: 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, fetchLR: saveLR, fetchFP: FP);
278 // We want the nearest (negative) offsets first, so reverse list.
279 std::reverse(first: SpillList.begin(), last: 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, OffsetFromTop, Adjusted, FrameSize,
285 emitFrameMoves);
286 int Offset = Adjusted - OffsetFromTop;
287 int Opcode = isImmU6(val: Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
288 MBB.addLiveIn(PhysReg: SpillList[i].Reg);
289 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode))
290 .addReg(RegNo: SpillList[i].Reg, Flags: RegState::Kill)
291 .addImm(Val: Offset)
292 .addMemOperand(MMO: getFrameIndexMMO(MBB, FrameIndex: SpillList[i].FI,
293 flags: MachineMemOperand::MOStore));
294 if (emitFrameMoves) {
295 unsigned DRegNum = MRI->getDwarfRegNum(Reg: SpillList[i].Reg, isEH: true);
296 EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, Offset: SpillList[i].Offset);
297 }
298 }
299
300 // Complete any remaining Stack adjustment.
301 IfNeededExtSP(MBB, MBBI, dl, TII, OffsetFromTop: 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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::LDAWSP_ru6), DestReg: FramePtr).addImm(Val: 0);
308 if (emitFrameMoves)
309 EmitDefCfaRegister(MBB, MBBI, dl, TII, MF,
310 DRegNum: MRI->getDwarfRegNum(Reg: FramePtr, isEH: true));
311 }
312
313 if (emitFrameMoves) {
314 // Frame moves for callee saved.
315 for (const auto &SpillLabel : XFI->getSpillLabels()) {
316 MachineBasicBlock::iterator Pos = SpillLabel.first;
317 ++Pos;
318 const CalleeSavedInfo &CSI = SpillLabel.second;
319 int Offset = MFI.getObjectOffset(ObjectIdx: CSI.getFrameIdx());
320 unsigned DRegNum = MRI->getDwarfRegNum(Reg: CSI.getReg(), isEH: true);
321 EmitCfiOffset(MBB, MBBI: Pos, dl, TII, DRegNum, Offset);
322 }
323 if (XFI->hasEHSpillSlot()) {
324 // The unwinder requires stack slot & CFI offsets for the exception info.
325 // We do not save/spill these registers.
326 const Function *Fn = &MF.getFunction();
327 const Constant *PersonalityFn =
328 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
329 SmallVector<StackSlotInfo, 2> SpillList;
330 GetEHSpillList(SpillList, MFI, XFI, M: *Fn->getParent(), PersonalityFn,
331 TL: MF.getSubtarget().getTargetLowering());
332 assert(SpillList.size()==2 && "Unexpected SpillList size");
333 EmitCfiOffset(MBB, MBBI, dl, TII,
334 DRegNum: MRI->getDwarfRegNum(Reg: SpillList[0].Reg, isEH: true),
335 Offset: SpillList[0].Offset);
336 EmitCfiOffset(MBB, MBBI, dl, TII,
337 DRegNum: MRI->getDwarfRegNum(Reg: SpillList[1].Reg, isEH: true),
338 Offset: SpillList[1].Offset);
339 }
340 }
341}
342
343void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
344 MachineBasicBlock &MBB) const {
345 MachineFrameInfo &MFI = MF.getFrameInfo();
346 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
347 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
348 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
349 DebugLoc dl = MBBI->getDebugLoc();
350 unsigned RetOpcode = MBBI->getOpcode();
351
352 // Work out frame sizes.
353 // We will adjust the SP in stages towards the final FrameSize.
354 int RemainingAdj = MFI.getStackSize();
355 assert(RemainingAdj%4 == 0 && "Misaligned frame size");
356 RemainingAdj /= 4;
357
358 if (RetOpcode == XCore::EH_RETURN) {
359 // 'Restore' the exception info the unwinder has placed into the stack
360 // slots.
361 const Function *Fn = &MF.getFunction();
362 const Constant *PersonalityFn =
363 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
364 SmallVector<StackSlotInfo, 2> SpillList;
365 GetEHSpillList(SpillList, MFI, XFI, M: *Fn->getParent(), PersonalityFn,
366 TL: MF.getSubtarget().getTargetLowering());
367 RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
368
369 // Return to the landing pad.
370 Register EhStackReg = MBBI->getOperand(i: 0).getReg();
371 Register EhHandlerReg = MBBI->getOperand(i: 1).getReg();
372 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::SETSP_1r)).addReg(RegNo: EhStackReg);
373 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::BAU_1r)).addReg(RegNo: EhHandlerReg);
374 MBB.erase(I: MBBI); // Erase the previous return instruction.
375 return;
376 }
377
378 bool restoreLR = XFI->hasLRSpillSlot();
379 bool UseRETSP = restoreLR && RemainingAdj
380 && (MFI.getObjectOffset(ObjectIdx: XFI->getLRSpillSlot()) == 0);
381 if (UseRETSP)
382 restoreLR = false;
383 bool FP = hasFP(MF);
384
385 if (FP) // Restore the stack pointer.
386 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::SETSP_1r)).addReg(RegNo: FramePtr);
387
388 // If necessary, restore LR and FP from the stack, as we EXTSP.
389 SmallVector<StackSlotInfo,2> SpillList;
390 GetSpillList(SpillList, MFI, XFI, fetchLR: restoreLR, fetchFP: FP);
391 RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
392
393 if (RemainingAdj) {
394 // Complete all but one of the remaining Stack adjustments.
395 IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop: 0, RemainingAdj);
396 if (UseRETSP) {
397 // Fold prologue into return instruction
398 assert(RetOpcode == XCore::RETSP_u6
399 || RetOpcode == XCore::RETSP_lu6);
400 int Opcode = isImmU6(val: RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
401 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode))
402 .addImm(Val: RemainingAdj);
403 for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
404 MIB->addOperand(Op: MBBI->getOperand(i)); // copy any variadic operands
405 MBB.erase(I: MBBI); // Erase the previous return instruction.
406 } else {
407 int Opcode = isImmU6(val: RemainingAdj) ? XCore::LDAWSP_ru6 :
408 XCore::LDAWSP_lru6;
409 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode), DestReg: XCore::SP).addImm(Val: RemainingAdj);
410 // Don't erase the return instruction.
411 }
412 } // else Don't erase the return instruction.
413}
414
415bool XCoreFrameLowering::spillCalleeSavedRegisters(
416 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
417 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
418 if (CSI.empty())
419 return true;
420
421 MachineFunction *MF = MBB.getParent();
422 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
423 XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
424 bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF: *MF);
425
426 DebugLoc DL;
427 if (MI != MBB.end() && !MI->isDebugInstr())
428 DL = MI->getDebugLoc();
429
430 for (const CalleeSavedInfo &I : CSI) {
431 MCRegister Reg = I.getReg();
432 assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
433 "LR & FP are always handled in emitPrologue");
434
435 // Add the callee-saved register as live-in. It's killed at the spill.
436 MBB.addLiveIn(PhysReg: Reg);
437 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
438 TII.storeRegToStackSlot(MBB, MI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(), RC,
439 VReg: Register());
440 if (emitFrameMoves) {
441 auto Store = MI;
442 --Store;
443 XFI->getSpillLabels().push_back(x: std::make_pair(x&: Store, y: I));
444 }
445 }
446 return true;
447}
448
449bool XCoreFrameLowering::restoreCalleeSavedRegisters(
450 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
451 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
452 MachineFunction *MF = MBB.getParent();
453 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
454 bool AtStart = MI == MBB.begin();
455 MachineBasicBlock::iterator BeforeI = MI;
456 if (!AtStart)
457 --BeforeI;
458 for (const CalleeSavedInfo &CSR : CSI) {
459 MCRegister Reg = CSR.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, DestReg: Reg, FrameIndex: CSR.getFrameIdx(), RC, VReg: Register());
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
481MachineBasicBlock::iterator XCoreFrameLowering::eliminateCallFramePseudoInstr(
482 MachineFunction &MF, MachineBasicBlock &MBB,
483 MachineBasicBlock::iterator I) const {
484 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
485 if (!hasReservedCallFrame(MF)) {
486 // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
487 // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
488 MachineInstr &Old = *I;
489 uint64_t Amount = Old.getOperand(i: 0).getImm();
490 if (Amount != 0) {
491 // We need to keep the stack aligned properly. To do this, we round the
492 // amount of space needed for the outgoing arguments up to the next
493 // alignment boundary.
494 Amount = alignTo(Size: Amount, A: getStackAlign());
495
496 assert(Amount%4 == 0);
497 Amount /= 4;
498
499 bool isU6 = isImmU6(val: Amount);
500 if (!isU6 && !isImmU16(val: Amount)) {
501 // FIX could emit multiple instructions in this case.
502#ifndef NDEBUG
503 errs() << "eliminateCallFramePseudoInstr size too big: "
504 << Amount << "\n";
505#endif
506 llvm_unreachable(nullptr);
507 }
508
509 MachineInstr *New;
510 if (Old.getOpcode() == XCore::ADJCALLSTACKDOWN) {
511 int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
512 New = BuildMI(MF, MIMD: Old.getDebugLoc(), MCID: TII.get(Opcode)).addImm(Val: Amount);
513 } else {
514 assert(Old.getOpcode() == XCore::ADJCALLSTACKUP);
515 int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
516 New = BuildMI(MF, MIMD: Old.getDebugLoc(), MCID: TII.get(Opcode), DestReg: XCore::SP)
517 .addImm(Val: Amount);
518 }
519
520 // Replace the pseudo instruction with a new instruction...
521 MBB.insert(I, MI: New);
522 }
523 }
524
525 return MBB.erase(I);
526}
527
528void XCoreFrameLowering::determineCalleeSaves(MachineFunction &MF,
529 BitVector &SavedRegs,
530 RegScavenger *RS) const {
531 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
532
533 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
534
535 const MachineRegisterInfo &MRI = MF.getRegInfo();
536 bool LRUsed = MRI.isPhysRegModified(PhysReg: 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.callsUnwindInit() || MF.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 SavedRegs.reset(Idx: 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
566void XCoreFrameLowering::
567processFunctionBeforeFrameFinalized(MachineFunction &MF,
568 RegScavenger *RS) const {
569 assert(RS && "requiresRegisterScavenging failed");
570 MachineFrameInfo &MFI = MF.getFrameInfo();
571 const TargetRegisterClass &RC = XCore::GRRegsRegClass;
572 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
573 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
574 // Reserve slots close to SP or frame pointer for Scavenging spills.
575 // When using SP for small frames, we don't need any scratch registers.
576 // When using SP for large frames, we may need 2 scratch registers.
577 // When using FP, for large or small frames, we may need 1 scratch register.
578 unsigned Size = TRI.getSpillSize(RC);
579 Align Alignment = TRI.getSpillAlign(RC);
580 if (XFI->isLargeFrame(MF) || hasFP(MF))
581 RS->addScavengingFrameIndex(FI: MFI.CreateSpillStackObject(Size, Alignment));
582 if (XFI->isLargeFrame(MF) && !hasFP(MF))
583 RS->addScavengingFrameIndex(FI: MFI.CreateSpillStackObject(Size, Alignment));
584}
585