blob: 6f6128f55bbad96a8f27a15e4d4ec56b455dd26f [file] [log] [blame]
Dylan McKay192405a2016-10-05 11:48:56 +00001//===-- AVRFrameLowering.cpp - AVR Frame Information ----------------------===//
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 the AVR implementation of TargetFrameLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AVRFrameLowering.h"
15
16#include "AVR.h"
17#include "AVRInstrInfo.h"
18#include "AVRMachineFunctionInfo.h"
19#include "AVRTargetMachine.h"
20#include "MCTargetDesc/AVRMCTargetDesc.h"
21
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
28
29namespace llvm {
30
31AVRFrameLowering::AVRFrameLowering()
32 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 1, -2) {}
33
34bool AVRFrameLowering::canSimplifyCallFramePseudos(
35 const MachineFunction &MF) const {
36 // Always simplify call frame pseudo instructions, even when
37 // hasReservedCallFrame is false.
38 return true;
39}
40
41bool AVRFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
42 // Reserve call frame memory in function prologue under the following
43 // conditions:
44 // - Y pointer is reserved to be the frame pointer.
45 // - The function does not contain variable sized objects.
46 // - MaxCallFrameSize doesn't fit into 6-bits (when it's greater than 63).
47 const MachineFrameInfo &MFI = MF.getFrameInfo();
48 return (hasFP(MF) && !MFI.hasVarSizedObjects() &&
49 !isUInt<6>(MFI.getMaxCallFrameSize()));
50}
51
52void AVRFrameLowering::emitPrologue(MachineFunction &MF,
53 MachineBasicBlock &MBB) const {
54 MachineBasicBlock::iterator MBBI = MBB.begin();
55 CallingConv::ID CallConv = MF.getFunction()->getCallingConv();
56 DebugLoc DL = (MBBI != MBB.end()) ? MBBI->getDebugLoc() : DebugLoc();
57 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
58 const AVRInstrInfo &TII = *STI.getInstrInfo();
59
60 // Interrupt handlers re-enable interrupts in function entry.
61 if (CallConv == CallingConv::AVR_INTR) {
62 BuildMI(MBB, MBBI, DL, TII.get(AVR::BSETs))
63 .addImm(0x07)
64 .setMIFlag(MachineInstr::FrameSetup);
65 }
66
67 // Emit special prologue code to save R1, R0 and SREG in interrupt/signal
68 // handlers before saving any other registers.
69 if (CallConv == CallingConv::AVR_INTR ||
70 CallConv == CallingConv::AVR_SIGNAL) {
71 BuildMI(MBB, MBBI, DL, TII.get(AVR::PUSHWRr))
72 .addReg(AVR::R1R0, RegState::Kill)
73 .setMIFlag(MachineInstr::FrameSetup);
74 BuildMI(MBB, MBBI, DL, TII.get(AVR::INRdA), AVR::R0)
75 .addImm(0x3f)
76 .setMIFlag(MachineInstr::FrameSetup);
77 BuildMI(MBB, MBBI, DL, TII.get(AVR::PUSHRr))
78 .addReg(AVR::R0, RegState::Kill)
79 .setMIFlag(MachineInstr::FrameSetup);
80 BuildMI(MBB, MBBI, DL, TII.get(AVR::EORRdRr))
81 .addReg(AVR::R0, RegState::Define)
82 .addReg(AVR::R0, RegState::Kill)
83 .addReg(AVR::R0, RegState::Kill)
84 .setMIFlag(MachineInstr::FrameSetup);
85 }
86
87 // Early exit if the frame pointer is not needed in this function.
88 if (!hasFP(MF)) {
89 return;
90 }
91
92 const MachineFrameInfo &MFI = MF.getFrameInfo();
93 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
94 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
95
96 // Skip the callee-saved push instructions.
97 while (
98 (MBBI != MBB.end()) && MBBI->getFlag(MachineInstr::FrameSetup) &&
99 (MBBI->getOpcode() == AVR::PUSHRr || MBBI->getOpcode() == AVR::PUSHWRr)) {
100 ++MBBI;
101 }
102
103 // Update Y with the new base value.
104 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPREAD), AVR::R29R28)
105 .addReg(AVR::SP)
106 .setMIFlag(MachineInstr::FrameSetup);
107
108 // Mark the FramePtr as live-in in every block except the entry.
109 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
110 I != E; ++I) {
111 I->addLiveIn(AVR::R29R28);
112 }
113
114 if (!FrameSize) {
115 return;
116 }
117
118 // Reserve the necessary frame memory by doing FP -= <size>.
119 unsigned Opcode = (isUInt<6>(FrameSize)) ? AVR::SBIWRdK : AVR::SUBIWRdK;
120
121 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28)
122 .addReg(AVR::R29R28, RegState::Kill)
123 .addImm(FrameSize)
124 .setMIFlag(MachineInstr::FrameSetup);
125 // The SREG implicit def is dead.
126 MI->getOperand(3).setIsDead();
127
128 // Write back R29R28 to SP and temporarily disable interrupts.
129 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
130 .addReg(AVR::R29R28)
131 .setMIFlag(MachineInstr::FrameSetup);
132}
133
134void AVRFrameLowering::emitEpilogue(MachineFunction &MF,
135 MachineBasicBlock &MBB) const {
136 CallingConv::ID CallConv = MF.getFunction()->getCallingConv();
137 bool isHandler = (CallConv == CallingConv::AVR_INTR ||
138 CallConv == CallingConv::AVR_SIGNAL);
139
140 // Early exit if the frame pointer is not needed in this function except for
141 // signal/interrupt handlers where special code generation is required.
142 if (!hasFP(MF) && !isHandler) {
143 return;
144 }
145
146 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
147 assert(MBBI == MBB.end() &&
148 "Can only insert epilog into returning blocks");
149 DebugLoc DL = MBBI->getDebugLoc();
150 const MachineFrameInfo &MFI = MF.getFrameInfo();
151 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
152 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
153 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
154 const AVRInstrInfo &TII = *STI.getInstrInfo();
155
156 // Emit special epilogue code to restore R1, R0 and SREG in interrupt/signal
157 // handlers at the very end of the function, just before reti.
158 if (isHandler) {
159 BuildMI(MBB, MBBI, DL, TII.get(AVR::POPRd), AVR::R0);
160 BuildMI(MBB, MBBI, DL, TII.get(AVR::OUTARr))
161 .addImm(0x3f)
162 .addReg(AVR::R0, RegState::Kill);
163 BuildMI(MBB, MBBI, DL, TII.get(AVR::POPWRd), AVR::R1R0);
164 }
165
166 // Early exit if there is no need to restore the frame pointer.
167 if (!FrameSize) {
168 return;
169 }
170
171 // Skip the callee-saved pop instructions.
172 while (MBBI != MBB.begin()) {
173 MachineBasicBlock::iterator PI = std::prev(MBBI);
174 int Opc = PI->getOpcode();
175
176 if (Opc != AVR::POPRd && Opc != AVR::POPWRd && !PI->isTerminator()) {
177 break;
178 }
179
180 --MBBI;
181 }
182
183 unsigned Opcode;
184
185 // Select the optimal opcode depending on how big it is.
186 if (isUInt<6>(FrameSize)) {
187 Opcode = AVR::ADIWRdK;
188 } else {
189 Opcode = AVR::SUBIWRdK;
190 FrameSize = -FrameSize;
191 }
192
193 // Restore the frame pointer by doing FP += <size>.
194 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28)
195 .addReg(AVR::R29R28, RegState::Kill)
196 .addImm(FrameSize);
197 // The SREG implicit def is dead.
198 MI->getOperand(3).setIsDead();
199
200 // Write back R29R28 to SP and temporarily disable interrupts.
201 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
202 .addReg(AVR::R29R28, RegState::Kill);
203}
204
205// Return true if the specified function should have a dedicated frame
206// pointer register. This is true if the function meets any of the following
207// conditions:
208// - a register has been spilled
209// - has allocas
210// - input arguments are passed using the stack
211//
212// Notice that strictly this is not a frame pointer because it contains SP after
213// frame allocation instead of having the original SP in function entry.
214bool AVRFrameLowering::hasFP(const MachineFunction &MF) const {
215 const AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
216
217 return (FuncInfo->getHasSpills() || FuncInfo->getHasAllocas() ||
218 FuncInfo->getHasStackArgs());
219}
220
221bool AVRFrameLowering::spillCalleeSavedRegisters(
222 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
223 const std::vector<CalleeSavedInfo> &CSI,
224 const TargetRegisterInfo *TRI) const {
225 if (CSI.empty()) {
226 return false;
227 }
228
229 unsigned CalleeFrameSize = 0;
230 DebugLoc DL = MBB.findDebugLoc(MI);
231 MachineFunction &MF = *MBB.getParent();
232 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
233 const TargetInstrInfo &TII = *STI.getInstrInfo();
234 AVRMachineFunctionInfo *AVRFI = MF.getInfo<AVRMachineFunctionInfo>();
235
236 for (unsigned i = CSI.size(); i != 0; --i) {
237 unsigned Reg = CSI[i - 1].getReg();
238 bool IsNotLiveIn = !MBB.isLiveIn(Reg);
239
240 assert(TRI->getMinimalPhysRegClass(Reg)->getSize() == 1 &&
241 "Invalid register size");
242
243 // Add the callee-saved register as live-in only if it is not already a
244 // live-in register, this usually happens with arguments that are passed
245 // through callee-saved registers.
246 if (IsNotLiveIn) {
247 MBB.addLiveIn(Reg);
248 }
249
250 // Do not kill the register when it is an input argument.
251 BuildMI(MBB, MI, DL, TII.get(AVR::PUSHRr))
252 .addReg(Reg, getKillRegState(IsNotLiveIn))
253 .setMIFlag(MachineInstr::FrameSetup);
254 ++CalleeFrameSize;
255 }
256
257 AVRFI->setCalleeSavedFrameSize(CalleeFrameSize);
258
259 return true;
260}
261
262bool AVRFrameLowering::restoreCalleeSavedRegisters(
263 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
264 const std::vector<CalleeSavedInfo> &CSI,
265 const TargetRegisterInfo *TRI) const {
266 if (CSI.empty()) {
267 return false;
268 }
269
270 DebugLoc DL = MBB.findDebugLoc(MI);
271 const MachineFunction &MF = *MBB.getParent();
272 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
273 const TargetInstrInfo &TII = *STI.getInstrInfo();
274
275 for (const CalleeSavedInfo &CSI : CSI) {
276 unsigned Reg = CSI.getReg();
277
278 assert(TRI->getMinimalPhysRegClass(Reg)->getSize() == 1 &&
279 "Invalid register size");
280
281 BuildMI(MBB, MI, DL, TII.get(AVR::POPRd), Reg);
282 }
283
284 return true;
285}
286
287/// Replace pseudo store instructions that pass arguments through the stack with
288/// real instructions. If insertPushes is true then all instructions are
289/// replaced with push instructions, otherwise regular std instructions are
290/// inserted.
291static void fixStackStores(MachineBasicBlock &MBB,
292 MachineBasicBlock::iterator MI,
293 const TargetInstrInfo &TII, bool insertPushes) {
294 const AVRSubtarget &STI = MBB.getParent()->getSubtarget<AVRSubtarget>();
295 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
296
297 // Iterate through the BB until we hit a call instruction or we reach the end.
298 for (auto I = MI, E = MBB.end(); I != E && !I->isCall();) {
299 MachineBasicBlock::iterator NextMI = std::next(I);
300 MachineInstr &MI = *I;
301 unsigned Opcode = I->getOpcode();
302
303 // Only care of pseudo store instructions where SP is the base pointer.
304 if (Opcode != AVR::STDSPQRr && Opcode != AVR::STDWSPQRr) {
305 I = NextMI;
306 continue;
307 }
308
309 assert(MI.getOperand(0).getReg() == AVR::SP &&
310 "Invalid register, should be SP!");
311 if (insertPushes) {
312 // Replace this instruction with a push.
313 unsigned SrcReg = MI.getOperand(2).getReg();
314 bool SrcIsKill = MI.getOperand(2).isKill();
315
316 // We can't use PUSHWRr here because when expanded the order of the new
317 // instructions are reversed from what we need. Perform the expansion now.
318 if (Opcode == AVR::STDWSPQRr) {
319 BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
320 .addReg(TRI.getSubReg(SrcReg, AVR::sub_hi),
321 getKillRegState(SrcIsKill));
322 BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
323 .addReg(TRI.getSubReg(SrcReg, AVR::sub_lo),
324 getKillRegState(SrcIsKill));
325 } else {
326 BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
327 .addReg(SrcReg, getKillRegState(SrcIsKill));
328 }
329
330 MI.eraseFromParent();
331 I = NextMI;
332 continue;
333 }
334
335 // Replace this instruction with a regular store. Use Y as the base
336 // pointer since it is guaranteed to contain a copy of SP.
337 unsigned STOpc =
338 (Opcode == AVR::STDWSPQRr) ? AVR::STDWPtrQRr : AVR::STDPtrQRr;
339 assert(isUInt<6>(MI.getOperand(1).getImm()) && "Offset is out of range");
340
341 MI.setDesc(TII.get(STOpc));
342 MI.getOperand(0).setReg(AVR::R29R28);
343
344 I = NextMI;
345 }
346}
347
348MachineBasicBlock::iterator AVRFrameLowering::eliminateCallFramePseudoInstr(
349 MachineFunction &MF, MachineBasicBlock &MBB,
350 MachineBasicBlock::iterator MI) const {
351 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
352 const TargetFrameLowering &TFI = *STI.getFrameLowering();
353 const AVRInstrInfo &TII = *STI.getInstrInfo();
354
355 // There is nothing to insert when the call frame memory is allocated during
356 // function entry. Delete the call frame pseudo and replace all pseudo stores
357 // with real store instructions.
358 if (TFI.hasReservedCallFrame(MF)) {
359 fixStackStores(MBB, MI, TII, false);
360 return MBB.erase(MI);
361 }
362
363 DebugLoc DL = MI->getDebugLoc();
364 unsigned int Opcode = MI->getOpcode();
365 int Amount = MI->getOperand(0).getImm();
366
367 // Adjcallstackup does not need to allocate stack space for the call, instead
368 // we insert push instructions that will allocate the necessary stack.
369 // For adjcallstackdown we convert it into an 'adiw reg, <amt>' handling
370 // the read and write of SP in I/O space.
371 if (Amount != 0) {
372 assert(TFI.getStackAlignment() == 1 && "Unsupported stack alignment");
373
374 if (Opcode == TII.getCallFrameSetupOpcode()) {
375 fixStackStores(MBB, MI, TII, true);
376 } else {
377 assert(Opcode == TII.getCallFrameDestroyOpcode());
378
379 // Select the best opcode to adjust SP based on the offset size.
380 unsigned addOpcode;
381 if (isUInt<6>(Amount)) {
382 addOpcode = AVR::ADIWRdK;
383 } else {
384 addOpcode = AVR::SUBIWRdK;
385 Amount = -Amount;
386 }
387
388 // Build the instruction sequence.
389 BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP);
390
391 MachineInstr *New = BuildMI(MBB, MI, DL, TII.get(addOpcode), AVR::R31R30)
392 .addReg(AVR::R31R30, RegState::Kill)
393 .addImm(Amount);
394 New->getOperand(3).setIsDead();
395
396 BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP)
397 .addReg(AVR::R31R30, RegState::Kill);
398 }
399 }
400
401 return MBB.erase(MI);
402}
403
404void AVRFrameLowering::determineCalleeSaves(MachineFunction &MF,
405 BitVector &SavedRegs,
406 RegScavenger *RS) const {
407 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
408
409 // Spill register Y when it is used as the frame pointer.
410 if (hasFP(MF)) {
411 SavedRegs.set(AVR::R29R28);
412 SavedRegs.set(AVR::R29);
413 SavedRegs.set(AVR::R28);
414 }
415}
416/// The frame analyzer pass.
417///
418/// Scans the function for allocas and used arguments
419/// that are passed through the stack.
420struct AVRFrameAnalyzer : public MachineFunctionPass {
421 static char ID;
422 AVRFrameAnalyzer() : MachineFunctionPass(ID) {}
423
424 bool runOnMachineFunction(MachineFunction &MF) {
425 const MachineFrameInfo &MFI = MF.getFrameInfo();
426 AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
427
428 // If there are no fixed frame indexes during this stage it means there
429 // are allocas present in the function.
430 if (MFI.getNumObjects() != MFI.getNumFixedObjects()) {
431 // Check for the type of allocas present in the function. We only care
432 // about fixed size allocas so do not give false positives if only
433 // variable sized allocas are present.
434 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
435 // Variable sized objects have size 0.
436 if (MFI.getObjectSize(i)) {
437 FuncInfo->setHasAllocas(true);
438 break;
439 }
440 }
441 }
442
443 // If there are fixed frame indexes present, scan the function to see if
444 // they are really being used.
445 if (MFI.getNumFixedObjects() == 0) {
446 return false;
447 }
448
449 // Ok fixed frame indexes present, now scan the function to see if they
450 // are really being used, otherwise we can ignore them.
451 for (const MachineBasicBlock &BB : MF) {
452 for (const MachineInstr &MI : BB) {
453 int Opcode = MI.getOpcode();
454
455 if ((Opcode != AVR::LDDRdPtrQ) && (Opcode != AVR::LDDWRdPtrQ) &&
456 (Opcode != AVR::STDPtrQRr) && (Opcode != AVR::STDWPtrQRr)) {
457 continue;
458 }
459
460 for (const MachineOperand &MO : MI.operands()) {
461 if (!MO.isFI()) {
462 continue;
463 }
464
465 if (MFI.isFixedObjectIndex(MO.getIndex())) {
466 FuncInfo->setHasStackArgs(true);
467 return false;
468 }
469 }
470 }
471 }
472
473 return false;
474 }
475
Dylan McKayea555542016-10-05 12:32:24 +0000476 StringRef getPassName() const { return "AVR Frame Analyzer"; }
Dylan McKay192405a2016-10-05 11:48:56 +0000477};
478
479char AVRFrameAnalyzer::ID = 0;
480
481/// Creates instance of the frame analyzer pass.
482FunctionPass *createAVRFrameAnalyzerPass() { return new AVRFrameAnalyzer(); }
483
484/// Create the Dynalloca Stack Pointer Save/Restore pass.
485/// Insert a copy of SP before allocating the dynamic stack memory and restore
486/// it in function exit to restore the original SP state. This avoids the need
487/// of reserving a register pair for a frame pointer.
488struct AVRDynAllocaSR : public MachineFunctionPass {
489 static char ID;
490 AVRDynAllocaSR() : MachineFunctionPass(ID) {}
491
492 bool runOnMachineFunction(MachineFunction &MF) {
493 // Early exit when there are no variable sized objects in the function.
494 if (!MF.getFrameInfo().hasVarSizedObjects()) {
495 return false;
496 }
497
498 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
499 const TargetInstrInfo &TII = *STI.getInstrInfo();
500 MachineBasicBlock &EntryMBB = MF.front();
501 MachineBasicBlock::iterator MBBI = EntryMBB.begin();
502 DebugLoc DL = EntryMBB.findDebugLoc(MBBI);
503
504 unsigned SPCopy =
505 MF.getRegInfo().createVirtualRegister(&AVR::DREGSRegClass);
506
507 // Create a copy of SP in function entry before any dynallocas are
508 // inserted.
509 BuildMI(EntryMBB, MBBI, DL, TII.get(AVR::COPY), SPCopy).addReg(AVR::SP);
510
511 // Restore SP in all exit basic blocks.
512 for (MachineBasicBlock &MBB : MF) {
513 // If last instruction is a return instruction, add a restore copy.
514 if (!MBB.empty() && MBB.back().isReturn()) {
515 MBBI = MBB.getLastNonDebugInstr();
516 DL = MBBI->getDebugLoc();
517 BuildMI(MBB, MBBI, DL, TII.get(AVR::COPY), AVR::SP)
518 .addReg(SPCopy, RegState::Kill);
519 }
520 }
521
522 return true;
523 }
524
Dylan McKayea555542016-10-05 12:32:24 +0000525 StringRef getPassName() const {
Dylan McKay192405a2016-10-05 11:48:56 +0000526 return "AVR dynalloca stack pointer save/restore";
527 }
528};
529
530char AVRDynAllocaSR::ID = 0;
531
532/// createAVRDynAllocaSRPass - returns an instance of the dynalloca stack
533/// pointer save/restore pass.
534FunctionPass *createAVRDynAllocaSRPass() { return new AVRDynAllocaSR(); }
535
536} // end of namespace llvm
537