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 BuildMI(MBB, MBBI, DL, TII.get(AVR::EORRdRr)) 87 .addReg(AVR::R1, RegState::Define) 88 .addReg(AVR::R1, RegState::Kill) 89 .addReg(AVR::R1, RegState::Kill) 90 .setMIFlag(MachineInstr::FrameSetup); 91 } 92 93 // Early exit if the frame pointer is not needed in this function. 94 if (!HasFP) { 95 return; 96 } 97 98 const MachineFrameInfo &MFI = MF.getFrameInfo(); 99 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize(); 100 101 // Skip the callee-saved push instructions. 102 while ( 103 (MBBI != MBB.end()) && MBBI->getFlag(MachineInstr::FrameSetup) && 104 (MBBI->getOpcode() == AVR::PUSHRr || MBBI->getOpcode() == AVR::PUSHWRr)) { 105 ++MBBI; 106 } 107 108 // Update Y with the new base value. 109 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPREAD), AVR::R29R28) 110 .addReg(AVR::SP) 111 .setMIFlag(MachineInstr::FrameSetup); 112 113 // Mark the FramePtr as live-in in every block except the entry. 114 for (MachineBasicBlock &MBBJ : llvm::drop_begin(MF)) { 115 MBBJ.addLiveIn(AVR::R29R28); 116 } 117 118 if (!FrameSize) { 119 return; 120 } 121 122 // Reserve the necessary frame memory by doing FP -= <size>. 123 unsigned Opcode = (isUInt<6>(FrameSize)) ? AVR::SBIWRdK : AVR::SUBIWRdK; 124 125 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28) 126 .addReg(AVR::R29R28, RegState::Kill) 127 .addImm(FrameSize) 128 .setMIFlag(MachineInstr::FrameSetup); 129 // The SREG implicit def is dead. 130 MI->getOperand(3).setIsDead(); 131 132 // Write back R29R28 to SP and temporarily disable interrupts. 133 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP) 134 .addReg(AVR::R29R28) 135 .setMIFlag(MachineInstr::FrameSetup); 136 } 137 138 static void restoreStatusRegister(MachineFunction &MF, MachineBasicBlock &MBB) { 139 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 140 141 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 142 143 DebugLoc DL = MBBI->getDebugLoc(); 144 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>(); 145 const AVRInstrInfo &TII = *STI.getInstrInfo(); 146 147 // Emit special epilogue code to restore R1, R0 and SREG in interrupt/signal 148 // handlers at the very end of the function, just before reti. 149 if (AFI->isInterruptOrSignalHandler()) { 150 BuildMI(MBB, MBBI, DL, TII.get(AVR::POPRd), AVR::R0); 151 BuildMI(MBB, MBBI, DL, TII.get(AVR::OUTARr)) 152 .addImm(0x3f) 153 .addReg(AVR::R0, RegState::Kill); 154 BuildMI(MBB, MBBI, DL, TII.get(AVR::POPWRd), AVR::R1R0); 155 } 156 } 157 158 void AVRFrameLowering::emitEpilogue(MachineFunction &MF, 159 MachineBasicBlock &MBB) const { 160 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 161 162 // Early exit if the frame pointer is not needed in this function except for 163 // signal/interrupt handlers where special code generation is required. 164 if (!hasFP(MF) && !AFI->isInterruptOrSignalHandler()) { 165 return; 166 } 167 168 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 169 assert(MBBI->getDesc().isReturn() && 170 "Can only insert epilog into returning blocks"); 171 172 DebugLoc DL = MBBI->getDebugLoc(); 173 const MachineFrameInfo &MFI = MF.getFrameInfo(); 174 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize(); 175 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>(); 176 const AVRInstrInfo &TII = *STI.getInstrInfo(); 177 178 // Early exit if there is no need to restore the frame pointer. 179 if (!FrameSize && !MF.getFrameInfo().hasVarSizedObjects()) { 180 restoreStatusRegister(MF, MBB); 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 if (FrameSize) { 197 unsigned Opcode; 198 199 // Select the optimal opcode depending on how big it is. 200 if (isUInt<6>(FrameSize)) { 201 Opcode = AVR::ADIWRdK; 202 } else { 203 Opcode = AVR::SUBIWRdK; 204 FrameSize = -FrameSize; 205 } 206 207 // Restore the frame pointer by doing FP += <size>. 208 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28) 209 .addReg(AVR::R29R28, RegState::Kill) 210 .addImm(FrameSize); 211 // The SREG implicit def is dead. 212 MI->getOperand(3).setIsDead(); 213 } 214 215 // Write back R29R28 to SP and temporarily disable interrupts. 216 BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP) 217 .addReg(AVR::R29R28, RegState::Kill); 218 219 restoreStatusRegister(MF, MBB); 220 } 221 222 // Return true if the specified function should have a dedicated frame 223 // pointer register. This is true if the function meets any of the following 224 // conditions: 225 // - a register has been spilled 226 // - has allocas 227 // - input arguments are passed using the stack 228 // 229 // Notice that strictly this is not a frame pointer because it contains SP after 230 // frame allocation instead of having the original SP in function entry. 231 bool AVRFrameLowering::hasFP(const MachineFunction &MF) const { 232 const AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>(); 233 234 return (FuncInfo->getHasSpills() || FuncInfo->getHasAllocas() || 235 FuncInfo->getHasStackArgs() || 236 MF.getFrameInfo().hasVarSizedObjects()); 237 } 238 239 bool AVRFrameLowering::spillCalleeSavedRegisters( 240 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 241 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 242 if (CSI.empty()) { 243 return false; 244 } 245 246 unsigned CalleeFrameSize = 0; 247 DebugLoc DL = MBB.findDebugLoc(MI); 248 MachineFunction &MF = *MBB.getParent(); 249 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>(); 250 const TargetInstrInfo &TII = *STI.getInstrInfo(); 251 AVRMachineFunctionInfo *AVRFI = MF.getInfo<AVRMachineFunctionInfo>(); 252 253 for (const CalleeSavedInfo &I : llvm::reverse(CSI)) { 254 Register Reg = I.getReg(); 255 bool IsNotLiveIn = !MBB.isLiveIn(Reg); 256 257 assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 && 258 "Invalid register size"); 259 260 // Add the callee-saved register as live-in only if it is not already a 261 // live-in register, this usually happens with arguments that are passed 262 // through callee-saved registers. 263 if (IsNotLiveIn) { 264 MBB.addLiveIn(Reg); 265 } 266 267 // Do not kill the register when it is an input argument. 268 BuildMI(MBB, MI, DL, TII.get(AVR::PUSHRr)) 269 .addReg(Reg, getKillRegState(IsNotLiveIn)) 270 .setMIFlag(MachineInstr::FrameSetup); 271 ++CalleeFrameSize; 272 } 273 274 AVRFI->setCalleeSavedFrameSize(CalleeFrameSize); 275 276 return true; 277 } 278 279 bool AVRFrameLowering::restoreCalleeSavedRegisters( 280 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 281 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 282 if (CSI.empty()) { 283 return false; 284 } 285 286 DebugLoc DL = MBB.findDebugLoc(MI); 287 const MachineFunction &MF = *MBB.getParent(); 288 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>(); 289 const TargetInstrInfo &TII = *STI.getInstrInfo(); 290 291 for (const CalleeSavedInfo &CCSI : CSI) { 292 Register Reg = CCSI.getReg(); 293 294 assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 && 295 "Invalid register size"); 296 297 BuildMI(MBB, MI, DL, TII.get(AVR::POPRd), Reg); 298 } 299 300 return true; 301 } 302 303 /// Replace pseudo store instructions that pass arguments through the stack with 304 /// real instructions. 305 static void fixStackStores(MachineBasicBlock &MBB, 306 MachineBasicBlock::iterator MI, 307 const TargetInstrInfo &TII, Register FP) { 308 // Iterate through the BB until we hit a call instruction or we reach the end. 309 for (MachineInstr &MI : 310 llvm::make_early_inc_range(llvm::make_range(MI, MBB.end()))) { 311 if (MI.isCall()) 312 break; 313 314 unsigned Opcode = MI.getOpcode(); 315 316 // Only care of pseudo store instructions where SP is the base pointer. 317 if (Opcode != AVR::STDSPQRr && Opcode != AVR::STDWSPQRr) 318 continue; 319 320 assert(MI.getOperand(0).getReg() == AVR::SP && 321 "Invalid register, should be SP!"); 322 323 // Replace this instruction with a regular store. Use Y as the base 324 // pointer since it is guaranteed to contain a copy of SP. 325 unsigned STOpc = 326 (Opcode == AVR::STDWSPQRr) ? AVR::STDWPtrQRr : AVR::STDPtrQRr; 327 328 MI.setDesc(TII.get(STOpc)); 329 MI.getOperand(0).setReg(FP); 330 } 331 } 332 333 MachineBasicBlock::iterator AVRFrameLowering::eliminateCallFramePseudoInstr( 334 MachineFunction &MF, MachineBasicBlock &MBB, 335 MachineBasicBlock::iterator MI) const { 336 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>(); 337 const AVRInstrInfo &TII = *STI.getInstrInfo(); 338 339 // There is nothing to insert when the call frame memory is allocated during 340 // function entry. Delete the call frame pseudo and replace all pseudo stores 341 // with real store instructions. 342 if (hasReservedCallFrame(MF)) { 343 fixStackStores(MBB, MI, TII, AVR::R29R28); 344 return MBB.erase(MI); 345 } 346 347 DebugLoc DL = MI->getDebugLoc(); 348 unsigned int Opcode = MI->getOpcode(); 349 int Amount = TII.getFrameSize(*MI); 350 351 // ADJCALLSTACKUP and ADJCALLSTACKDOWN are converted to adiw/subi 352 // instructions to read and write the stack pointer in I/O space. 353 if (Amount != 0) { 354 assert(getStackAlign() == Align(1) && "Unsupported stack alignment"); 355 356 if (Opcode == TII.getCallFrameSetupOpcode()) { 357 // Update the stack pointer. 358 // In many cases this can be done far more efficiently by pushing the 359 // relevant values directly to the stack. However, doing that correctly 360 // (in the right order, possibly skipping some empty space for undef 361 // values, etc) is tricky and thus left to be optimized in the future. 362 BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP); 363 364 MachineInstr *New = 365 BuildMI(MBB, MI, DL, TII.get(AVR::SUBIWRdK), AVR::R31R30) 366 .addReg(AVR::R31R30, RegState::Kill) 367 .addImm(Amount); 368 New->getOperand(3).setIsDead(); 369 370 BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP).addReg(AVR::R31R30); 371 372 // Make sure the remaining stack stores are converted to real store 373 // instructions. 374 fixStackStores(MBB, MI, TII, AVR::R31R30); 375 } else { 376 assert(Opcode == TII.getCallFrameDestroyOpcode()); 377 378 // Note that small stack changes could be implemented more efficiently 379 // with a few pop instructions instead of the 8-9 instructions now 380 // required. 381 382 // Select the best opcode to adjust SP based on the offset size. 383 unsigned addOpcode; 384 if (isUInt<6>(Amount)) { 385 addOpcode = AVR::ADIWRdK; 386 } else { 387 addOpcode = AVR::SUBIWRdK; 388 Amount = -Amount; 389 } 390 391 // Build the instruction sequence. 392 BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP); 393 394 MachineInstr *New = BuildMI(MBB, MI, DL, TII.get(addOpcode), AVR::R31R30) 395 .addReg(AVR::R31R30, RegState::Kill) 396 .addImm(Amount); 397 New->getOperand(3).setIsDead(); 398 399 BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP) 400 .addReg(AVR::R31R30, RegState::Kill); 401 } 402 } 403 404 return MBB.erase(MI); 405 } 406 407 void AVRFrameLowering::determineCalleeSaves(MachineFunction &MF, 408 BitVector &SavedRegs, 409 RegScavenger *RS) const { 410 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 411 412 // If we have a frame pointer, the Y register needs to be saved as well. 413 if (hasFP(MF)) { 414 SavedRegs.set(AVR::R29); 415 SavedRegs.set(AVR::R28); 416 } 417 } 418 /// The frame analyzer pass. 419 /// 420 /// Scans the function for allocas and used arguments 421 /// that are passed through the stack. 422 struct AVRFrameAnalyzer : public MachineFunctionPass { 423 static char ID; 424 AVRFrameAnalyzer() : MachineFunctionPass(ID) {} 425 426 bool runOnMachineFunction(MachineFunction &MF) override { 427 const MachineFrameInfo &MFI = MF.getFrameInfo(); 428 AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>(); 429 430 // If there are no fixed frame indexes during this stage it means there 431 // are allocas present in the function. 432 if (MFI.getNumObjects() != MFI.getNumFixedObjects()) { 433 // Check for the type of allocas present in the function. We only care 434 // about fixed size allocas so do not give false positives if only 435 // variable sized allocas are present. 436 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 437 // Variable sized objects have size 0. 438 if (MFI.getObjectSize(i)) { 439 FuncInfo->setHasAllocas(true); 440 break; 441 } 442 } 443 } 444 445 // If there are fixed frame indexes present, scan the function to see if 446 // they are really being used. 447 if (MFI.getNumFixedObjects() == 0) { 448 return false; 449 } 450 451 // Ok fixed frame indexes present, now scan the function to see if they 452 // are really being used, otherwise we can ignore them. 453 for (const MachineBasicBlock &BB : MF) { 454 for (const MachineInstr &MI : BB) { 455 int Opcode = MI.getOpcode(); 456 457 if ((Opcode != AVR::LDDRdPtrQ) && (Opcode != AVR::LDDWRdPtrQ) && 458 (Opcode != AVR::STDPtrQRr) && (Opcode != AVR::STDWPtrQRr)) { 459 continue; 460 } 461 462 for (const MachineOperand &MO : MI.operands()) { 463 if (!MO.isFI()) { 464 continue; 465 } 466 467 if (MFI.isFixedObjectIndex(MO.getIndex())) { 468 FuncInfo->setHasStackArgs(true); 469 return false; 470 } 471 } 472 } 473 } 474 475 return false; 476 } 477 478 StringRef getPassName() const override { return "AVR Frame Analyzer"; } 479 }; 480 481 char AVRFrameAnalyzer::ID = 0; 482 483 /// Creates instance of the frame analyzer pass. 484 FunctionPass *createAVRFrameAnalyzerPass() { return new AVRFrameAnalyzer(); } 485 486 } // end of namespace llvm 487