xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AVR/AVRFrameLowering.cpp (revision 3a9a9c0ca44ec535dcf73fe8462bee458e54814b)
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::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(0x3f)
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, Register FP) {
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            "Invalid register, should be SP!");
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(FP);
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 =
360           BuildMI(MBB, MI, DL, TII.get(AVR::SUBIWRdK), AVR::R31R30)
361               .addReg(AVR::R31R30, RegState::Kill)
362               .addImm(Amount);
363       New->getOperand(3).setIsDead();
364 
365       BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP).addReg(AVR::R31R30);
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 } // end of namespace llvm
482