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