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