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(STI.getIORegSREG())
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::R1, RegState::Define)
83         .addReg(AVR::R1, RegState::Kill)
84         .addReg(AVR::R1, 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 (MachineBasicBlock &MBBJ : llvm::drop_begin(MF)) {
110     MBBJ.addLiveIn(AVR::R29R28);
111   }
112 
113   if (!FrameSize) {
114     return;
115   }
116 
117   // Reserve the necessary frame memory by doing FP -= <size>.
118   unsigned Opcode = (isUInt<6>(FrameSize)) ? AVR::SBIWRdK : AVR::SUBIWRdK;
119 
120   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28)
121                          .addReg(AVR::R29R28, RegState::Kill)
122                          .addImm(FrameSize)
123                          .setMIFlag(MachineInstr::FrameSetup);
124   // The SREG implicit def is dead.
125   MI->getOperand(3).setIsDead();
126 
127   // Write back R29R28 to SP and temporarily disable interrupts.
128   BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
129       .addReg(AVR::R29R28)
130       .setMIFlag(MachineInstr::FrameSetup);
131 }
132 
133 static void restoreStatusRegister(MachineFunction &MF, MachineBasicBlock &MBB) {
134   const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
135 
136   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
137 
138   DebugLoc DL = MBBI->getDebugLoc();
139   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
140   const AVRInstrInfo &TII = *STI.getInstrInfo();
141 
142   // Emit special epilogue code to restore R1, R0 and SREG in interrupt/signal
143   // handlers at the very end of the function, just before reti.
144   if (AFI->isInterruptOrSignalHandler()) {
145     BuildMI(MBB, MBBI, DL, TII.get(AVR::POPRd), AVR::R0);
146     BuildMI(MBB, MBBI, DL, TII.get(AVR::OUTARr))
147         .addImm(STI.getIORegSREG())
148         .addReg(AVR::R0, RegState::Kill);
149     BuildMI(MBB, MBBI, DL, TII.get(AVR::POPWRd), AVR::R1R0);
150   }
151 }
152 
153 void AVRFrameLowering::emitEpilogue(MachineFunction &MF,
154                                     MachineBasicBlock &MBB) const {
155   const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
156 
157   // Early exit if the frame pointer is not needed in this function except for
158   // signal/interrupt handlers where special code generation is required.
159   if (!hasFP(MF) && !AFI->isInterruptOrSignalHandler()) {
160     return;
161   }
162 
163   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
164   assert(MBBI->getDesc().isReturn() &&
165          "Can only insert epilog into returning blocks");
166 
167   DebugLoc DL = MBBI->getDebugLoc();
168   const MachineFrameInfo &MFI = MF.getFrameInfo();
169   unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
170   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
171   const AVRInstrInfo &TII = *STI.getInstrInfo();
172 
173   // Early exit if there is no need to restore the frame pointer.
174   if (!FrameSize && !MF.getFrameInfo().hasVarSizedObjects()) {
175     restoreStatusRegister(MF, MBB);
176     return;
177   }
178 
179   // Skip the callee-saved pop instructions.
180   while (MBBI != MBB.begin()) {
181     MachineBasicBlock::iterator PI = std::prev(MBBI);
182     int Opc = PI->getOpcode();
183 
184     if (Opc != AVR::POPRd && Opc != AVR::POPWRd && !PI->isTerminator()) {
185       break;
186     }
187 
188     --MBBI;
189   }
190 
191   if (FrameSize) {
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 
210   // Write back R29R28 to SP and temporarily disable interrupts.
211   BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
212       .addReg(AVR::R29R28, RegState::Kill);
213 
214   restoreStatusRegister(MF, MBB);
215 }
216 
217 // Return true if the specified function should have a dedicated frame
218 // pointer register. This is true if the function meets any of the following
219 // conditions:
220 //  - a register has been spilled
221 //  - has allocas
222 //  - input arguments are passed using the stack
223 //
224 // Notice that strictly this is not a frame pointer because it contains SP after
225 // frame allocation instead of having the original SP in function entry.
226 bool AVRFrameLowering::hasFP(const MachineFunction &MF) const {
227   const AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
228 
229   return (FuncInfo->getHasSpills() || FuncInfo->getHasAllocas() ||
230           FuncInfo->getHasStackArgs() ||
231           MF.getFrameInfo().hasVarSizedObjects());
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 (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
249     Register Reg = I.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     Register 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.
300 static void fixStackStores(MachineBasicBlock &MBB,
301                            MachineBasicBlock::iterator StartMI,
302                            const TargetInstrInfo &TII) {
303   // Iterate through the BB until we hit a call instruction or we reach the end.
304   for (MachineInstr &MI :
305        llvm::make_early_inc_range(llvm::make_range(StartMI, MBB.end()))) {
306     if (MI.isCall())
307       break;
308 
309     unsigned Opcode = MI.getOpcode();
310 
311     // Only care of pseudo store instructions where SP is the base pointer.
312     if (Opcode != AVR::STDSPQRr && Opcode != AVR::STDWSPQRr)
313       continue;
314 
315     assert(MI.getOperand(0).getReg() == AVR::SP &&
316            "SP is expected as base pointer");
317 
318     // Replace this instruction with a regular store. Use Y as the base
319     // pointer since it is guaranteed to contain a copy of SP.
320     unsigned STOpc =
321         (Opcode == AVR::STDWSPQRr) ? AVR::STDWPtrQRr : AVR::STDPtrQRr;
322 
323     MI.setDesc(TII.get(STOpc));
324     MI.getOperand(0).setReg(AVR::R31R30);
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   if (hasReservedCallFrame(MF)) {
335     return MBB.erase(MI);
336   }
337 
338   DebugLoc DL = MI->getDebugLoc();
339   unsigned int Opcode = MI->getOpcode();
340   int Amount = TII.getFrameSize(*MI);
341 
342   if (Amount == 0) {
343     return MBB.erase(MI);
344   }
345 
346   assert(getStackAlign() == Align(1) && "Unsupported stack alignment");
347 
348   if (Opcode == TII.getCallFrameSetupOpcode()) {
349     // Update the stack pointer.
350     // In many cases this can be done far more efficiently by pushing the
351     // relevant values directly to the stack. However, doing that correctly
352     // (in the right order, possibly skipping some empty space for undef
353     // values, etc) is tricky and thus left to be optimized in the future.
354     BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP);
355 
356     MachineInstr *New =
357         BuildMI(MBB, MI, DL, TII.get(AVR::SUBIWRdK), AVR::R31R30)
358             .addReg(AVR::R31R30, RegState::Kill)
359             .addImm(Amount);
360     New->getOperand(3).setIsDead();
361 
362     BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP).addReg(AVR::R31R30);
363 
364     // Make sure the remaining stack stores are converted to real store
365     // instructions.
366     fixStackStores(MBB, MI, TII);
367   } else {
368     assert(Opcode == TII.getCallFrameDestroyOpcode());
369 
370     // Note that small stack changes could be implemented more efficiently
371     // with a few pop instructions instead of the 8-9 instructions now
372     // required.
373 
374     // Select the best opcode to adjust SP based on the offset size.
375     unsigned AddOpcode;
376 
377     if (isUInt<6>(Amount)) {
378       AddOpcode = AVR::ADIWRdK;
379     } else {
380       AddOpcode = AVR::SUBIWRdK;
381       Amount = -Amount;
382     }
383 
384     // Build the instruction sequence.
385     BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP);
386 
387     MachineInstr *New = BuildMI(MBB, MI, DL, TII.get(AddOpcode), AVR::R31R30)
388                             .addReg(AVR::R31R30, RegState::Kill)
389                             .addImm(Amount);
390     New->getOperand(3).setIsDead();
391 
392     BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP)
393         .addReg(AVR::R31R30, RegState::Kill);
394   }
395 
396   return MBB.erase(MI);
397 }
398 
399 void AVRFrameLowering::determineCalleeSaves(MachineFunction &MF,
400                                             BitVector &SavedRegs,
401                                             RegScavenger *RS) const {
402   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
403 
404   // If we have a frame pointer, the Y register needs to be saved as well.
405   if (hasFP(MF)) {
406     SavedRegs.set(AVR::R29);
407     SavedRegs.set(AVR::R28);
408   }
409 }
410 /// The frame analyzer pass.
411 ///
412 /// Scans the function for allocas and used arguments
413 /// that are passed through the stack.
414 struct AVRFrameAnalyzer : public MachineFunctionPass {
415   static char ID;
416   AVRFrameAnalyzer() : MachineFunctionPass(ID) {}
417 
418   bool runOnMachineFunction(MachineFunction &MF) override {
419     const MachineFrameInfo &MFI = MF.getFrameInfo();
420     AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
421 
422     // If there are no fixed frame indexes during this stage it means there
423     // are allocas present in the function.
424     if (MFI.getNumObjects() != MFI.getNumFixedObjects()) {
425       // Check for the type of allocas present in the function. We only care
426       // about fixed size allocas so do not give false positives if only
427       // variable sized allocas are present.
428       for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
429         // Variable sized objects have size 0.
430         if (MFI.getObjectSize(i)) {
431           AFI->setHasAllocas(true);
432           break;
433         }
434       }
435     }
436 
437     // If there are fixed frame indexes present, scan the function to see if
438     // they are really being used.
439     if (MFI.getNumFixedObjects() == 0) {
440       return false;
441     }
442 
443     // Ok fixed frame indexes present, now scan the function to see if they
444     // are really being used, otherwise we can ignore them.
445     for (const MachineBasicBlock &BB : MF) {
446       for (const MachineInstr &MI : BB) {
447         int Opcode = MI.getOpcode();
448 
449         if ((Opcode != AVR::LDDRdPtrQ) && (Opcode != AVR::LDDWRdPtrQ) &&
450             (Opcode != AVR::STDPtrQRr) && (Opcode != AVR::STDWPtrQRr)) {
451           continue;
452         }
453 
454         for (const MachineOperand &MO : MI.operands()) {
455           if (!MO.isFI()) {
456             continue;
457           }
458 
459           if (MFI.isFixedObjectIndex(MO.getIndex())) {
460             AFI->setHasStackArgs(true);
461             return false;
462           }
463         }
464       }
465     }
466 
467     return false;
468   }
469 
470   StringRef getPassName() const override { return "AVR Frame Analyzer"; }
471 };
472 
473 char AVRFrameAnalyzer::ID = 0;
474 
475 /// Creates instance of the frame analyzer pass.
476 FunctionPass *createAVRFrameAnalyzerPass() { return new AVRFrameAnalyzer(); }
477 
478 } // end of namespace llvm
479