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