1 //=======- ARMFrameLowering.cpp - ARM Frame Information --------*- C++ -*-====// 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 "ARMAddressingModes.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMMachineFunctionInfo.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/Target/TargetOptions.h" 25 26 using namespace llvm; 27 28 /// hasFP - Return true if the specified function should have a dedicated frame 29 /// pointer register. This is true if the function has variable sized allocas 30 /// or if frame pointer elimination is disabled. 31 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const { 32 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 33 34 // Mac OS X requires FP not to be clobbered for backtracing purpose. 35 if (STI.isTargetDarwin()) 36 return true; 37 38 const MachineFrameInfo *MFI = MF.getFrameInfo(); 39 // Always eliminate non-leaf frame pointers. 40 return ((DisableFramePointerElim(MF) && MFI->hasCalls()) || 41 RegInfo->needsStackRealignment(MF) || 42 MFI->hasVarSizedObjects() || 43 MFI->isFrameAddressTaken()); 44 } 45 46 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 47 /// not required, we reserve argument space for call sites in the function 48 /// immediately on entry to the current function. This eliminates the need for 49 /// add/sub sp brackets around call sites. Returns true if the call frame is 50 /// included as part of the stack frame. 51 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 52 const MachineFrameInfo *FFI = MF.getFrameInfo(); 53 unsigned CFSize = FFI->getMaxCallFrameSize(); 54 // It's not always a good idea to include the call frame as part of the 55 // stack frame. ARM (especially Thumb) has small immediate offset to 56 // address the stack frame. So a large call frame can cause poor codegen 57 // and may even makes it impossible to scavenge a register. 58 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 59 return false; 60 61 return !MF.getFrameInfo()->hasVarSizedObjects(); 62 } 63 64 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 65 /// call frame pseudos can be simplified. Unlike most targets, having a FP 66 /// is not sufficient here since we still may reference some objects via SP 67 /// even when FP is available in Thumb2 mode. 68 bool 69 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 70 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects(); 71 } 72 73 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) { 74 for (unsigned i = 0; CSRegs[i]; ++i) 75 if (Reg == CSRegs[i]) 76 return true; 77 return false; 78 } 79 80 static bool isCSRestore(MachineInstr *MI, 81 const ARMBaseInstrInfo &TII, 82 const unsigned *CSRegs) { 83 // Integer spill area is handled with "pop". 84 if (MI->getOpcode() == ARM::LDMIA_RET || 85 MI->getOpcode() == ARM::t2LDMIA_RET || 86 MI->getOpcode() == ARM::LDMIA_UPD || 87 MI->getOpcode() == ARM::t2LDMIA_UPD || 88 MI->getOpcode() == ARM::VLDMDIA_UPD) { 89 // The first two operands are predicates. The last two are 90 // imp-def and imp-use of SP. Check everything in between. 91 for (int i = 5, e = MI->getNumOperands(); i != e; ++i) 92 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs)) 93 return false; 94 return true; 95 } 96 if ((MI->getOpcode() == ARM::LDR_POST || 97 MI->getOpcode() == ARM::t2LDR_POST) && 98 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) && 99 MI->getOperand(1).getReg() == ARM::SP) 100 return true; 101 102 return false; 103 } 104 105 static void 106 emitSPUpdate(bool isARM, 107 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, 108 DebugLoc dl, const ARMBaseInstrInfo &TII, 109 int NumBytes, 110 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) { 111 if (isARM) 112 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, 113 Pred, PredReg, TII); 114 else 115 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, 116 Pred, PredReg, TII); 117 } 118 119 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const { 120 MachineBasicBlock &MBB = MF.front(); 121 MachineBasicBlock::iterator MBBI = MBB.begin(); 122 MachineFrameInfo *MFI = MF.getFrameInfo(); 123 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 124 const ARMBaseRegisterInfo *RegInfo = 125 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 126 const ARMBaseInstrInfo &TII = 127 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 128 assert(!AFI->isThumb1OnlyFunction() && 129 "This emitPrologue does not support Thumb1!"); 130 bool isARM = !AFI->isThumbFunction(); 131 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize(); 132 unsigned NumBytes = MFI->getStackSize(); 133 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 134 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 135 unsigned FramePtr = RegInfo->getFrameRegister(MF); 136 137 // Determine the sizes of each callee-save spill areas and record which frame 138 // belongs to which callee-save spill areas. 139 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 140 int FramePtrSpillFI = 0; 141 142 // Allocate the vararg register save area. This is not counted in NumBytes. 143 if (VARegSaveSize) 144 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize); 145 146 if (!AFI->hasStackFrame()) { 147 if (NumBytes != 0) 148 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes); 149 return; 150 } 151 152 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 153 unsigned Reg = CSI[i].getReg(); 154 int FI = CSI[i].getFrameIdx(); 155 switch (Reg) { 156 case ARM::R4: 157 case ARM::R5: 158 case ARM::R6: 159 case ARM::R7: 160 case ARM::LR: 161 if (Reg == FramePtr) 162 FramePtrSpillFI = FI; 163 AFI->addGPRCalleeSavedArea1Frame(FI); 164 GPRCS1Size += 4; 165 break; 166 case ARM::R8: 167 case ARM::R9: 168 case ARM::R10: 169 case ARM::R11: 170 if (Reg == FramePtr) 171 FramePtrSpillFI = FI; 172 if (STI.isTargetDarwin()) { 173 AFI->addGPRCalleeSavedArea2Frame(FI); 174 GPRCS2Size += 4; 175 } else { 176 AFI->addGPRCalleeSavedArea1Frame(FI); 177 GPRCS1Size += 4; 178 } 179 break; 180 default: 181 AFI->addDPRCalleeSavedAreaFrame(FI); 182 DPRCSSize += 8; 183 } 184 } 185 186 // Move past area 1. 187 if (GPRCS1Size > 0) MBBI++; 188 189 // Set FP to point to the stack slot that contains the previous FP. 190 // For Darwin, FP is R7, which has now been stored in spill area 1. 191 // Otherwise, if this is not Darwin, all the callee-saved registers go 192 // into spill area 1, including the FP in R11. In either case, it is 193 // now safe to emit this assignment. 194 bool HasFP = hasFP(MF); 195 if (HasFP) { 196 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri; 197 MachineInstrBuilder MIB = 198 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr) 199 .addFrameIndex(FramePtrSpillFI).addImm(0); 200 AddDefaultCC(AddDefaultPred(MIB)); 201 } 202 203 // Move past area 2. 204 if (GPRCS2Size > 0) MBBI++; 205 206 // Determine starting offsets of spill areas. 207 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize); 208 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize; 209 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size; 210 if (HasFP) 211 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + 212 NumBytes); 213 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 214 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 215 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 216 217 // Move past area 3. 218 if (DPRCSSize > 0) { 219 MBBI++; 220 // Since vpush register list cannot have gaps, there may be multiple vpush 221 // instructions in the prologue. 222 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) 223 MBBI++; 224 } 225 226 NumBytes = DPRCSOffset; 227 if (NumBytes) { 228 // Adjust SP after all the callee-save spills. 229 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes); 230 if (HasFP && isARM) 231 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 232 // Note it's not safe to do this in Thumb2 mode because it would have 233 // taken two instructions: 234 // mov sp, r7 235 // sub sp, #24 236 // If an interrupt is taken between the two instructions, then sp is in 237 // an inconsistent state (pointing to the middle of callee-saved area). 238 // The interrupt handler can end up clobbering the registers. 239 AFI->setShouldRestoreSPFromFP(true); 240 } 241 242 if (STI.isTargetELF() && hasFP(MF)) 243 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() - 244 AFI->getFramePtrSpillOffset()); 245 246 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 247 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 248 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 249 250 // If we need dynamic stack realignment, do it here. Be paranoid and make 251 // sure if we also have VLAs, we have a base pointer for frame access. 252 if (RegInfo->needsStackRealignment(MF)) { 253 unsigned MaxAlign = MFI->getMaxAlignment(); 254 assert (!AFI->isThumb1OnlyFunction()); 255 if (!AFI->isThumbFunction()) { 256 // Emit bic sp, sp, MaxAlign 257 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 258 TII.get(ARM::BICri), ARM::SP) 259 .addReg(ARM::SP, RegState::Kill) 260 .addImm(MaxAlign-1))); 261 } else { 262 // We cannot use sp as source/dest register here, thus we're emitting the 263 // following sequence: 264 // mov r4, sp 265 // bic r4, r4, MaxAlign 266 // mov sp, r4 267 // FIXME: It will be better just to find spare register here. 268 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4) 269 .addReg(ARM::SP, RegState::Kill); 270 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 271 TII.get(ARM::t2BICri), ARM::R4) 272 .addReg(ARM::R4, RegState::Kill) 273 .addImm(MaxAlign-1))); 274 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP) 275 .addReg(ARM::R4, RegState::Kill); 276 } 277 278 AFI->setShouldRestoreSPFromFP(true); 279 } 280 281 // If we need a base pointer, set it up here. It's whatever the value 282 // of the stack pointer is at this point. Any variable size objects 283 // will be allocated after this, so we can still use the base pointer 284 // to reference locals. 285 if (RegInfo->hasBasePointer(MF)) { 286 if (isARM) 287 BuildMI(MBB, MBBI, dl, 288 TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 289 .addReg(ARM::SP) 290 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 291 else 292 BuildMI(MBB, MBBI, dl, 293 TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister()) 294 .addReg(ARM::SP); 295 } 296 297 // If the frame has variable sized objects then the epilogue must restore 298 // the sp from fp. We can assume there's an FP here since hasFP already 299 // checks for hasVarSizedObjects. 300 if (MFI->hasVarSizedObjects()) 301 AFI->setShouldRestoreSPFromFP(true); 302 } 303 304 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 305 MachineBasicBlock &MBB) const { 306 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 307 assert(MBBI->getDesc().isReturn() && 308 "Can only insert epilog into returning blocks"); 309 unsigned RetOpcode = MBBI->getOpcode(); 310 DebugLoc dl = MBBI->getDebugLoc(); 311 MachineFrameInfo *MFI = MF.getFrameInfo(); 312 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 313 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 314 const ARMBaseInstrInfo &TII = 315 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 316 assert(!AFI->isThumb1OnlyFunction() && 317 "This emitEpilogue does not support Thumb1!"); 318 bool isARM = !AFI->isThumbFunction(); 319 320 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize(); 321 int NumBytes = (int)MFI->getStackSize(); 322 unsigned FramePtr = RegInfo->getFrameRegister(MF); 323 324 if (!AFI->hasStackFrame()) { 325 if (NumBytes != 0) 326 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 327 } else { 328 // Unwind MBBI to point to first LDR / VLDRD. 329 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(); 330 if (MBBI != MBB.begin()) { 331 do 332 --MBBI; 333 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs)); 334 if (!isCSRestore(MBBI, TII, CSRegs)) 335 ++MBBI; 336 } 337 338 // Move SP to start of FP callee save spill area. 339 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() + 340 AFI->getGPRCalleeSavedArea2Size() + 341 AFI->getDPRCalleeSavedAreaSize()); 342 343 // Reset SP based on frame pointer only if the stack frame extends beyond 344 // frame pointer stack slot or target is ELF and the function has FP. 345 if (AFI->shouldRestoreSPFromFP()) { 346 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 347 if (NumBytes) { 348 if (isARM) 349 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 350 ARMCC::AL, 0, TII); 351 else { 352 // It's not possible to restore SP from FP in a single instruction. 353 // For Darwin, this looks like: 354 // mov sp, r7 355 // sub sp, #24 356 // This is bad, if an interrupt is taken after the mov, sp is in an 357 // inconsistent state. 358 // Use the first callee-saved register as a scratch register. 359 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) && 360 "No scratch register to restore SP from FP!"); 361 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 362 ARMCC::AL, 0, TII); 363 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP) 364 .addReg(ARM::R4); 365 } 366 } else { 367 // Thumb2 or ARM. 368 if (isARM) 369 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 370 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 371 else 372 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP) 373 .addReg(FramePtr); 374 } 375 } else if (NumBytes) 376 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 377 378 // Increment past our save areas. 379 if (AFI->getDPRCalleeSavedAreaSize()) { 380 MBBI++; 381 // Since vpop register list cannot have gaps, there may be multiple vpop 382 // instructions in the epilogue. 383 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD) 384 MBBI++; 385 } 386 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++; 387 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 388 } 389 390 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND || 391 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) { 392 // Tail call return: adjust the stack pointer and jump to callee. 393 MBBI = MBB.getLastNonDebugInstr(); 394 MachineOperand &JumpTarget = MBBI->getOperand(0); 395 396 // Jump to label or value in register. 397 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) { 398 unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi) 399 ? (STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd) 400 : (STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND); 401 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode)); 402 if (JumpTarget.isGlobal()) 403 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), 404 JumpTarget.getTargetFlags()); 405 else { 406 assert(JumpTarget.isSymbol()); 407 MIB.addExternalSymbol(JumpTarget.getSymbolName(), 408 JumpTarget.getTargetFlags()); 409 } 410 } else if (RetOpcode == ARM::TCRETURNri) { 411 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)). 412 addReg(JumpTarget.getReg(), RegState::Kill); 413 } else if (RetOpcode == ARM::TCRETURNriND) { 414 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)). 415 addReg(JumpTarget.getReg(), RegState::Kill); 416 } 417 418 MachineInstr *NewMI = prior(MBBI); 419 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i) 420 NewMI->addOperand(MBBI->getOperand(i)); 421 422 // Delete the pseudo instruction TCRETURN. 423 MBB.erase(MBBI); 424 } 425 426 if (VARegSaveSize) 427 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize); 428 } 429 430 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 431 /// debug info. It's the same as what we use for resolving the code-gen 432 /// references for now. FIXME: This can go wrong when references are 433 /// SP-relative and simple call frames aren't used. 434 int 435 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 436 unsigned &FrameReg) const { 437 return ResolveFrameIndexReference(MF, FI, FrameReg, 0); 438 } 439 440 int 441 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 442 int FI, 443 unsigned &FrameReg, 444 int SPAdj) const { 445 const MachineFrameInfo *MFI = MF.getFrameInfo(); 446 const ARMBaseRegisterInfo *RegInfo = 447 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 448 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 449 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize(); 450 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 451 bool isFixed = MFI->isFixedObjectIndex(FI); 452 453 FrameReg = ARM::SP; 454 Offset += SPAdj; 455 if (AFI->isGPRCalleeSavedArea1Frame(FI)) 456 return Offset - AFI->getGPRCalleeSavedArea1Offset(); 457 else if (AFI->isGPRCalleeSavedArea2Frame(FI)) 458 return Offset - AFI->getGPRCalleeSavedArea2Offset(); 459 else if (AFI->isDPRCalleeSavedAreaFrame(FI)) 460 return Offset - AFI->getDPRCalleeSavedAreaOffset(); 461 462 // When dynamically realigning the stack, use the frame pointer for 463 // parameters, and the stack/base pointer for locals. 464 if (RegInfo->needsStackRealignment(MF)) { 465 assert (hasFP(MF) && "dynamic stack realignment without a FP!"); 466 if (isFixed) { 467 FrameReg = RegInfo->getFrameRegister(MF); 468 Offset = FPOffset; 469 } else if (MFI->hasVarSizedObjects()) { 470 assert(RegInfo->hasBasePointer(MF) && 471 "VLAs and dynamic stack alignment, but missing base pointer!"); 472 FrameReg = RegInfo->getBaseRegister(); 473 } 474 return Offset; 475 } 476 477 // If there is a frame pointer, use it when we can. 478 if (hasFP(MF) && AFI->hasStackFrame()) { 479 // Use frame pointer to reference fixed objects. Use it for locals if 480 // there are VLAs (and thus the SP isn't reliable as a base). 481 if (isFixed || (MFI->hasVarSizedObjects() && 482 !RegInfo->hasBasePointer(MF))) { 483 FrameReg = RegInfo->getFrameRegister(MF); 484 return FPOffset; 485 } else if (MFI->hasVarSizedObjects()) { 486 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 487 // Try to use the frame pointer if we can, else use the base pointer 488 // since it's available. This is handy for the emergency spill slot, in 489 // particular. 490 if (AFI->isThumb2Function()) { 491 if (FPOffset >= -255 && FPOffset < 0) { 492 FrameReg = RegInfo->getFrameRegister(MF); 493 return FPOffset; 494 } 495 } else 496 FrameReg = RegInfo->getBaseRegister(); 497 } else if (AFI->isThumb2Function()) { 498 // In Thumb2 mode, the negative offset is very limited. Try to avoid 499 // out of range references. 500 if (FPOffset >= -255 && FPOffset < 0) { 501 FrameReg = RegInfo->getFrameRegister(MF); 502 return FPOffset; 503 } 504 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 505 // Otherwise, use SP or FP, whichever is closer to the stack slot. 506 FrameReg = RegInfo->getFrameRegister(MF); 507 return FPOffset; 508 } 509 } 510 // Use the base pointer if we have one. 511 if (RegInfo->hasBasePointer(MF)) 512 FrameReg = RegInfo->getBaseRegister(); 513 return Offset; 514 } 515 516 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF, 517 int FI) const { 518 unsigned FrameReg; 519 return getFrameIndexReference(MF, FI, FrameReg); 520 } 521 522 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 523 MachineBasicBlock::iterator MI, 524 const std::vector<CalleeSavedInfo> &CSI, 525 unsigned StmOpc, unsigned StrOpc, 526 bool NoGap, 527 bool(*Func)(unsigned, bool)) const { 528 MachineFunction &MF = *MBB.getParent(); 529 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 530 531 DebugLoc DL; 532 if (MI != MBB.end()) DL = MI->getDebugLoc(); 533 534 SmallVector<std::pair<unsigned,bool>, 4> Regs; 535 unsigned i = CSI.size(); 536 while (i != 0) { 537 unsigned LastReg = 0; 538 for (; i != 0; --i) { 539 unsigned Reg = CSI[i-1].getReg(); 540 if (!(Func)(Reg, STI.isTargetDarwin())) continue; 541 542 // Add the callee-saved register as live-in unless it's LR and 543 // @llvm.returnaddress is called. If LR is returned for 544 // @llvm.returnaddress then it's already added to the function and 545 // entry block live-in sets. 546 bool isKill = true; 547 if (Reg == ARM::LR) { 548 if (MF.getFrameInfo()->isReturnAddressTaken() && 549 MF.getRegInfo().isLiveIn(Reg)) 550 isKill = false; 551 } 552 553 if (isKill) 554 MBB.addLiveIn(Reg); 555 556 // If NoGap is true, push consecutive registers and then leave the rest 557 // for other instructions. e.g. 558 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 559 if (NoGap && LastReg && LastReg != Reg-1) 560 break; 561 LastReg = Reg; 562 Regs.push_back(std::make_pair(Reg, isKill)); 563 } 564 565 if (Regs.empty()) 566 continue; 567 if (Regs.size() > 1 || StrOpc== 0) { 568 MachineInstrBuilder MIB = 569 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 570 .addReg(ARM::SP)); 571 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 572 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 573 } else if (Regs.size() == 1) { 574 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc), 575 ARM::SP) 576 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 577 .addReg(ARM::SP); 578 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 579 // that refactoring is complete (eventually). 580 if (StrOpc == ARM::STR_PRE) { 581 MIB.addReg(0); 582 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::sub, 4, ARM_AM::no_shift)); 583 } else 584 MIB.addImm(-4); 585 AddDefaultPred(MIB); 586 } 587 Regs.clear(); 588 } 589 } 590 591 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 592 MachineBasicBlock::iterator MI, 593 const std::vector<CalleeSavedInfo> &CSI, 594 unsigned LdmOpc, unsigned LdrOpc, 595 bool isVarArg, bool NoGap, 596 bool(*Func)(unsigned, bool)) const { 597 MachineFunction &MF = *MBB.getParent(); 598 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 600 DebugLoc DL = MI->getDebugLoc(); 601 unsigned RetOpcode = MI->getOpcode(); 602 bool isTailCall = (RetOpcode == ARM::TCRETURNdi || 603 RetOpcode == ARM::TCRETURNdiND || 604 RetOpcode == ARM::TCRETURNri || 605 RetOpcode == ARM::TCRETURNriND); 606 607 SmallVector<unsigned, 4> Regs; 608 unsigned i = CSI.size(); 609 while (i != 0) { 610 unsigned LastReg = 0; 611 bool DeleteRet = false; 612 for (; i != 0; --i) { 613 unsigned Reg = CSI[i-1].getReg(); 614 if (!(Func)(Reg, STI.isTargetDarwin())) continue; 615 616 if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) { 617 Reg = ARM::PC; 618 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 619 // Fold the return instruction into the LDM. 620 DeleteRet = true; 621 } 622 623 // If NoGap is true, pop consecutive registers and then leave the rest 624 // for other instructions. e.g. 625 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 626 if (NoGap && LastReg && LastReg != Reg-1) 627 break; 628 629 LastReg = Reg; 630 Regs.push_back(Reg); 631 } 632 633 if (Regs.empty()) 634 continue; 635 if (Regs.size() > 1 || LdrOpc == 0) { 636 MachineInstrBuilder MIB = 637 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 638 .addReg(ARM::SP)); 639 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 640 MIB.addReg(Regs[i], getDefRegState(true)); 641 if (DeleteRet) 642 MI->eraseFromParent(); 643 MI = MIB; 644 } else if (Regs.size() == 1) { 645 // If we adjusted the reg to PC from LR above, switch it back here. We 646 // only do that for LDM. 647 if (Regs[0] == ARM::PC) 648 Regs[0] = ARM::LR; 649 MachineInstrBuilder MIB = 650 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 651 .addReg(ARM::SP, RegState::Define) 652 .addReg(ARM::SP); 653 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 654 // that refactoring is complete (eventually). 655 if (LdrOpc == ARM::LDR_POST) { 656 MIB.addReg(0); 657 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 658 } else 659 MIB.addImm(4); 660 AddDefaultPred(MIB); 661 } 662 Regs.clear(); 663 } 664 } 665 666 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB, 667 MachineBasicBlock::iterator MI, 668 const std::vector<CalleeSavedInfo> &CSI, 669 const TargetRegisterInfo *TRI) const { 670 if (CSI.empty()) 671 return false; 672 673 MachineFunction &MF = *MBB.getParent(); 674 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 675 676 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 677 unsigned PushOneOpc = AFI->isThumbFunction() ? ARM::t2STR_PRE : ARM::STR_PRE; 678 unsigned FltOpc = ARM::VSTMDDB_UPD; 679 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register); 680 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register); 681 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register); 682 683 return true; 684 } 685 686 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB, 687 MachineBasicBlock::iterator MI, 688 const std::vector<CalleeSavedInfo> &CSI, 689 const TargetRegisterInfo *TRI) const { 690 if (CSI.empty()) 691 return false; 692 693 MachineFunction &MF = *MBB.getParent(); 694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 695 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0; 696 697 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 698 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST; 699 unsigned FltOpc = ARM::VLDMDIA_UPD; 700 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register); 701 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 702 &isARMArea2Register); 703 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 704 &isARMArea1Register); 705 706 return true; 707 } 708 709 // FIXME: Make generic? 710 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF, 711 const ARMBaseInstrInfo &TII) { 712 unsigned FnSize = 0; 713 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end(); 714 MBBI != E; ++MBBI) { 715 const MachineBasicBlock &MBB = *MBBI; 716 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end(); 717 I != E; ++I) 718 FnSize += TII.GetInstSizeInBytes(I); 719 } 720 return FnSize; 721 } 722 723 /// estimateStackSize - Estimate and return the size of the frame. 724 /// FIXME: Make generic? 725 static unsigned estimateStackSize(MachineFunction &MF) { 726 const MachineFrameInfo *FFI = MF.getFrameInfo(); 727 int Offset = 0; 728 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) { 729 int FixedOff = -FFI->getObjectOffset(i); 730 if (FixedOff > Offset) Offset = FixedOff; 731 } 732 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { 733 if (FFI->isDeadObjectIndex(i)) 734 continue; 735 Offset += FFI->getObjectSize(i); 736 unsigned Align = FFI->getObjectAlignment(i); 737 // Adjust to alignment boundary 738 Offset = (Offset+Align-1)/Align*Align; 739 } 740 return (unsigned)Offset; 741 } 742 743 /// estimateRSStackSizeLimit - Look at each instruction that references stack 744 /// frames and return the stack size limit beyond which some of these 745 /// instructions will require a scratch register during their expansion later. 746 // FIXME: Move to TII? 747 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 748 const TargetFrameLowering *TFI) { 749 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 750 unsigned Limit = (1 << 12) - 1; 751 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) { 752 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); 753 I != E; ++I) { 754 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 755 if (!I->getOperand(i).isFI()) continue; 756 757 // When using ADDri to get the address of a stack object, 255 is the 758 // largest offset guaranteed to fit in the immediate offset. 759 if (I->getOpcode() == ARM::ADDri) { 760 Limit = std::min(Limit, (1U << 8) - 1); 761 break; 762 } 763 764 // Otherwise check the addressing mode. 765 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) { 766 case ARMII::AddrMode3: 767 case ARMII::AddrModeT2_i8: 768 Limit = std::min(Limit, (1U << 8) - 1); 769 break; 770 case ARMII::AddrMode5: 771 case ARMII::AddrModeT2_i8s4: 772 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 773 break; 774 case ARMII::AddrModeT2_i12: 775 // i12 supports only positive offset so these will be converted to 776 // i8 opcodes. See llvm::rewriteT2FrameIndex. 777 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 778 Limit = std::min(Limit, (1U << 8) - 1); 779 break; 780 case ARMII::AddrMode4: 781 case ARMII::AddrMode6: 782 // Addressing modes 4 & 6 (load/store) instructions can't encode an 783 // immediate offset for stack references. 784 return 0; 785 default: 786 break; 787 } 788 break; // At most one FI per instruction 789 } 790 } 791 } 792 793 return Limit; 794 } 795 796 void 797 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF, 798 RegScavenger *RS) const { 799 // This tells PEI to spill the FP as if it is any other callee-save register 800 // to take advantage the eliminateFrameIndex machinery. This also ensures it 801 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 802 // to combine multiple loads / stores. 803 bool CanEliminateFrame = true; 804 bool CS1Spilled = false; 805 bool LRSpilled = false; 806 unsigned NumGPRSpills = 0; 807 SmallVector<unsigned, 4> UnspilledCS1GPRs; 808 SmallVector<unsigned, 4> UnspilledCS2GPRs; 809 const ARMBaseRegisterInfo *RegInfo = 810 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 811 const ARMBaseInstrInfo &TII = 812 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 813 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 814 MachineFrameInfo *MFI = MF.getFrameInfo(); 815 unsigned FramePtr = RegInfo->getFrameRegister(MF); 816 817 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 818 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 819 // since it's not always possible to restore sp from fp in a single 820 // instruction. 821 // FIXME: It will be better just to find spare register here. 822 if (AFI->isThumb2Function() && 823 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF))) 824 MF.getRegInfo().setPhysRegUsed(ARM::R4); 825 826 if (AFI->isThumb1OnlyFunction()) { 827 // Spill LR if Thumb1 function uses variable length argument lists. 828 if (AFI->getVarArgsRegSaveSize() > 0) 829 MF.getRegInfo().setPhysRegUsed(ARM::LR); 830 831 // Spill R4 if Thumb1 epilogue has to restore SP from FP since 832 // FIXME: It will be better just to find spare register here. 833 if (MFI->hasVarSizedObjects()) 834 MF.getRegInfo().setPhysRegUsed(ARM::R4); 835 } 836 837 // Spill the BasePtr if it's used. 838 if (RegInfo->hasBasePointer(MF)) 839 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister()); 840 841 // Don't spill FP if the frame can be eliminated. This is determined 842 // by scanning the callee-save registers to see if any is used. 843 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(); 844 for (unsigned i = 0; CSRegs[i]; ++i) { 845 unsigned Reg = CSRegs[i]; 846 bool Spilled = false; 847 if (MF.getRegInfo().isPhysRegUsed(Reg)) { 848 Spilled = true; 849 CanEliminateFrame = false; 850 } else { 851 // Check alias registers too. 852 for (const unsigned *Aliases = 853 RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) { 854 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) { 855 Spilled = true; 856 CanEliminateFrame = false; 857 } 858 } 859 } 860 861 if (!ARM::GPRRegisterClass->contains(Reg)) 862 continue; 863 864 if (Spilled) { 865 NumGPRSpills++; 866 867 if (!STI.isTargetDarwin()) { 868 if (Reg == ARM::LR) 869 LRSpilled = true; 870 CS1Spilled = true; 871 continue; 872 } 873 874 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 875 switch (Reg) { 876 case ARM::LR: 877 LRSpilled = true; 878 // Fallthrough 879 case ARM::R4: case ARM::R5: 880 case ARM::R6: case ARM::R7: 881 CS1Spilled = true; 882 break; 883 default: 884 break; 885 } 886 } else { 887 if (!STI.isTargetDarwin()) { 888 UnspilledCS1GPRs.push_back(Reg); 889 continue; 890 } 891 892 switch (Reg) { 893 case ARM::R4: case ARM::R5: 894 case ARM::R6: case ARM::R7: 895 case ARM::LR: 896 UnspilledCS1GPRs.push_back(Reg); 897 break; 898 default: 899 UnspilledCS2GPRs.push_back(Reg); 900 break; 901 } 902 } 903 } 904 905 bool ForceLRSpill = false; 906 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 907 unsigned FnSize = GetFunctionSizeInBytes(MF, TII); 908 // Force LR to be spilled if the Thumb function size is > 2048. This enables 909 // use of BL to implement far jump. If it turns out that it's not needed 910 // then the branch fix up path will undo it. 911 if (FnSize >= (1 << 11)) { 912 CanEliminateFrame = false; 913 ForceLRSpill = true; 914 } 915 } 916 917 // If any of the stack slot references may be out of range of an immediate 918 // offset, make sure a register (or a spill slot) is available for the 919 // register scavenger. Note that if we're indexing off the frame pointer, the 920 // effective stack size is 4 bytes larger since the FP points to the stack 921 // slot of the previous FP. Also, if we have variable sized objects in the 922 // function, stack slot references will often be negative, and some of 923 // our instructions are positive-offset only, so conservatively consider 924 // that case to want a spill slot (or register) as well. Similarly, if 925 // the function adjusts the stack pointer during execution and the 926 // adjustments aren't already part of our stack size estimate, our offset 927 // calculations may be off, so be conservative. 928 // FIXME: We could add logic to be more precise about negative offsets 929 // and which instructions will need a scratch register for them. Is it 930 // worth the effort and added fragility? 931 bool BigStack = 932 (RS && 933 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >= 934 estimateRSStackSizeLimit(MF, this))) 935 || MFI->hasVarSizedObjects() 936 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF)); 937 938 bool ExtraCSSpill = false; 939 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 940 AFI->setHasStackFrame(true); 941 942 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 943 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 944 if (!LRSpilled && CS1Spilled) { 945 MF.getRegInfo().setPhysRegUsed(ARM::LR); 946 NumGPRSpills++; 947 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(), 948 UnspilledCS1GPRs.end(), (unsigned)ARM::LR)); 949 ForceLRSpill = false; 950 ExtraCSSpill = true; 951 } 952 953 if (hasFP(MF)) { 954 MF.getRegInfo().setPhysRegUsed(FramePtr); 955 NumGPRSpills++; 956 } 957 958 // If stack and double are 8-byte aligned and we are spilling an odd number 959 // of GPRs, spill one extra callee save GPR so we won't have to pad between 960 // the integer and double callee save areas. 961 unsigned TargetAlign = getStackAlignment(); 962 if (TargetAlign == 8 && (NumGPRSpills & 1)) { 963 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 964 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) { 965 unsigned Reg = UnspilledCS1GPRs[i]; 966 // Don't spill high register if the function is thumb1 967 if (!AFI->isThumb1OnlyFunction() || 968 isARMLowRegister(Reg) || Reg == ARM::LR) { 969 MF.getRegInfo().setPhysRegUsed(Reg); 970 if (!RegInfo->isReservedReg(MF, Reg)) 971 ExtraCSSpill = true; 972 break; 973 } 974 } 975 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 976 unsigned Reg = UnspilledCS2GPRs.front(); 977 MF.getRegInfo().setPhysRegUsed(Reg); 978 if (!RegInfo->isReservedReg(MF, Reg)) 979 ExtraCSSpill = true; 980 } 981 } 982 983 // Estimate if we might need to scavenge a register at some point in order 984 // to materialize a stack offset. If so, either spill one additional 985 // callee-saved register or reserve a special spill slot to facilitate 986 // register scavenging. Thumb1 needs a spill slot for stack pointer 987 // adjustments also, even when the frame itself is small. 988 if (BigStack && !ExtraCSSpill) { 989 // If any non-reserved CS register isn't spilled, just spill one or two 990 // extra. That should take care of it! 991 unsigned NumExtras = TargetAlign / 4; 992 SmallVector<unsigned, 2> Extras; 993 while (NumExtras && !UnspilledCS1GPRs.empty()) { 994 unsigned Reg = UnspilledCS1GPRs.back(); 995 UnspilledCS1GPRs.pop_back(); 996 if (!RegInfo->isReservedReg(MF, Reg) && 997 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) || 998 Reg == ARM::LR)) { 999 Extras.push_back(Reg); 1000 NumExtras--; 1001 } 1002 } 1003 // For non-Thumb1 functions, also check for hi-reg CS registers 1004 if (!AFI->isThumb1OnlyFunction()) { 1005 while (NumExtras && !UnspilledCS2GPRs.empty()) { 1006 unsigned Reg = UnspilledCS2GPRs.back(); 1007 UnspilledCS2GPRs.pop_back(); 1008 if (!RegInfo->isReservedReg(MF, Reg)) { 1009 Extras.push_back(Reg); 1010 NumExtras--; 1011 } 1012 } 1013 } 1014 if (Extras.size() && NumExtras == 0) { 1015 for (unsigned i = 0, e = Extras.size(); i != e; ++i) { 1016 MF.getRegInfo().setPhysRegUsed(Extras[i]); 1017 } 1018 } else if (!AFI->isThumb1OnlyFunction()) { 1019 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot 1020 // closest to SP or frame pointer. 1021 const TargetRegisterClass *RC = ARM::GPRRegisterClass; 1022 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(), 1023 RC->getAlignment(), 1024 false)); 1025 } 1026 } 1027 } 1028 1029 if (ForceLRSpill) { 1030 MF.getRegInfo().setPhysRegUsed(ARM::LR); 1031 AFI->setLRIsSpilledForFarJump(true); 1032 } 1033 } 1034