1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the ARM implementation of TargetFrameLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMFrameLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMMachineFunctionInfo.h" 18 #include "MCTargetDesc/ARMAddressingModes.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/RegisterScavenging.h" 24 #include "llvm/IR/CallingConv.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Target/TargetOptions.h" 28 29 using namespace llvm; 30 31 static cl::opt<bool> 32 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), 33 cl::desc("Align ARM NEON spills in prolog and epilog")); 34 35 static MachineBasicBlock::iterator 36 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 37 unsigned NumAlignedDPRCS2Regs); 38 39 /// hasFP - Return true if the specified function should have a dedicated frame 40 /// pointer register. This is true if the function has variable sized allocas 41 /// or if frame pointer elimination is disabled. 42 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const { 43 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 44 45 // iOS requires FP not to be clobbered for backtracing purpose. 46 if (STI.isTargetIOS()) 47 return true; 48 49 const MachineFrameInfo *MFI = MF.getFrameInfo(); 50 // Always eliminate non-leaf frame pointers. 51 return ((MF.getTarget().Options.DisableFramePointerElim(MF) && 52 MFI->hasCalls()) || 53 RegInfo->needsStackRealignment(MF) || 54 MFI->hasVarSizedObjects() || 55 MFI->isFrameAddressTaken()); 56 } 57 58 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 59 /// not required, we reserve argument space for call sites in the function 60 /// immediately on entry to the current function. This eliminates the need for 61 /// add/sub sp brackets around call sites. Returns true if the call frame is 62 /// included as part of the stack frame. 63 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 64 const MachineFrameInfo *FFI = MF.getFrameInfo(); 65 unsigned CFSize = FFI->getMaxCallFrameSize(); 66 // It's not always a good idea to include the call frame as part of the 67 // stack frame. ARM (especially Thumb) has small immediate offset to 68 // address the stack frame. So a large call frame can cause poor codegen 69 // and may even makes it impossible to scavenge a register. 70 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 71 return false; 72 73 return !MF.getFrameInfo()->hasVarSizedObjects(); 74 } 75 76 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 77 /// call frame pseudos can be simplified. Unlike most targets, having a FP 78 /// is not sufficient here since we still may reference some objects via SP 79 /// even when FP is available in Thumb2 mode. 80 bool 81 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 82 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects(); 83 } 84 85 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) { 86 for (unsigned i = 0; CSRegs[i]; ++i) 87 if (Reg == CSRegs[i]) 88 return true; 89 return false; 90 } 91 92 static bool isCSRestore(MachineInstr *MI, 93 const ARMBaseInstrInfo &TII, 94 const uint16_t *CSRegs) { 95 // Integer spill area is handled with "pop". 96 if (MI->getOpcode() == ARM::LDMIA_RET || 97 MI->getOpcode() == ARM::t2LDMIA_RET || 98 MI->getOpcode() == ARM::LDMIA_UPD || 99 MI->getOpcode() == ARM::t2LDMIA_UPD || 100 MI->getOpcode() == ARM::VLDMDIA_UPD) { 101 // The first two operands are predicates. The last two are 102 // imp-def and imp-use of SP. Check everything in between. 103 for (int i = 5, e = MI->getNumOperands(); i != e; ++i) 104 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs)) 105 return false; 106 return true; 107 } 108 if ((MI->getOpcode() == ARM::LDR_POST_IMM || 109 MI->getOpcode() == ARM::LDR_POST_REG || 110 MI->getOpcode() == ARM::t2LDR_POST) && 111 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) && 112 MI->getOperand(1).getReg() == ARM::SP) 113 return true; 114 115 return false; 116 } 117 118 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB, 119 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 120 const ARMBaseInstrInfo &TII, unsigned DestReg, 121 unsigned SrcReg, int NumBytes, 122 unsigned MIFlags = MachineInstr::NoFlags, 123 ARMCC::CondCodes Pred = ARMCC::AL, 124 unsigned PredReg = 0) { 125 if (isARM) 126 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 127 Pred, PredReg, TII, MIFlags); 128 else 129 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 130 Pred, PredReg, TII, MIFlags); 131 } 132 133 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, 134 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 135 const ARMBaseInstrInfo &TII, int NumBytes, 136 unsigned MIFlags = MachineInstr::NoFlags, 137 ARMCC::CondCodes Pred = ARMCC::AL, 138 unsigned PredReg = 0) { 139 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes, 140 MIFlags, Pred, PredReg); 141 } 142 143 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const { 144 MachineBasicBlock &MBB = MF.front(); 145 MachineBasicBlock::iterator MBBI = MBB.begin(); 146 MachineFrameInfo *MFI = MF.getFrameInfo(); 147 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 148 const ARMBaseRegisterInfo *RegInfo = 149 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 150 const ARMBaseInstrInfo &TII = 151 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 152 assert(!AFI->isThumb1OnlyFunction() && 153 "This emitPrologue does not support Thumb1!"); 154 bool isARM = !AFI->isThumbFunction(); 155 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment(); 156 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 157 unsigned NumBytes = MFI->getStackSize(); 158 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 159 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 160 unsigned FramePtr = RegInfo->getFrameRegister(MF); 161 162 // Determine the sizes of each callee-save spill areas and record which frame 163 // belongs to which callee-save spill areas. 164 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 165 int FramePtrSpillFI = 0; 166 int D8SpillFI = 0; 167 168 // All calls are tail calls in GHC calling conv, and functions have no 169 // prologue/epilogue. 170 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 171 return; 172 173 // Allocate the vararg register save area. This is not counted in NumBytes. 174 if (ArgRegsSaveSize) 175 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize, 176 MachineInstr::FrameSetup); 177 178 if (!AFI->hasStackFrame()) { 179 if (NumBytes != 0) 180 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 181 MachineInstr::FrameSetup); 182 return; 183 } 184 185 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 186 unsigned Reg = CSI[i].getReg(); 187 int FI = CSI[i].getFrameIdx(); 188 switch (Reg) { 189 case ARM::R0: 190 case ARM::R1: 191 case ARM::R2: 192 case ARM::R3: 193 case ARM::R4: 194 case ARM::R5: 195 case ARM::R6: 196 case ARM::R7: 197 case ARM::LR: 198 if (Reg == FramePtr) 199 FramePtrSpillFI = FI; 200 GPRCS1Size += 4; 201 break; 202 case ARM::R8: 203 case ARM::R9: 204 case ARM::R10: 205 case ARM::R11: 206 case ARM::R12: 207 if (Reg == FramePtr) 208 FramePtrSpillFI = FI; 209 if (STI.isTargetIOS()) 210 GPRCS2Size += 4; 211 else 212 GPRCS1Size += 4; 213 break; 214 default: 215 // This is a DPR. Exclude the aligned DPRCS2 spills. 216 if (Reg == ARM::D8) 217 D8SpillFI = FI; 218 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) 219 DPRCSSize += 8; 220 } 221 } 222 223 // Move past area 1. 224 if (GPRCS1Size > 0) MBBI++; 225 226 // Determine starting offsets of spill areas. 227 bool HasFP = hasFP(MF); 228 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize); 229 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize; 230 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size; 231 if (HasFP) 232 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + 233 NumBytes); 234 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 235 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 236 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 237 238 // Set FP to point to the stack slot that contains the previous FP. 239 // For iOS, FP is R7, which has now been stored in spill area 1. 240 // Otherwise, if this is not iOS, all the callee-saved registers go 241 // into spill area 1, including the FP in R11. In either case, it is 242 // now safe to emit this assignment. 243 if (HasFP) { 244 int FramePtrOffset = MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size; 245 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, MBBI, dl, TII, 246 FramePtr, ARM::SP, FramePtrOffset, 247 MachineInstr::FrameSetup); 248 } 249 250 // Move past area 2. 251 if (GPRCS2Size > 0) MBBI++; 252 253 // Move past area 3. 254 if (DPRCSSize > 0) { 255 MBBI++; 256 // Since vpush register list cannot have gaps, there may be multiple vpush 257 // instructions in the prologue. 258 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) 259 MBBI++; 260 } 261 262 // Move past the aligned DPRCS2 area. 263 if (AFI->getNumAlignedDPRCS2Regs() > 0) { 264 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs()); 265 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and 266 // leaves the stack pointer pointing to the DPRCS2 area. 267 // 268 // Adjust NumBytes to represent the stack slots below the DPRCS2 area. 269 NumBytes += MFI->getObjectOffset(D8SpillFI); 270 } else 271 NumBytes = DPRCSOffset; 272 273 if (NumBytes) { 274 // Adjust SP after all the callee-save spills. 275 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 276 MachineInstr::FrameSetup); 277 if (HasFP && isARM) 278 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 279 // Note it's not safe to do this in Thumb2 mode because it would have 280 // taken two instructions: 281 // mov sp, r7 282 // sub sp, #24 283 // If an interrupt is taken between the two instructions, then sp is in 284 // an inconsistent state (pointing to the middle of callee-saved area). 285 // The interrupt handler can end up clobbering the registers. 286 AFI->setShouldRestoreSPFromFP(true); 287 } 288 289 if (STI.isTargetELF() && hasFP(MF)) 290 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() - 291 AFI->getFramePtrSpillOffset()); 292 293 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 294 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 295 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 296 297 // If we need dynamic stack realignment, do it here. Be paranoid and make 298 // sure if we also have VLAs, we have a base pointer for frame access. 299 // If aligned NEON registers were spilled, the stack has already been 300 // realigned. 301 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) { 302 unsigned MaxAlign = MFI->getMaxAlignment(); 303 assert (!AFI->isThumb1OnlyFunction()); 304 if (!AFI->isThumbFunction()) { 305 // Emit bic sp, sp, MaxAlign 306 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 307 TII.get(ARM::BICri), ARM::SP) 308 .addReg(ARM::SP, RegState::Kill) 309 .addImm(MaxAlign-1))); 310 } else { 311 // We cannot use sp as source/dest register here, thus we're emitting the 312 // following sequence: 313 // mov r4, sp 314 // bic r4, r4, MaxAlign 315 // mov sp, r4 316 // FIXME: It will be better just to find spare register here. 317 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4) 318 .addReg(ARM::SP, RegState::Kill)); 319 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 320 TII.get(ARM::t2BICri), ARM::R4) 321 .addReg(ARM::R4, RegState::Kill) 322 .addImm(MaxAlign-1))); 323 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 324 .addReg(ARM::R4, RegState::Kill)); 325 } 326 327 AFI->setShouldRestoreSPFromFP(true); 328 } 329 330 // If we need a base pointer, set it up here. It's whatever the value 331 // of the stack pointer is at this point. Any variable size objects 332 // will be allocated after this, so we can still use the base pointer 333 // to reference locals. 334 // FIXME: Clarify FrameSetup flags here. 335 if (RegInfo->hasBasePointer(MF)) { 336 if (isARM) 337 BuildMI(MBB, MBBI, dl, 338 TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 339 .addReg(ARM::SP) 340 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 341 else 342 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 343 RegInfo->getBaseRegister()) 344 .addReg(ARM::SP)); 345 } 346 347 // If the frame has variable sized objects then the epilogue must restore 348 // the sp from fp. We can assume there's an FP here since hasFP already 349 // checks for hasVarSizedObjects. 350 if (MFI->hasVarSizedObjects()) 351 AFI->setShouldRestoreSPFromFP(true); 352 } 353 354 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 355 MachineBasicBlock &MBB) const { 356 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 357 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks"); 358 unsigned RetOpcode = MBBI->getOpcode(); 359 DebugLoc dl = MBBI->getDebugLoc(); 360 MachineFrameInfo *MFI = MF.getFrameInfo(); 361 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 362 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 363 const ARMBaseInstrInfo &TII = 364 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 365 assert(!AFI->isThumb1OnlyFunction() && 366 "This emitEpilogue does not support Thumb1!"); 367 bool isARM = !AFI->isThumbFunction(); 368 369 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment(); 370 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 371 int NumBytes = (int)MFI->getStackSize(); 372 unsigned FramePtr = RegInfo->getFrameRegister(MF); 373 374 // All calls are tail calls in GHC calling conv, and functions have no 375 // prologue/epilogue. 376 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 377 return; 378 379 if (!AFI->hasStackFrame()) { 380 if (NumBytes != 0) 381 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 382 } else { 383 // Unwind MBBI to point to first LDR / VLDRD. 384 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 385 if (MBBI != MBB.begin()) { 386 do 387 --MBBI; 388 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs)); 389 if (!isCSRestore(MBBI, TII, CSRegs)) 390 ++MBBI; 391 } 392 393 // Move SP to start of FP callee save spill area. 394 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() + 395 AFI->getGPRCalleeSavedArea2Size() + 396 AFI->getDPRCalleeSavedAreaSize()); 397 398 // Reset SP based on frame pointer only if the stack frame extends beyond 399 // frame pointer stack slot or target is ELF and the function has FP. 400 if (AFI->shouldRestoreSPFromFP()) { 401 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 402 if (NumBytes) { 403 if (isARM) 404 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 405 ARMCC::AL, 0, TII); 406 else { 407 // It's not possible to restore SP from FP in a single instruction. 408 // For iOS, this looks like: 409 // mov sp, r7 410 // sub sp, #24 411 // This is bad, if an interrupt is taken after the mov, sp is in an 412 // inconsistent state. 413 // Use the first callee-saved register as a scratch register. 414 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) && 415 "No scratch register to restore SP from FP!"); 416 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 417 ARMCC::AL, 0, TII); 418 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 419 ARM::SP) 420 .addReg(ARM::R4)); 421 } 422 } else { 423 // Thumb2 or ARM. 424 if (isARM) 425 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 426 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 427 else 428 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 429 ARM::SP) 430 .addReg(FramePtr)); 431 } 432 } else if (NumBytes) 433 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 434 435 // Increment past our save areas. 436 if (AFI->getDPRCalleeSavedAreaSize()) { 437 MBBI++; 438 // Since vpop register list cannot have gaps, there may be multiple vpop 439 // instructions in the epilogue. 440 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD) 441 MBBI++; 442 } 443 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++; 444 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 445 } 446 447 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) { 448 // Tail call return: adjust the stack pointer and jump to callee. 449 MBBI = MBB.getLastNonDebugInstr(); 450 MachineOperand &JumpTarget = MBBI->getOperand(0); 451 452 // Jump to label or value in register. 453 if (RetOpcode == ARM::TCRETURNdi) { 454 unsigned TCOpcode = STI.isThumb() ? 455 (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) : 456 ARM::TAILJMPd; 457 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode)); 458 if (JumpTarget.isGlobal()) 459 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), 460 JumpTarget.getTargetFlags()); 461 else { 462 assert(JumpTarget.isSymbol()); 463 MIB.addExternalSymbol(JumpTarget.getSymbolName(), 464 JumpTarget.getTargetFlags()); 465 } 466 467 // Add the default predicate in Thumb mode. 468 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0); 469 } else if (RetOpcode == ARM::TCRETURNri) { 470 BuildMI(MBB, MBBI, dl, 471 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)). 472 addReg(JumpTarget.getReg(), RegState::Kill); 473 } 474 475 MachineInstr *NewMI = prior(MBBI); 476 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i) 477 NewMI->addOperand(MBBI->getOperand(i)); 478 479 // Delete the pseudo instruction TCRETURN. 480 MBB.erase(MBBI); 481 MBBI = NewMI; 482 } 483 484 if (ArgRegsSaveSize) 485 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize); 486 } 487 488 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 489 /// debug info. It's the same as what we use for resolving the code-gen 490 /// references for now. FIXME: This can go wrong when references are 491 /// SP-relative and simple call frames aren't used. 492 int 493 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 494 unsigned &FrameReg) const { 495 return ResolveFrameIndexReference(MF, FI, FrameReg, 0); 496 } 497 498 int 499 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 500 int FI, unsigned &FrameReg, 501 int SPAdj) const { 502 const MachineFrameInfo *MFI = MF.getFrameInfo(); 503 const ARMBaseRegisterInfo *RegInfo = 504 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 505 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 506 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize(); 507 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 508 bool isFixed = MFI->isFixedObjectIndex(FI); 509 510 FrameReg = ARM::SP; 511 Offset += SPAdj; 512 513 // SP can move around if there are allocas. We may also lose track of SP 514 // when emergency spilling inside a non-reserved call frame setup. 515 bool hasMovingSP = !hasReservedCallFrame(MF); 516 517 // When dynamically realigning the stack, use the frame pointer for 518 // parameters, and the stack/base pointer for locals. 519 if (RegInfo->needsStackRealignment(MF)) { 520 assert (hasFP(MF) && "dynamic stack realignment without a FP!"); 521 if (isFixed) { 522 FrameReg = RegInfo->getFrameRegister(MF); 523 Offset = FPOffset; 524 } else if (hasMovingSP) { 525 assert(RegInfo->hasBasePointer(MF) && 526 "VLAs and dynamic stack alignment, but missing base pointer!"); 527 FrameReg = RegInfo->getBaseRegister(); 528 } 529 return Offset; 530 } 531 532 // If there is a frame pointer, use it when we can. 533 if (hasFP(MF) && AFI->hasStackFrame()) { 534 // Use frame pointer to reference fixed objects. Use it for locals if 535 // there are VLAs (and thus the SP isn't reliable as a base). 536 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) { 537 FrameReg = RegInfo->getFrameRegister(MF); 538 return FPOffset; 539 } else if (hasMovingSP) { 540 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 541 if (AFI->isThumb2Function()) { 542 // Try to use the frame pointer if we can, else use the base pointer 543 // since it's available. This is handy for the emergency spill slot, in 544 // particular. 545 if (FPOffset >= -255 && FPOffset < 0) { 546 FrameReg = RegInfo->getFrameRegister(MF); 547 return FPOffset; 548 } 549 } 550 } else if (AFI->isThumb2Function()) { 551 // Use add <rd>, sp, #<imm8> 552 // ldr <rd>, [sp, #<imm8>] 553 // if at all possible to save space. 554 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020) 555 return Offset; 556 // In Thumb2 mode, the negative offset is very limited. Try to avoid 557 // out of range references. ldr <rt>,[<rn>, #-<imm8>] 558 if (FPOffset >= -255 && FPOffset < 0) { 559 FrameReg = RegInfo->getFrameRegister(MF); 560 return FPOffset; 561 } 562 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 563 // Otherwise, use SP or FP, whichever is closer to the stack slot. 564 FrameReg = RegInfo->getFrameRegister(MF); 565 return FPOffset; 566 } 567 } 568 // Use the base pointer if we have one. 569 if (RegInfo->hasBasePointer(MF)) 570 FrameReg = RegInfo->getBaseRegister(); 571 return Offset; 572 } 573 574 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF, 575 int FI) const { 576 unsigned FrameReg; 577 return getFrameIndexReference(MF, FI, FrameReg); 578 } 579 580 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 581 MachineBasicBlock::iterator MI, 582 const std::vector<CalleeSavedInfo> &CSI, 583 unsigned StmOpc, unsigned StrOpc, 584 bool NoGap, 585 bool(*Func)(unsigned, bool), 586 unsigned NumAlignedDPRCS2Regs, 587 unsigned MIFlags) const { 588 MachineFunction &MF = *MBB.getParent(); 589 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 590 591 DebugLoc DL; 592 if (MI != MBB.end()) DL = MI->getDebugLoc(); 593 594 SmallVector<std::pair<unsigned,bool>, 4> Regs; 595 unsigned i = CSI.size(); 596 while (i != 0) { 597 unsigned LastReg = 0; 598 for (; i != 0; --i) { 599 unsigned Reg = CSI[i-1].getReg(); 600 if (!(Func)(Reg, STI.isTargetIOS())) continue; 601 602 // D-registers in the aligned area DPRCS2 are NOT spilled here. 603 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 604 continue; 605 606 // Add the callee-saved register as live-in unless it's LR and 607 // @llvm.returnaddress is called. If LR is returned for 608 // @llvm.returnaddress then it's already added to the function and 609 // entry block live-in sets. 610 bool isKill = true; 611 if (Reg == ARM::LR) { 612 if (MF.getFrameInfo()->isReturnAddressTaken() && 613 MF.getRegInfo().isLiveIn(Reg)) 614 isKill = false; 615 } 616 617 if (isKill) 618 MBB.addLiveIn(Reg); 619 620 // If NoGap is true, push consecutive registers and then leave the rest 621 // for other instructions. e.g. 622 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 623 if (NoGap && LastReg && LastReg != Reg-1) 624 break; 625 LastReg = Reg; 626 Regs.push_back(std::make_pair(Reg, isKill)); 627 } 628 629 if (Regs.empty()) 630 continue; 631 if (Regs.size() > 1 || StrOpc== 0) { 632 MachineInstrBuilder MIB = 633 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 634 .addReg(ARM::SP).setMIFlags(MIFlags)); 635 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 636 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 637 } else if (Regs.size() == 1) { 638 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc), 639 ARM::SP) 640 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 641 .addReg(ARM::SP).setMIFlags(MIFlags) 642 .addImm(-4); 643 AddDefaultPred(MIB); 644 } 645 Regs.clear(); 646 } 647 } 648 649 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 650 MachineBasicBlock::iterator MI, 651 const std::vector<CalleeSavedInfo> &CSI, 652 unsigned LdmOpc, unsigned LdrOpc, 653 bool isVarArg, bool NoGap, 654 bool(*Func)(unsigned, bool), 655 unsigned NumAlignedDPRCS2Regs) const { 656 MachineFunction &MF = *MBB.getParent(); 657 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 658 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 659 DebugLoc DL = MI->getDebugLoc(); 660 unsigned RetOpcode = MI->getOpcode(); 661 bool isTailCall = (RetOpcode == ARM::TCRETURNdi || 662 RetOpcode == ARM::TCRETURNri); 663 bool isInterrupt = 664 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR; 665 666 SmallVector<unsigned, 4> Regs; 667 unsigned i = CSI.size(); 668 while (i != 0) { 669 unsigned LastReg = 0; 670 bool DeleteRet = false; 671 for (; i != 0; --i) { 672 unsigned Reg = CSI[i-1].getReg(); 673 if (!(Func)(Reg, STI.isTargetIOS())) continue; 674 675 // The aligned reloads from area DPRCS2 are not inserted here. 676 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 677 continue; 678 679 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt && 680 STI.hasV5TOps()) { 681 Reg = ARM::PC; 682 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 683 // Fold the return instruction into the LDM. 684 DeleteRet = true; 685 } 686 687 // If NoGap is true, pop consecutive registers and then leave the rest 688 // for other instructions. e.g. 689 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 690 if (NoGap && LastReg && LastReg != Reg-1) 691 break; 692 693 LastReg = Reg; 694 Regs.push_back(Reg); 695 } 696 697 if (Regs.empty()) 698 continue; 699 if (Regs.size() > 1 || LdrOpc == 0) { 700 MachineInstrBuilder MIB = 701 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 702 .addReg(ARM::SP)); 703 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 704 MIB.addReg(Regs[i], getDefRegState(true)); 705 if (DeleteRet) { 706 MIB.copyImplicitOps(&*MI); 707 MI->eraseFromParent(); 708 } 709 MI = MIB; 710 } else if (Regs.size() == 1) { 711 // If we adjusted the reg to PC from LR above, switch it back here. We 712 // only do that for LDM. 713 if (Regs[0] == ARM::PC) 714 Regs[0] = ARM::LR; 715 MachineInstrBuilder MIB = 716 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 717 .addReg(ARM::SP, RegState::Define) 718 .addReg(ARM::SP); 719 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 720 // that refactoring is complete (eventually). 721 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) { 722 MIB.addReg(0); 723 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 724 } else 725 MIB.addImm(4); 726 AddDefaultPred(MIB); 727 } 728 Regs.clear(); 729 } 730 } 731 732 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers 733 /// starting from d8. Also insert stack realignment code and leave the stack 734 /// pointer pointing to the d8 spill slot. 735 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, 736 MachineBasicBlock::iterator MI, 737 unsigned NumAlignedDPRCS2Regs, 738 const std::vector<CalleeSavedInfo> &CSI, 739 const TargetRegisterInfo *TRI) { 740 MachineFunction &MF = *MBB.getParent(); 741 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 742 DebugLoc DL = MI->getDebugLoc(); 743 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 744 MachineFrameInfo &MFI = *MF.getFrameInfo(); 745 746 // Mark the D-register spill slots as properly aligned. Since MFI computes 747 // stack slot layout backwards, this can actually mean that the d-reg stack 748 // slot offsets can be wrong. The offset for d8 will always be correct. 749 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 750 unsigned DNum = CSI[i].getReg() - ARM::D8; 751 if (DNum >= 8) 752 continue; 753 int FI = CSI[i].getFrameIdx(); 754 // The even-numbered registers will be 16-byte aligned, the odd-numbered 755 // registers will be 8-byte aligned. 756 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16); 757 758 // The stack slot for D8 needs to be maximally aligned because this is 759 // actually the point where we align the stack pointer. MachineFrameInfo 760 // computes all offsets relative to the incoming stack pointer which is a 761 // bit weird when realigning the stack. Any extra padding for this 762 // over-alignment is not realized because the code inserted below adjusts 763 // the stack pointer by numregs * 8 before aligning the stack pointer. 764 if (DNum == 0) 765 MFI.setObjectAlignment(FI, MFI.getMaxAlignment()); 766 } 767 768 // Move the stack pointer to the d8 spill slot, and align it at the same 769 // time. Leave the stack slot address in the scratch register r4. 770 // 771 // sub r4, sp, #numregs * 8 772 // bic r4, r4, #align - 1 773 // mov sp, r4 774 // 775 bool isThumb = AFI->isThumbFunction(); 776 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 777 AFI->setShouldRestoreSPFromFP(true); 778 779 // sub r4, sp, #numregs * 8 780 // The immediate is <= 64, so it doesn't need any special encoding. 781 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri; 782 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 783 .addReg(ARM::SP) 784 .addImm(8 * NumAlignedDPRCS2Regs))); 785 786 // bic r4, r4, #align-1 787 Opc = isThumb ? ARM::t2BICri : ARM::BICri; 788 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment(); 789 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 790 .addReg(ARM::R4, RegState::Kill) 791 .addImm(MaxAlign - 1))); 792 793 // mov sp, r4 794 // The stack pointer must be adjusted before spilling anything, otherwise 795 // the stack slots could be clobbered by an interrupt handler. 796 // Leave r4 live, it is used below. 797 Opc = isThumb ? ARM::tMOVr : ARM::MOVr; 798 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP) 799 .addReg(ARM::R4); 800 MIB = AddDefaultPred(MIB); 801 if (!isThumb) 802 AddDefaultCC(MIB); 803 804 // Now spill NumAlignedDPRCS2Regs registers starting from d8. 805 // r4 holds the stack slot address. 806 unsigned NextReg = ARM::D8; 807 808 // 16-byte aligned vst1.64 with 4 d-regs and address writeback. 809 // The writeback is only needed when emitting two vst1.64 instructions. 810 if (NumAlignedDPRCS2Regs >= 6) { 811 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 812 &ARM::QQPRRegClass); 813 MBB.addLiveIn(SupReg); 814 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), 815 ARM::R4) 816 .addReg(ARM::R4, RegState::Kill).addImm(16) 817 .addReg(NextReg) 818 .addReg(SupReg, RegState::ImplicitKill)); 819 NextReg += 4; 820 NumAlignedDPRCS2Regs -= 4; 821 } 822 823 // We won't modify r4 beyond this point. It currently points to the next 824 // register to be spilled. 825 unsigned R4BaseReg = NextReg; 826 827 // 16-byte aligned vst1.64 with 4 d-regs, no writeback. 828 if (NumAlignedDPRCS2Regs >= 4) { 829 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 830 &ARM::QQPRRegClass); 831 MBB.addLiveIn(SupReg); 832 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q)) 833 .addReg(ARM::R4).addImm(16).addReg(NextReg) 834 .addReg(SupReg, RegState::ImplicitKill)); 835 NextReg += 4; 836 NumAlignedDPRCS2Regs -= 4; 837 } 838 839 // 16-byte aligned vst1.64 with 2 d-regs. 840 if (NumAlignedDPRCS2Regs >= 2) { 841 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 842 &ARM::QPRRegClass); 843 MBB.addLiveIn(SupReg); 844 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64)) 845 .addReg(ARM::R4).addImm(16).addReg(SupReg)); 846 NextReg += 2; 847 NumAlignedDPRCS2Regs -= 2; 848 } 849 850 // Finally, use a vanilla vstr.64 for the odd last register. 851 if (NumAlignedDPRCS2Regs) { 852 MBB.addLiveIn(NextReg); 853 // vstr.64 uses addrmode5 which has an offset scale of 4. 854 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD)) 855 .addReg(NextReg) 856 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2)); 857 } 858 859 // The last spill instruction inserted should kill the scratch register r4. 860 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI); 861 } 862 863 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an 864 /// iterator to the following instruction. 865 static MachineBasicBlock::iterator 866 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 867 unsigned NumAlignedDPRCS2Regs) { 868 // sub r4, sp, #numregs * 8 869 // bic r4, r4, #align - 1 870 // mov sp, r4 871 ++MI; ++MI; ++MI; 872 assert(MI->mayStore() && "Expecting spill instruction"); 873 874 // These switches all fall through. 875 switch(NumAlignedDPRCS2Regs) { 876 case 7: 877 ++MI; 878 assert(MI->mayStore() && "Expecting spill instruction"); 879 default: 880 ++MI; 881 assert(MI->mayStore() && "Expecting spill instruction"); 882 case 1: 883 case 2: 884 case 4: 885 assert(MI->killsRegister(ARM::R4) && "Missed kill flag"); 886 ++MI; 887 } 888 return MI; 889 } 890 891 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers 892 /// starting from d8. These instructions are assumed to execute while the 893 /// stack is still aligned, unlike the code inserted by emitPopInst. 894 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, 895 MachineBasicBlock::iterator MI, 896 unsigned NumAlignedDPRCS2Regs, 897 const std::vector<CalleeSavedInfo> &CSI, 898 const TargetRegisterInfo *TRI) { 899 MachineFunction &MF = *MBB.getParent(); 900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 901 DebugLoc DL = MI->getDebugLoc(); 902 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 903 904 // Find the frame index assigned to d8. 905 int D8SpillFI = 0; 906 for (unsigned i = 0, e = CSI.size(); i != e; ++i) 907 if (CSI[i].getReg() == ARM::D8) { 908 D8SpillFI = CSI[i].getFrameIdx(); 909 break; 910 } 911 912 // Materialize the address of the d8 spill slot into the scratch register r4. 913 // This can be fairly complicated if the stack frame is large, so just use 914 // the normal frame index elimination mechanism to do it. This code runs as 915 // the initial part of the epilog where the stack and base pointers haven't 916 // been changed yet. 917 bool isThumb = AFI->isThumbFunction(); 918 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 919 920 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri; 921 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 922 .addFrameIndex(D8SpillFI).addImm(0))); 923 924 // Now restore NumAlignedDPRCS2Regs registers starting from d8. 925 unsigned NextReg = ARM::D8; 926 927 // 16-byte aligned vld1.64 with 4 d-regs and writeback. 928 if (NumAlignedDPRCS2Regs >= 6) { 929 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 930 &ARM::QQPRRegClass); 931 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg) 932 .addReg(ARM::R4, RegState::Define) 933 .addReg(ARM::R4, RegState::Kill).addImm(16) 934 .addReg(SupReg, RegState::ImplicitDefine)); 935 NextReg += 4; 936 NumAlignedDPRCS2Regs -= 4; 937 } 938 939 // We won't modify r4 beyond this point. It currently points to the next 940 // register to be spilled. 941 unsigned R4BaseReg = NextReg; 942 943 // 16-byte aligned vld1.64 with 4 d-regs, no writeback. 944 if (NumAlignedDPRCS2Regs >= 4) { 945 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 946 &ARM::QQPRRegClass); 947 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg) 948 .addReg(ARM::R4).addImm(16) 949 .addReg(SupReg, RegState::ImplicitDefine)); 950 NextReg += 4; 951 NumAlignedDPRCS2Regs -= 4; 952 } 953 954 // 16-byte aligned vld1.64 with 2 d-regs. 955 if (NumAlignedDPRCS2Regs >= 2) { 956 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 957 &ARM::QPRRegClass); 958 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg) 959 .addReg(ARM::R4).addImm(16)); 960 NextReg += 2; 961 NumAlignedDPRCS2Regs -= 2; 962 } 963 964 // Finally, use a vanilla vldr.64 for the remaining odd register. 965 if (NumAlignedDPRCS2Regs) 966 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg) 967 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg))); 968 969 // Last store kills r4. 970 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI); 971 } 972 973 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB, 974 MachineBasicBlock::iterator MI, 975 const std::vector<CalleeSavedInfo> &CSI, 976 const TargetRegisterInfo *TRI) const { 977 if (CSI.empty()) 978 return false; 979 980 MachineFunction &MF = *MBB.getParent(); 981 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 982 983 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 984 unsigned PushOneOpc = AFI->isThumbFunction() ? 985 ARM::t2STR_PRE : ARM::STR_PRE_IMM; 986 unsigned FltOpc = ARM::VSTMDDB_UPD; 987 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 988 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0, 989 MachineInstr::FrameSetup); 990 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0, 991 MachineInstr::FrameSetup); 992 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register, 993 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup); 994 995 // The code above does not insert spill code for the aligned DPRCS2 registers. 996 // The stack realignment code will be inserted between the push instructions 997 // and these spills. 998 if (NumAlignedDPRCS2Regs) 999 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1000 1001 return true; 1002 } 1003 1004 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB, 1005 MachineBasicBlock::iterator MI, 1006 const std::vector<CalleeSavedInfo> &CSI, 1007 const TargetRegisterInfo *TRI) const { 1008 if (CSI.empty()) 1009 return false; 1010 1011 MachineFunction &MF = *MBB.getParent(); 1012 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1013 bool isVarArg = AFI->getArgRegsSaveSize() > 0; 1014 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1015 1016 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2 1017 // registers. Do that here instead. 1018 if (NumAlignedDPRCS2Regs) 1019 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1020 1021 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 1022 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM; 1023 unsigned FltOpc = ARM::VLDMDIA_UPD; 1024 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register, 1025 NumAlignedDPRCS2Regs); 1026 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1027 &isARMArea2Register, 0); 1028 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1029 &isARMArea1Register, 0); 1030 1031 return true; 1032 } 1033 1034 // FIXME: Make generic? 1035 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF, 1036 const ARMBaseInstrInfo &TII) { 1037 unsigned FnSize = 0; 1038 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end(); 1039 MBBI != E; ++MBBI) { 1040 const MachineBasicBlock &MBB = *MBBI; 1041 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end(); 1042 I != E; ++I) 1043 FnSize += TII.GetInstSizeInBytes(I); 1044 } 1045 return FnSize; 1046 } 1047 1048 /// estimateRSStackSizeLimit - Look at each instruction that references stack 1049 /// frames and return the stack size limit beyond which some of these 1050 /// instructions will require a scratch register during their expansion later. 1051 // FIXME: Move to TII? 1052 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 1053 const TargetFrameLowering *TFI) { 1054 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1055 unsigned Limit = (1 << 12) - 1; 1056 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) { 1057 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); 1058 I != E; ++I) { 1059 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1060 if (!I->getOperand(i).isFI()) continue; 1061 1062 // When using ADDri to get the address of a stack object, 255 is the 1063 // largest offset guaranteed to fit in the immediate offset. 1064 if (I->getOpcode() == ARM::ADDri) { 1065 Limit = std::min(Limit, (1U << 8) - 1); 1066 break; 1067 } 1068 1069 // Otherwise check the addressing mode. 1070 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) { 1071 case ARMII::AddrMode3: 1072 case ARMII::AddrModeT2_i8: 1073 Limit = std::min(Limit, (1U << 8) - 1); 1074 break; 1075 case ARMII::AddrMode5: 1076 case ARMII::AddrModeT2_i8s4: 1077 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 1078 break; 1079 case ARMII::AddrModeT2_i12: 1080 // i12 supports only positive offset so these will be converted to 1081 // i8 opcodes. See llvm::rewriteT2FrameIndex. 1082 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 1083 Limit = std::min(Limit, (1U << 8) - 1); 1084 break; 1085 case ARMII::AddrMode4: 1086 case ARMII::AddrMode6: 1087 // Addressing modes 4 & 6 (load/store) instructions can't encode an 1088 // immediate offset for stack references. 1089 return 0; 1090 default: 1091 break; 1092 } 1093 break; // At most one FI per instruction 1094 } 1095 } 1096 } 1097 1098 return Limit; 1099 } 1100 1101 // In functions that realign the stack, it can be an advantage to spill the 1102 // callee-saved vector registers after realigning the stack. The vst1 and vld1 1103 // instructions take alignment hints that can improve performance. 1104 // 1105 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) { 1106 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0); 1107 if (!SpillAlignedNEONRegs) 1108 return; 1109 1110 // Naked functions don't spill callee-saved registers. 1111 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1112 Attribute::Naked)) 1113 return; 1114 1115 // We are planning to use NEON instructions vst1 / vld1. 1116 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON()) 1117 return; 1118 1119 // Don't bother if the default stack alignment is sufficiently high. 1120 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8) 1121 return; 1122 1123 // Aligned spills require stack realignment. 1124 const ARMBaseRegisterInfo *RegInfo = 1125 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 1126 if (!RegInfo->canRealignStack(MF)) 1127 return; 1128 1129 // We always spill contiguous d-registers starting from d8. Count how many 1130 // needs spilling. The register allocator will almost always use the 1131 // callee-saved registers in order, but it can happen that there are holes in 1132 // the range. Registers above the hole will be spilled to the standard DPRCS 1133 // area. 1134 MachineRegisterInfo &MRI = MF.getRegInfo(); 1135 unsigned NumSpills = 0; 1136 for (; NumSpills < 8; ++NumSpills) 1137 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills)) 1138 break; 1139 1140 // Don't do this for just one d-register. It's not worth it. 1141 if (NumSpills < 2) 1142 return; 1143 1144 // Spill the first NumSpills D-registers after realigning the stack. 1145 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills); 1146 1147 // A scratch register is required for the vst1 / vld1 instructions. 1148 MF.getRegInfo().setPhysRegUsed(ARM::R4); 1149 } 1150 1151 void 1152 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF, 1153 RegScavenger *RS) const { 1154 // This tells PEI to spill the FP as if it is any other callee-save register 1155 // to take advantage the eliminateFrameIndex machinery. This also ensures it 1156 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 1157 // to combine multiple loads / stores. 1158 bool CanEliminateFrame = true; 1159 bool CS1Spilled = false; 1160 bool LRSpilled = false; 1161 unsigned NumGPRSpills = 0; 1162 SmallVector<unsigned, 4> UnspilledCS1GPRs; 1163 SmallVector<unsigned, 4> UnspilledCS2GPRs; 1164 const ARMBaseRegisterInfo *RegInfo = 1165 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 1166 const ARMBaseInstrInfo &TII = 1167 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 1168 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1169 MachineFrameInfo *MFI = MF.getFrameInfo(); 1170 MachineRegisterInfo &MRI = MF.getRegInfo(); 1171 unsigned FramePtr = RegInfo->getFrameRegister(MF); 1172 1173 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 1174 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 1175 // since it's not always possible to restore sp from fp in a single 1176 // instruction. 1177 // FIXME: It will be better just to find spare register here. 1178 if (AFI->isThumb2Function() && 1179 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF))) 1180 MRI.setPhysRegUsed(ARM::R4); 1181 1182 if (AFI->isThumb1OnlyFunction()) { 1183 // Spill LR if Thumb1 function uses variable length argument lists. 1184 if (AFI->getArgRegsSaveSize() > 0) 1185 MRI.setPhysRegUsed(ARM::LR); 1186 1187 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know 1188 // for sure what the stack size will be, but for this, an estimate is good 1189 // enough. If there anything changes it, it'll be a spill, which implies 1190 // we've used all the registers and so R4 is already used, so not marking 1191 // it here will be OK. 1192 // FIXME: It will be better just to find spare register here. 1193 unsigned StackSize = MFI->estimateStackSize(MF); 1194 if (MFI->hasVarSizedObjects() || StackSize > 508) 1195 MRI.setPhysRegUsed(ARM::R4); 1196 } 1197 1198 // See if we can spill vector registers to aligned stack. 1199 checkNumAlignedDPRCS2Regs(MF); 1200 1201 // Spill the BasePtr if it's used. 1202 if (RegInfo->hasBasePointer(MF)) 1203 MRI.setPhysRegUsed(RegInfo->getBaseRegister()); 1204 1205 // Don't spill FP if the frame can be eliminated. This is determined 1206 // by scanning the callee-save registers to see if any is used. 1207 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 1208 for (unsigned i = 0; CSRegs[i]; ++i) { 1209 unsigned Reg = CSRegs[i]; 1210 bool Spilled = false; 1211 if (MRI.isPhysRegUsed(Reg)) { 1212 Spilled = true; 1213 CanEliminateFrame = false; 1214 } 1215 1216 if (!ARM::GPRRegClass.contains(Reg)) 1217 continue; 1218 1219 if (Spilled) { 1220 NumGPRSpills++; 1221 1222 if (!STI.isTargetIOS()) { 1223 if (Reg == ARM::LR) 1224 LRSpilled = true; 1225 CS1Spilled = true; 1226 continue; 1227 } 1228 1229 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 1230 switch (Reg) { 1231 case ARM::LR: 1232 LRSpilled = true; 1233 // Fallthrough 1234 case ARM::R0: case ARM::R1: 1235 case ARM::R2: case ARM::R3: 1236 case ARM::R4: case ARM::R5: 1237 case ARM::R6: case ARM::R7: 1238 CS1Spilled = true; 1239 break; 1240 default: 1241 break; 1242 } 1243 } else { 1244 if (!STI.isTargetIOS()) { 1245 UnspilledCS1GPRs.push_back(Reg); 1246 continue; 1247 } 1248 1249 switch (Reg) { 1250 case ARM::R0: case ARM::R1: 1251 case ARM::R2: case ARM::R3: 1252 case ARM::R4: case ARM::R5: 1253 case ARM::R6: case ARM::R7: 1254 case ARM::LR: 1255 UnspilledCS1GPRs.push_back(Reg); 1256 break; 1257 default: 1258 UnspilledCS2GPRs.push_back(Reg); 1259 break; 1260 } 1261 } 1262 } 1263 1264 bool ForceLRSpill = false; 1265 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 1266 unsigned FnSize = GetFunctionSizeInBytes(MF, TII); 1267 // Force LR to be spilled if the Thumb function size is > 2048. This enables 1268 // use of BL to implement far jump. If it turns out that it's not needed 1269 // then the branch fix up path will undo it. 1270 if (FnSize >= (1 << 11)) { 1271 CanEliminateFrame = false; 1272 ForceLRSpill = true; 1273 } 1274 } 1275 1276 // If any of the stack slot references may be out of range of an immediate 1277 // offset, make sure a register (or a spill slot) is available for the 1278 // register scavenger. Note that if we're indexing off the frame pointer, the 1279 // effective stack size is 4 bytes larger since the FP points to the stack 1280 // slot of the previous FP. Also, if we have variable sized objects in the 1281 // function, stack slot references will often be negative, and some of 1282 // our instructions are positive-offset only, so conservatively consider 1283 // that case to want a spill slot (or register) as well. Similarly, if 1284 // the function adjusts the stack pointer during execution and the 1285 // adjustments aren't already part of our stack size estimate, our offset 1286 // calculations may be off, so be conservative. 1287 // FIXME: We could add logic to be more precise about negative offsets 1288 // and which instructions will need a scratch register for them. Is it 1289 // worth the effort and added fragility? 1290 bool BigStack = 1291 (RS && 1292 (MFI->estimateStackSize(MF) + 1293 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >= 1294 estimateRSStackSizeLimit(MF, this))) 1295 || MFI->hasVarSizedObjects() 1296 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF)); 1297 1298 bool ExtraCSSpill = false; 1299 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 1300 AFI->setHasStackFrame(true); 1301 1302 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 1303 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 1304 if (!LRSpilled && CS1Spilled) { 1305 MRI.setPhysRegUsed(ARM::LR); 1306 NumGPRSpills++; 1307 SmallVectorImpl<unsigned>::iterator LRPos; 1308 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(), 1309 (unsigned)ARM::LR); 1310 if (LRPos != UnspilledCS1GPRs.end()) 1311 UnspilledCS1GPRs.erase(LRPos); 1312 1313 ForceLRSpill = false; 1314 ExtraCSSpill = true; 1315 } 1316 1317 if (hasFP(MF)) { 1318 MRI.setPhysRegUsed(FramePtr); 1319 NumGPRSpills++; 1320 } 1321 1322 // If stack and double are 8-byte aligned and we are spilling an odd number 1323 // of GPRs, spill one extra callee save GPR so we won't have to pad between 1324 // the integer and double callee save areas. 1325 unsigned TargetAlign = getStackAlignment(); 1326 if (TargetAlign == 8 && (NumGPRSpills & 1)) { 1327 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 1328 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) { 1329 unsigned Reg = UnspilledCS1GPRs[i]; 1330 // Don't spill high register if the function is thumb1 1331 if (!AFI->isThumb1OnlyFunction() || 1332 isARMLowRegister(Reg) || Reg == ARM::LR) { 1333 MRI.setPhysRegUsed(Reg); 1334 if (!MRI.isReserved(Reg)) 1335 ExtraCSSpill = true; 1336 break; 1337 } 1338 } 1339 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 1340 unsigned Reg = UnspilledCS2GPRs.front(); 1341 MRI.setPhysRegUsed(Reg); 1342 if (!MRI.isReserved(Reg)) 1343 ExtraCSSpill = true; 1344 } 1345 } 1346 1347 // Estimate if we might need to scavenge a register at some point in order 1348 // to materialize a stack offset. If so, either spill one additional 1349 // callee-saved register or reserve a special spill slot to facilitate 1350 // register scavenging. Thumb1 needs a spill slot for stack pointer 1351 // adjustments also, even when the frame itself is small. 1352 if (BigStack && !ExtraCSSpill) { 1353 // If any non-reserved CS register isn't spilled, just spill one or two 1354 // extra. That should take care of it! 1355 unsigned NumExtras = TargetAlign / 4; 1356 SmallVector<unsigned, 2> Extras; 1357 while (NumExtras && !UnspilledCS1GPRs.empty()) { 1358 unsigned Reg = UnspilledCS1GPRs.back(); 1359 UnspilledCS1GPRs.pop_back(); 1360 if (!MRI.isReserved(Reg) && 1361 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) || 1362 Reg == ARM::LR)) { 1363 Extras.push_back(Reg); 1364 NumExtras--; 1365 } 1366 } 1367 // For non-Thumb1 functions, also check for hi-reg CS registers 1368 if (!AFI->isThumb1OnlyFunction()) { 1369 while (NumExtras && !UnspilledCS2GPRs.empty()) { 1370 unsigned Reg = UnspilledCS2GPRs.back(); 1371 UnspilledCS2GPRs.pop_back(); 1372 if (!MRI.isReserved(Reg)) { 1373 Extras.push_back(Reg); 1374 NumExtras--; 1375 } 1376 } 1377 } 1378 if (Extras.size() && NumExtras == 0) { 1379 for (unsigned i = 0, e = Extras.size(); i != e; ++i) { 1380 MRI.setPhysRegUsed(Extras[i]); 1381 } 1382 } else if (!AFI->isThumb1OnlyFunction()) { 1383 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot 1384 // closest to SP or frame pointer. 1385 const TargetRegisterClass *RC = &ARM::GPRRegClass; 1386 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(), 1387 RC->getAlignment(), 1388 false)); 1389 } 1390 } 1391 } 1392 1393 if (ForceLRSpill) { 1394 MRI.setPhysRegUsed(ARM::LR); 1395 AFI->setLRIsSpilledForFarJump(true); 1396 } 1397 } 1398 1399 1400 void ARMFrameLowering:: 1401 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, 1402 MachineBasicBlock::iterator I) const { 1403 const ARMBaseInstrInfo &TII = 1404 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 1405 if (!hasReservedCallFrame(MF)) { 1406 // If we have alloca, convert as follows: 1407 // ADJCALLSTACKDOWN -> sub, sp, sp, amount 1408 // ADJCALLSTACKUP -> add, sp, sp, amount 1409 MachineInstr *Old = I; 1410 DebugLoc dl = Old->getDebugLoc(); 1411 unsigned Amount = Old->getOperand(0).getImm(); 1412 if (Amount != 0) { 1413 // We need to keep the stack aligned properly. To do this, we round the 1414 // amount of space needed for the outgoing arguments up to the next 1415 // alignment boundary. 1416 unsigned Align = getStackAlignment(); 1417 Amount = (Amount+Align-1)/Align*Align; 1418 1419 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1420 assert(!AFI->isThumb1OnlyFunction() && 1421 "This eliminateCallFramePseudoInstr does not support Thumb1!"); 1422 bool isARM = !AFI->isThumbFunction(); 1423 1424 // Replace the pseudo instruction with a new instruction... 1425 unsigned Opc = Old->getOpcode(); 1426 int PIdx = Old->findFirstPredOperandIdx(); 1427 ARMCC::CondCodes Pred = (PIdx == -1) 1428 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm(); 1429 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) { 1430 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN. 1431 unsigned PredReg = Old->getOperand(2).getReg(); 1432 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags, 1433 Pred, PredReg); 1434 } else { 1435 // Note: PredReg is operand 3 for ADJCALLSTACKUP. 1436 unsigned PredReg = Old->getOperand(3).getReg(); 1437 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP); 1438 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags, 1439 Pred, PredReg); 1440 } 1441 } 1442 } 1443 MBB.erase(I); 1444 } 1445 1446