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/Support/ErrorHandling.h"
27#include "llvm/Target/TargetOptions.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 Constant *PersonalityFn,
161 const TargetLowering *TL) {
162 assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
163 const int *EHSlot = XFI->getEHSpillSlot();
164 ExceptionHandling EH = TL->getTargetMachine().getExceptionModel();
165 SpillList.push_back(
166 Elt: StackSlotInfo(EHSlot[0], MFI.getObjectOffset(ObjectIdx: EHSlot[0]),
167 TL->getExceptionPointerRegister(EH, PersonalityFn)));
168 SpillList.push_back(
169 Elt: StackSlotInfo(EHSlot[0], MFI.getObjectOffset(ObjectIdx: EHSlot[1]),
170 TL->getExceptionSelectorRegister(EH, PersonalityFn)));
171 llvm::sort(C&: SpillList, Comp: CompareSSIOffset);
172}
173
174static MachineMemOperand *getFrameIndexMMO(MachineBasicBlock &MBB,
175 int FrameIndex,
176 MachineMemOperand::Flags flags) {
177 MachineFunction *MF = MBB.getParent();
178 const MachineFrameInfo &MFI = MF->getFrameInfo();
179 MachineMemOperand *MMO = MF->getMachineMemOperand(
180 PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI: FrameIndex), F: flags,
181 Size: MFI.getObjectSize(ObjectIdx: FrameIndex), BaseAlignment: MFI.getObjectAlign(ObjectIdx: FrameIndex));
182 return MMO;
183}
184
185
186/// Restore clobbered registers with their spill slot value.
187/// The SP will be adjusted at the same time, thus the SpillList must be ordered
188/// with the largest (negative) offsets first.
189static void RestoreSpillList(MachineBasicBlock &MBB,
190 MachineBasicBlock::iterator MBBI,
191 const DebugLoc &dl, const TargetInstrInfo &TII,
192 int &RemainingAdj,
193 SmallVectorImpl<StackSlotInfo> &SpillList) {
194 for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
195 assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
196 assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
197 int OffsetFromTop = - SpillList[i].Offset/4;
198 IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
199 int Offset = RemainingAdj - OffsetFromTop;
200 int Opcode = isImmU6(val: Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
201 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode), DestReg: SpillList[i].Reg)
202 .addImm(Val: Offset)
203 .addMemOperand(MMO: getFrameIndexMMO(MBB, FrameIndex: SpillList[i].FI,
204 flags: MachineMemOperand::MOLoad));
205 }
206}
207
208//===----------------------------------------------------------------------===//
209// XCoreFrameLowering:
210//===----------------------------------------------------------------------===//
211
212XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
213 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(4), 0) {
214 // Do nothing
215}
216
217bool XCoreFrameLowering::hasFPImpl(const MachineFunction &MF) const {
218 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
219 MF.getFrameInfo().hasVarSizedObjects();
220}
221
222void XCoreFrameLowering::emitPrologue(MachineFunction &MF,
223 MachineBasicBlock &MBB) const {
224 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
225 MachineBasicBlock::iterator MBBI = MBB.begin();
226 MachineFrameInfo &MFI = MF.getFrameInfo();
227 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
228 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
229 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
230 // Debug location must be unknown since the first debug location is used
231 // to determine the end of the prologue.
232 DebugLoc dl;
233
234 if (MFI.getMaxAlign() > getStackAlign())
235 report_fatal_error(reason: "emitPrologue unsupported alignment: " +
236 Twine(MFI.getMaxAlign().value()));
237
238 const AttributeList &PAL = MF.getFunction().getAttributes();
239 if (PAL.hasAttrSomewhere(Kind: Attribute::Nest))
240 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::LDWSP_ru6), DestReg: XCore::R11).addImm(Val: 0);
241 // FIX: Needs addMemOperand() but can't use getFixedStack() or getStack().
242
243 // Work out frame sizes.
244 // We will adjust the SP in stages towards the final FrameSize.
245 assert(MFI.getStackSize()%4 == 0 && "Misaligned frame size");
246 const int FrameSize = MFI.getStackSize() / 4;
247 int Adjusted = 0;
248
249 bool saveLR = XFI->hasLRSpillSlot();
250 bool UseENTSP = saveLR && FrameSize
251 && (MFI.getObjectOffset(ObjectIdx: XFI->getLRSpillSlot()) == 0);
252 if (UseENTSP)
253 saveLR = false;
254 bool FP = hasFP(MF);
255 bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
256
257 if (UseENTSP) {
258 // Allocate space on the stack at the same time as saving LR.
259 Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
260 int Opcode = isImmU6(val: Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
261 MBB.addLiveIn(PhysReg: XCore::LR);
262 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode));
263 MIB.addImm(Val: Adjusted);
264 MIB->addRegisterKilled(IncomingReg: XCore::LR, RegInfo: MF.getSubtarget().getRegisterInfo(),
265 AddIfNotFound: true);
266 if (emitFrameMoves) {
267 EmitDefCfaOffset(MBB, MBBI, dl, TII, Offset: Adjusted*4);
268 unsigned DRegNum = MRI->getDwarfRegNum(Reg: XCore::LR, isEH: true);
269 EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, Offset: 0);
270 }
271 }
272
273 // If necessary, save LR and FP to the stack, as we EXTSP.
274 SmallVector<StackSlotInfo,2> SpillList;
275 GetSpillList(SpillList, MFI, XFI, fetchLR: saveLR, fetchFP: FP);
276 // We want the nearest (negative) offsets first, so reverse list.
277 std::reverse(first: SpillList.begin(), last: SpillList.end());
278 for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
279 assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
280 assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
281 int OffsetFromTop = - SpillList[i].Offset/4;
282 IfNeededExtSP(MBB, MBBI, dl, TII, OffsetFromTop, Adjusted, FrameSize,
283 emitFrameMoves);
284 int Offset = Adjusted - OffsetFromTop;
285 int Opcode = isImmU6(val: Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
286 MBB.addLiveIn(PhysReg: SpillList[i].Reg);
287 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode))
288 .addReg(RegNo: SpillList[i].Reg, Flags: RegState::Kill)
289 .addImm(Val: Offset)
290 .addMemOperand(MMO: getFrameIndexMMO(MBB, FrameIndex: SpillList[i].FI,
291 flags: MachineMemOperand::MOStore));
292 if (emitFrameMoves) {
293 unsigned DRegNum = MRI->getDwarfRegNum(Reg: SpillList[i].Reg, isEH: true);
294 EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, Offset: SpillList[i].Offset);
295 }
296 }
297
298 // Complete any remaining Stack adjustment.
299 IfNeededExtSP(MBB, MBBI, dl, TII, OffsetFromTop: FrameSize, Adjusted, FrameSize,
300 emitFrameMoves);
301 assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
302
303 if (FP) {
304 // Set the FP from the SP.
305 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::LDAWSP_ru6), DestReg: FramePtr).addImm(Val: 0);
306 if (emitFrameMoves)
307 EmitDefCfaRegister(MBB, MBBI, dl, TII, MF,
308 DRegNum: MRI->getDwarfRegNum(Reg: FramePtr, isEH: true));
309 }
310
311 if (emitFrameMoves) {
312 // Frame moves for callee saved.
313 for (const auto &SpillLabel : XFI->getSpillLabels()) {
314 MachineBasicBlock::iterator Pos = SpillLabel.first;
315 ++Pos;
316 const CalleeSavedInfo &CSI = SpillLabel.second;
317 int Offset = MFI.getObjectOffset(ObjectIdx: CSI.getFrameIdx());
318 unsigned DRegNum = MRI->getDwarfRegNum(Reg: CSI.getReg(), isEH: true);
319 EmitCfiOffset(MBB, MBBI: Pos, dl, TII, DRegNum, Offset);
320 }
321 if (XFI->hasEHSpillSlot()) {
322 // The unwinder requires stack slot & CFI offsets for the exception info.
323 // We do not save/spill these registers.
324 const Function *Fn = &MF.getFunction();
325 const Constant *PersonalityFn =
326 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
327 SmallVector<StackSlotInfo, 2> SpillList;
328 GetEHSpillList(SpillList, MFI, XFI, PersonalityFn,
329 TL: MF.getSubtarget().getTargetLowering());
330 assert(SpillList.size()==2 && "Unexpected SpillList size");
331 EmitCfiOffset(MBB, MBBI, dl, TII,
332 DRegNum: MRI->getDwarfRegNum(Reg: SpillList[0].Reg, isEH: true),
333 Offset: SpillList[0].Offset);
334 EmitCfiOffset(MBB, MBBI, dl, TII,
335 DRegNum: MRI->getDwarfRegNum(Reg: SpillList[1].Reg, isEH: true),
336 Offset: SpillList[1].Offset);
337 }
338 }
339}
340
341void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
342 MachineBasicBlock &MBB) const {
343 MachineFrameInfo &MFI = MF.getFrameInfo();
344 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
345 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
346 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
347 DebugLoc dl = MBBI->getDebugLoc();
348 unsigned RetOpcode = MBBI->getOpcode();
349
350 // Work out frame sizes.
351 // We will adjust the SP in stages towards the final FrameSize.
352 int RemainingAdj = MFI.getStackSize();
353 assert(RemainingAdj%4 == 0 && "Misaligned frame size");
354 RemainingAdj /= 4;
355
356 if (RetOpcode == XCore::EH_RETURN) {
357 // 'Restore' the exception info the unwinder has placed into the stack
358 // slots.
359 const Function *Fn = &MF.getFunction();
360 const Constant *PersonalityFn =
361 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
362 SmallVector<StackSlotInfo, 2> SpillList;
363 GetEHSpillList(SpillList, MFI, XFI, PersonalityFn,
364 TL: MF.getSubtarget().getTargetLowering());
365 RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
366
367 // Return to the landing pad.
368 Register EhStackReg = MBBI->getOperand(i: 0).getReg();
369 Register EhHandlerReg = MBBI->getOperand(i: 1).getReg();
370 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::SETSP_1r)).addReg(RegNo: EhStackReg);
371 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::BAU_1r)).addReg(RegNo: EhHandlerReg);
372 MBB.erase(I: MBBI); // Erase the previous return instruction.
373 return;
374 }
375
376 bool restoreLR = XFI->hasLRSpillSlot();
377 bool UseRETSP = restoreLR && RemainingAdj
378 && (MFI.getObjectOffset(ObjectIdx: XFI->getLRSpillSlot()) == 0);
379 if (UseRETSP)
380 restoreLR = false;
381 bool FP = hasFP(MF);
382
383 if (FP) // Restore the stack pointer.
384 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: XCore::SETSP_1r)).addReg(RegNo: 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, fetchLR: restoreLR, fetchFP: 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, OffsetFromTop: 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(val: RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
399 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode))
400 .addImm(Val: RemainingAdj);
401 for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
402 MIB->addOperand(Op: MBBI->getOperand(i)); // copy any variadic operands
403 MBB.erase(I: MBBI); // Erase the previous return instruction.
404 } else {
405 int Opcode = isImmU6(val: RemainingAdj) ? XCore::LDAWSP_ru6 :
406 XCore::LDAWSP_lru6;
407 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode), DestReg: XCore::SP).addImm(Val: RemainingAdj);
408 // Don't erase the return instruction.
409 }
410 } // else Don't erase the return instruction.
411}
412
413bool XCoreFrameLowering::spillCalleeSavedRegisters(
414 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
415 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
416 if (CSI.empty())
417 return true;
418
419 MachineFunction *MF = MBB.getParent();
420 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
421 XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
422 bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF: *MF);
423
424 DebugLoc DL;
425 if (MI != MBB.end() && !MI->isDebugInstr())
426 DL = MI->getDebugLoc();
427
428 for (const CalleeSavedInfo &I : CSI) {
429 MCRegister Reg = I.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(PhysReg: Reg);
435 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
436 TII.storeRegToStackSlot(MBB, MI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(), RC,
437 VReg: Register());
438 if (emitFrameMoves) {
439 auto Store = MI;
440 --Store;
441 XFI->getSpillLabels().push_back(x: std::make_pair(x&: Store, y: I));
442 }
443 }
444 return true;
445}
446
447bool XCoreFrameLowering::restoreCalleeSavedRegisters(
448 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
449 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
450 MachineFunction *MF = MBB.getParent();
451 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
452 bool AtStart = MI == MBB.begin();
453 MachineBasicBlock::iterator BeforeI = MI;
454 if (!AtStart)
455 --BeforeI;
456 for (const CalleeSavedInfo &CSR : CSI) {
457 MCRegister Reg = CSR.getReg();
458 assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
459 "LR & FP are always handled in emitEpilogue");
460
461 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
462 TII.loadRegFromStackSlot(MBB, MI, DestReg: Reg, FrameIndex: CSR.getFrameIdx(), RC, VReg: Register());
463 assert(MI != MBB.begin() &&
464 "loadRegFromStackSlot didn't insert any code!");
465 // Insert in reverse order. loadRegFromStackSlot can insert multiple
466 // instructions.
467 if (AtStart)
468 MI = MBB.begin();
469 else {
470 MI = BeforeI;
471 ++MI;
472 }
473 }
474 return true;
475}
476
477// This function eliminates ADJCALLSTACKDOWN,
478// ADJCALLSTACKUP pseudo instructions
479MachineBasicBlock::iterator XCoreFrameLowering::eliminateCallFramePseudoInstr(
480 MachineFunction &MF, MachineBasicBlock &MBB,
481 MachineBasicBlock::iterator I) const {
482 const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
483 if (!hasReservedCallFrame(MF)) {
484 // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
485 // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
486 MachineInstr &Old = *I;
487 uint64_t Amount = Old.getOperand(i: 0).getImm();
488 if (Amount != 0) {
489 // We need to keep the stack aligned properly. To do this, we round the
490 // amount of space needed for the outgoing arguments up to the next
491 // alignment boundary.
492 Amount = alignTo(Size: Amount, A: getStackAlign());
493
494 assert(Amount%4 == 0);
495 Amount /= 4;
496
497 bool isU6 = isImmU6(val: Amount);
498 if (!isU6 && !isImmU16(val: Amount)) {
499 // FIX could emit multiple instructions in this case.
500#ifndef NDEBUG
501 errs() << "eliminateCallFramePseudoInstr size too big: "
502 << Amount << "\n";
503#endif
504 llvm_unreachable(nullptr);
505 }
506
507 MachineInstr *New;
508 if (Old.getOpcode() == XCore::ADJCALLSTACKDOWN) {
509 int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
510 New = BuildMI(MF, MIMD: Old.getDebugLoc(), MCID: TII.get(Opcode)).addImm(Val: Amount);
511 } else {
512 assert(Old.getOpcode() == XCore::ADJCALLSTACKUP);
513 int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
514 New = BuildMI(MF, MIMD: Old.getDebugLoc(), MCID: TII.get(Opcode), DestReg: XCore::SP)
515 .addImm(Val: Amount);
516 }
517
518 // Replace the pseudo instruction with a new instruction...
519 MBB.insert(I, MI: New);
520 }
521 }
522
523 return MBB.erase(I);
524}
525
526void XCoreFrameLowering::determineCalleeSaves(MachineFunction &MF,
527 BitVector &SavedRegs,
528 RegScavenger *RS) const {
529 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
530
531 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
532
533 const MachineRegisterInfo &MRI = MF.getRegInfo();
534 bool LRUsed = MRI.isPhysRegModified(PhysReg: XCore::LR);
535
536 if (!LRUsed && !MF.getFunction().isVarArg() &&
537 MF.getFrameInfo().estimateStackSize(MF))
538 // If we need to extend the stack it is more efficient to use entsp / retsp.
539 // We force the LR to be saved so these instructions are used.
540 LRUsed = true;
541
542 if (MF.callsUnwindInit() || MF.callsEHReturn()) {
543 // The unwinder expects to find spill slots for the exception info regs R0
544 // & R1. These are used during llvm.eh.return() to 'restore' the exception
545 // info. N.B. we do not spill or restore R0, R1 during normal operation.
546 XFI->createEHSpillSlot(MF);
547 // As we will have a stack, we force the LR to be saved.
548 LRUsed = true;
549 }
550
551 if (LRUsed) {
552 // We will handle the LR in the prologue/epilogue
553 // and allocate space on the stack ourselves.
554 SavedRegs.reset(Idx: XCore::LR);
555 XFI->createLRSpillSlot(MF);
556 }
557
558 if (hasFP(MF))
559 // A callee save register is used to hold the FP.
560 // This needs saving / restoring in the epilogue / prologue.
561 XFI->createFPSpillSlot(MF);
562}
563
564void XCoreFrameLowering::
565processFunctionBeforeFrameFinalized(MachineFunction &MF,
566 RegScavenger *RS) const {
567 assert(RS && "requiresRegisterScavenging failed");
568 MachineFrameInfo &MFI = MF.getFrameInfo();
569 const TargetRegisterClass &RC = XCore::GRRegsRegClass;
570 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
571 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
572 // Reserve slots close to SP or frame pointer for Scavenging spills.
573 // When using SP for small frames, we don't need any scratch registers.
574 // When using SP for large frames, we may need 2 scratch registers.
575 // When using FP, for large or small frames, we may need 1 scratch register.
576 unsigned Size = TRI.getSpillSize(RC);
577 Align Alignment = TRI.getSpillAlign(RC);
578 if (XFI->isLargeFrame(MF) || hasFP(MF))
579 RS->addScavengingFrameIndex(FI: MFI.CreateSpillStackObject(Size, Alignment));
580 if (XFI->isLargeFrame(MF) && !hasFP(MF))
581 RS->addScavengingFrameIndex(FI: MFI.CreateSpillStackObject(Size, Alignment));
582}
583