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 "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "MCTargetDesc/ARMAddressingModes.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/RegisterScavenging.h" 26 #include "llvm/IR/CallingConv.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Target/TargetOptions.h" 31 32 using namespace llvm; 33 34 static cl::opt<bool> 35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), 36 cl::desc("Align ARM NEON spills in prolog and epilog")); 37 38 static MachineBasicBlock::iterator 39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 40 unsigned NumAlignedDPRCS2Regs); 41 42 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti) 43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4), 44 STI(sti) {} 45 46 /// hasFP - Return true if the specified function should have a dedicated frame 47 /// pointer register. This is true if the function has variable sized allocas 48 /// or if frame pointer elimination is disabled. 49 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const { 50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 51 52 // iOS requires FP not to be clobbered for backtracing purpose. 53 if (STI.isTargetIOS()) 54 return true; 55 56 const MachineFrameInfo *MFI = MF.getFrameInfo(); 57 // Always eliminate non-leaf frame pointers. 58 return ((MF.getTarget().Options.DisableFramePointerElim(MF) && 59 MFI->hasCalls()) || 60 RegInfo->needsStackRealignment(MF) || 61 MFI->hasVarSizedObjects() || 62 MFI->isFrameAddressTaken()); 63 } 64 65 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 66 /// not required, we reserve argument space for call sites in the function 67 /// immediately on entry to the current function. This eliminates the need for 68 /// add/sub sp brackets around call sites. Returns true if the call frame is 69 /// included as part of the stack frame. 70 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 71 const MachineFrameInfo *FFI = MF.getFrameInfo(); 72 unsigned CFSize = FFI->getMaxCallFrameSize(); 73 // It's not always a good idea to include the call frame as part of the 74 // stack frame. ARM (especially Thumb) has small immediate offset to 75 // address the stack frame. So a large call frame can cause poor codegen 76 // and may even makes it impossible to scavenge a register. 77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 78 return false; 79 80 return !MF.getFrameInfo()->hasVarSizedObjects(); 81 } 82 83 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 84 /// call frame pseudos can be simplified. Unlike most targets, having a FP 85 /// is not sufficient here since we still may reference some objects via SP 86 /// even when FP is available in Thumb2 mode. 87 bool 88 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 89 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects(); 90 } 91 92 static bool isCSRestore(MachineInstr *MI, 93 const ARMBaseInstrInfo &TII, 94 const MCPhysReg *CSRegs) { 95 // Integer spill area is handled with "pop". 96 if (isPopOpcode(MI->getOpcode())) { 97 // The first two operands are predicates. The last two are 98 // imp-def and imp-use of SP. Check everything in between. 99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i) 100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs)) 101 return false; 102 return true; 103 } 104 if ((MI->getOpcode() == ARM::LDR_POST_IMM || 105 MI->getOpcode() == ARM::LDR_POST_REG || 106 MI->getOpcode() == ARM::t2LDR_POST) && 107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) && 108 MI->getOperand(1).getReg() == ARM::SP) 109 return true; 110 111 return false; 112 } 113 114 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB, 115 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 116 const ARMBaseInstrInfo &TII, unsigned DestReg, 117 unsigned SrcReg, int NumBytes, 118 unsigned MIFlags = MachineInstr::NoFlags, 119 ARMCC::CondCodes Pred = ARMCC::AL, 120 unsigned PredReg = 0) { 121 if (isARM) 122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 123 Pred, PredReg, TII, MIFlags); 124 else 125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 126 Pred, PredReg, TII, MIFlags); 127 } 128 129 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, 130 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 131 const ARMBaseInstrInfo &TII, int NumBytes, 132 unsigned MIFlags = MachineInstr::NoFlags, 133 ARMCC::CondCodes Pred = ARMCC::AL, 134 unsigned PredReg = 0) { 135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes, 136 MIFlags, Pred, PredReg); 137 } 138 139 static int sizeOfSPAdjustment(const MachineInstr *MI) { 140 int RegSize; 141 switch (MI->getOpcode()) { 142 case ARM::VSTMDDB_UPD: 143 RegSize = 8; 144 break; 145 case ARM::STMDB_UPD: 146 case ARM::t2STMDB_UPD: 147 RegSize = 4; 148 break; 149 case ARM::t2STR_PRE: 150 case ARM::STR_PRE_IMM: 151 return 4; 152 default: 153 llvm_unreachable("Unknown push or pop like instruction"); 154 } 155 156 int count = 0; 157 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 158 // pred) so the list starts at 4. 159 for (int i = MI->getNumOperands() - 1; i >= 4; --i) 160 count += RegSize; 161 return count; 162 } 163 164 static bool WindowsRequiresStackProbe(const MachineFunction &MF, 165 size_t StackSizeInBytes) { 166 const MachineFrameInfo *MFI = MF.getFrameInfo(); 167 const Function *F = MF.getFunction(); 168 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096; 169 if (F->hasFnAttribute("stack-probe-size")) 170 F->getFnAttribute("stack-probe-size") 171 .getValueAsString() 172 .getAsInteger(0, StackProbeSize); 173 return StackSizeInBytes >= StackProbeSize; 174 } 175 176 namespace { 177 struct StackAdjustingInsts { 178 struct InstInfo { 179 MachineBasicBlock::iterator I; 180 unsigned SPAdjust; 181 bool BeforeFPSet; 182 }; 183 184 SmallVector<InstInfo, 4> Insts; 185 186 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust, 187 bool BeforeFPSet = false) { 188 InstInfo Info = {I, SPAdjust, BeforeFPSet}; 189 Insts.push_back(Info); 190 } 191 192 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) { 193 auto Info = std::find_if(Insts.begin(), Insts.end(), 194 [&](InstInfo &Info) { return Info.I == I; }); 195 assert(Info != Insts.end() && "invalid sp adjusting instruction"); 196 Info->SPAdjust += ExtraBytes; 197 } 198 199 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB, 200 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) { 201 unsigned CFAOffset = 0; 202 for (auto &Info : Insts) { 203 if (HasFP && !Info.BeforeFPSet) 204 return; 205 206 CFAOffset -= Info.SPAdjust; 207 unsigned CFIIndex = MMI.addFrameInst( 208 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 209 BuildMI(MBB, std::next(Info.I), dl, 210 TII.get(TargetOpcode::CFI_INSTRUCTION)) 211 .addCFIIndex(CFIIndex) 212 .setMIFlags(MachineInstr::FrameSetup); 213 } 214 } 215 }; 216 } 217 218 /// Emit an instruction sequence that will align the address in 219 /// register Reg by zero-ing out the lower bits. For versions of the 220 /// architecture that support Neon, this must be done in a single 221 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a 222 /// single instruction. That function only gets called when optimizing 223 /// spilling of D registers on a core with the Neon instruction set 224 /// present. 225 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI, 226 const TargetInstrInfo &TII, 227 MachineBasicBlock &MBB, 228 MachineBasicBlock::iterator MBBI, 229 DebugLoc DL, const unsigned Reg, 230 const unsigned Alignment, 231 const bool MustBeSingleInstruction) { 232 const ARMSubtarget &AST = 233 static_cast<const ARMSubtarget &>(MF.getSubtarget()); 234 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops(); 235 const unsigned AlignMask = Alignment - 1; 236 const unsigned NrBitsToZero = countTrailingZeros(Alignment); 237 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported"); 238 if (!AFI->isThumbFunction()) { 239 // if the BFC instruction is available, use that to zero the lower 240 // bits: 241 // bfc Reg, #0, log2(Alignment) 242 // otherwise use BIC, if the mask to zero the required number of bits 243 // can be encoded in the bic immediate field 244 // bic Reg, Reg, Alignment-1 245 // otherwise, emit 246 // lsr Reg, Reg, log2(Alignment) 247 // lsl Reg, Reg, log2(Alignment) 248 if (CanUseBFC) { 249 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg) 250 .addReg(Reg, RegState::Kill) 251 .addImm(~AlignMask)); 252 } else if (AlignMask <= 255) { 253 AddDefaultCC( 254 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg) 255 .addReg(Reg, RegState::Kill) 256 .addImm(AlignMask))); 257 } else { 258 assert(!MustBeSingleInstruction && 259 "Shouldn't call emitAligningInstructions demanding a single " 260 "instruction to be emitted for large stack alignment for a target " 261 "without BFC."); 262 AddDefaultCC(AddDefaultPred( 263 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 264 .addReg(Reg, RegState::Kill) 265 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero)))); 266 AddDefaultCC(AddDefaultPred( 267 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 268 .addReg(Reg, RegState::Kill) 269 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero)))); 270 } 271 } else { 272 // Since this is only reached for Thumb-2 targets, the BFC instruction 273 // should always be available. 274 assert(CanUseBFC); 275 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg) 276 .addReg(Reg, RegState::Kill) 277 .addImm(~AlignMask)); 278 } 279 } 280 281 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const { 282 MachineBasicBlock &MBB = MF.front(); 283 MachineBasicBlock::iterator MBBI = MBB.begin(); 284 MachineFrameInfo *MFI = MF.getFrameInfo(); 285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 286 MachineModuleInfo &MMI = MF.getMMI(); 287 MCContext &Context = MMI.getContext(); 288 const TargetMachine &TM = MF.getTarget(); 289 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 290 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo(); 291 const ARMBaseInstrInfo &TII = *STI.getInstrInfo(); 292 assert(!AFI->isThumb1OnlyFunction() && 293 "This emitPrologue does not support Thumb1!"); 294 bool isARM = !AFI->isThumbFunction(); 295 unsigned Align = STI.getFrameLowering()->getStackAlignment(); 296 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 297 unsigned NumBytes = MFI->getStackSize(); 298 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 299 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 300 unsigned FramePtr = RegInfo->getFrameRegister(MF); 301 302 // Determine the sizes of each callee-save spill areas and record which frame 303 // belongs to which callee-save spill areas. 304 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 305 int FramePtrSpillFI = 0; 306 int D8SpillFI = 0; 307 308 // All calls are tail calls in GHC calling conv, and functions have no 309 // prologue/epilogue. 310 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 311 return; 312 313 StackAdjustingInsts DefCFAOffsetCandidates; 314 315 // Allocate the vararg register save area. 316 if (ArgRegsSaveSize) { 317 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize, 318 MachineInstr::FrameSetup); 319 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true); 320 } 321 322 if (!AFI->hasStackFrame() && 323 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) { 324 if (NumBytes - ArgRegsSaveSize != 0) { 325 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize), 326 MachineInstr::FrameSetup); 327 DefCFAOffsetCandidates.addInst(std::prev(MBBI), 328 NumBytes - ArgRegsSaveSize, true); 329 } 330 return; 331 } 332 333 // Determine spill area sizes. 334 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 335 unsigned Reg = CSI[i].getReg(); 336 int FI = CSI[i].getFrameIdx(); 337 switch (Reg) { 338 case ARM::R8: 339 case ARM::R9: 340 case ARM::R10: 341 case ARM::R11: 342 case ARM::R12: 343 if (STI.isTargetDarwin()) { 344 GPRCS2Size += 4; 345 break; 346 } 347 // fallthrough 348 case ARM::R0: 349 case ARM::R1: 350 case ARM::R2: 351 case ARM::R3: 352 case ARM::R4: 353 case ARM::R5: 354 case ARM::R6: 355 case ARM::R7: 356 case ARM::LR: 357 if (Reg == FramePtr) 358 FramePtrSpillFI = FI; 359 GPRCS1Size += 4; 360 break; 361 default: 362 // This is a DPR. Exclude the aligned DPRCS2 spills. 363 if (Reg == ARM::D8) 364 D8SpillFI = FI; 365 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) 366 DPRCSSize += 8; 367 } 368 } 369 370 // Move past area 1. 371 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push; 372 if (GPRCS1Size > 0) { 373 GPRCS1Push = LastPush = MBBI++; 374 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true); 375 } 376 377 // Determine starting offsets of spill areas. 378 bool HasFP = hasFP(MF); 379 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size; 380 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size; 381 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U; 382 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign; 383 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize; 384 int FramePtrOffsetInPush = 0; 385 if (HasFP) { 386 FramePtrOffsetInPush = 387 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize; 388 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + 389 NumBytes); 390 } 391 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 392 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 393 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 394 395 // Move past area 2. 396 if (GPRCS2Size > 0) { 397 GPRCS2Push = LastPush = MBBI++; 398 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size); 399 } 400 401 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our 402 // .cfi_offset operations will reflect that. 403 if (DPRGapSize) { 404 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs"); 405 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize)) 406 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize); 407 else { 408 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize, 409 MachineInstr::FrameSetup); 410 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize); 411 } 412 } 413 414 // Move past area 3. 415 if (DPRCSSize > 0) { 416 // Since vpush register list cannot have gaps, there may be multiple vpush 417 // instructions in the prologue. 418 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) { 419 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI)); 420 LastPush = MBBI++; 421 } 422 } 423 424 // Move past the aligned DPRCS2 area. 425 if (AFI->getNumAlignedDPRCS2Regs() > 0) { 426 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs()); 427 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and 428 // leaves the stack pointer pointing to the DPRCS2 area. 429 // 430 // Adjust NumBytes to represent the stack slots below the DPRCS2 area. 431 NumBytes += MFI->getObjectOffset(D8SpillFI); 432 } else 433 NumBytes = DPRCSOffset; 434 435 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) { 436 uint32_t NumWords = NumBytes >> 2; 437 438 if (NumWords < 65536) 439 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4) 440 .addImm(NumWords) 441 .setMIFlags(MachineInstr::FrameSetup)); 442 else 443 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4) 444 .addImm(NumWords) 445 .setMIFlags(MachineInstr::FrameSetup); 446 447 switch (TM.getCodeModel()) { 448 case CodeModel::Small: 449 case CodeModel::Medium: 450 case CodeModel::Default: 451 case CodeModel::Kernel: 452 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL)) 453 .addImm((unsigned)ARMCC::AL).addReg(0) 454 .addExternalSymbol("__chkstk") 455 .addReg(ARM::R4, RegState::Implicit) 456 .setMIFlags(MachineInstr::FrameSetup); 457 break; 458 case CodeModel::Large: 459 case CodeModel::JITDefault: 460 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12) 461 .addExternalSymbol("__chkstk") 462 .setMIFlags(MachineInstr::FrameSetup); 463 464 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr)) 465 .addImm((unsigned)ARMCC::AL).addReg(0) 466 .addReg(ARM::R12, RegState::Kill) 467 .addReg(ARM::R4, RegState::Implicit) 468 .setMIFlags(MachineInstr::FrameSetup); 469 break; 470 } 471 472 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), 473 ARM::SP) 474 .addReg(ARM::SP, RegState::Define) 475 .addReg(ARM::R4, RegState::Kill) 476 .setMIFlags(MachineInstr::FrameSetup))); 477 NumBytes = 0; 478 } 479 480 if (NumBytes) { 481 // Adjust SP after all the callee-save spills. 482 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) 483 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes); 484 else { 485 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 486 MachineInstr::FrameSetup); 487 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes); 488 } 489 490 if (HasFP && isARM) 491 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 492 // Note it's not safe to do this in Thumb2 mode because it would have 493 // taken two instructions: 494 // mov sp, r7 495 // sub sp, #24 496 // If an interrupt is taken between the two instructions, then sp is in 497 // an inconsistent state (pointing to the middle of callee-saved area). 498 // The interrupt handler can end up clobbering the registers. 499 AFI->setShouldRestoreSPFromFP(true); 500 } 501 502 // Set FP to point to the stack slot that contains the previous FP. 503 // For iOS, FP is R7, which has now been stored in spill area 1. 504 // Otherwise, if this is not iOS, all the callee-saved registers go 505 // into spill area 1, including the FP in R11. In either case, it 506 // is in area one and the adjustment needs to take place just after 507 // that push. 508 if (HasFP) { 509 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push); 510 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push); 511 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, 512 dl, TII, FramePtr, ARM::SP, 513 PushSize + FramePtrOffsetInPush, 514 MachineInstr::FrameSetup); 515 if (FramePtrOffsetInPush + PushSize != 0) { 516 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa( 517 nullptr, MRI->getDwarfRegNum(FramePtr, true), 518 -(ArgRegsSaveSize - FramePtrOffsetInPush))); 519 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 520 .addCFIIndex(CFIIndex) 521 .setMIFlags(MachineInstr::FrameSetup); 522 } else { 523 unsigned CFIIndex = 524 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister( 525 nullptr, MRI->getDwarfRegNum(FramePtr, true))); 526 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 527 .addCFIIndex(CFIIndex) 528 .setMIFlags(MachineInstr::FrameSetup); 529 } 530 } 531 532 // Now that the prologue's actual instructions are finalised, we can insert 533 // the necessary DWARF cf instructions to describe the situation. Start by 534 // recording where each register ended up: 535 if (GPRCS1Size > 0) { 536 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push); 537 int CFIIndex; 538 for (const auto &Entry : CSI) { 539 unsigned Reg = Entry.getReg(); 540 int FI = Entry.getFrameIdx(); 541 switch (Reg) { 542 case ARM::R8: 543 case ARM::R9: 544 case ARM::R10: 545 case ARM::R11: 546 case ARM::R12: 547 if (STI.isTargetDarwin()) 548 break; 549 // fallthrough 550 case ARM::R0: 551 case ARM::R1: 552 case ARM::R2: 553 case ARM::R3: 554 case ARM::R4: 555 case ARM::R5: 556 case ARM::R6: 557 case ARM::R7: 558 case ARM::LR: 559 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 560 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI))); 561 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 562 .addCFIIndex(CFIIndex) 563 .setMIFlags(MachineInstr::FrameSetup); 564 break; 565 } 566 } 567 } 568 569 if (GPRCS2Size > 0) { 570 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push); 571 for (const auto &Entry : CSI) { 572 unsigned Reg = Entry.getReg(); 573 int FI = Entry.getFrameIdx(); 574 switch (Reg) { 575 case ARM::R8: 576 case ARM::R9: 577 case ARM::R10: 578 case ARM::R11: 579 case ARM::R12: 580 if (STI.isTargetDarwin()) { 581 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 582 unsigned Offset = MFI->getObjectOffset(FI); 583 unsigned CFIIndex = MMI.addFrameInst( 584 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 585 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 586 .addCFIIndex(CFIIndex) 587 .setMIFlags(MachineInstr::FrameSetup); 588 } 589 break; 590 } 591 } 592 } 593 594 if (DPRCSSize > 0) { 595 // Since vpush register list cannot have gaps, there may be multiple vpush 596 // instructions in the prologue. 597 MachineBasicBlock::iterator Pos = std::next(LastPush); 598 for (const auto &Entry : CSI) { 599 unsigned Reg = Entry.getReg(); 600 int FI = Entry.getFrameIdx(); 601 if ((Reg >= ARM::D0 && Reg <= ARM::D31) && 602 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) { 603 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 604 unsigned Offset = MFI->getObjectOffset(FI); 605 unsigned CFIIndex = MMI.addFrameInst( 606 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 607 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 608 .addCFIIndex(CFIIndex) 609 .setMIFlags(MachineInstr::FrameSetup); 610 } 611 } 612 } 613 614 // Now we can emit descriptions of where the canonical frame address was 615 // throughout the process. If we have a frame pointer, it takes over the job 616 // half-way through, so only the first few .cfi_def_cfa_offset instructions 617 // actually get emitted. 618 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP); 619 620 if (STI.isTargetELF() && hasFP(MF)) 621 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() - 622 AFI->getFramePtrSpillOffset()); 623 624 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 625 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 626 AFI->setDPRCalleeSavedGapSize(DPRGapSize); 627 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 628 629 // If we need dynamic stack realignment, do it here. Be paranoid and make 630 // sure if we also have VLAs, we have a base pointer for frame access. 631 // If aligned NEON registers were spilled, the stack has already been 632 // realigned. 633 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) { 634 unsigned MaxAlign = MFI->getMaxAlignment(); 635 assert(!AFI->isThumb1OnlyFunction()); 636 if (!AFI->isThumbFunction()) { 637 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign, 638 false); 639 } else { 640 // We cannot use sp as source/dest register here, thus we're using r4 to 641 // perform the calculations. We're emitting the following sequence: 642 // mov r4, sp 643 // -- use emitAligningInstructions to produce best sequence to zero 644 // -- out lower bits in r4 645 // mov sp, r4 646 // FIXME: It will be better just to find spare register here. 647 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4) 648 .addReg(ARM::SP, RegState::Kill)); 649 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign, 650 false); 651 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 652 .addReg(ARM::R4, RegState::Kill)); 653 } 654 655 AFI->setShouldRestoreSPFromFP(true); 656 } 657 658 // If we need a base pointer, set it up here. It's whatever the value 659 // of the stack pointer is at this point. Any variable size objects 660 // will be allocated after this, so we can still use the base pointer 661 // to reference locals. 662 // FIXME: Clarify FrameSetup flags here. 663 if (RegInfo->hasBasePointer(MF)) { 664 if (isARM) 665 BuildMI(MBB, MBBI, dl, 666 TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 667 .addReg(ARM::SP) 668 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 669 else 670 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 671 RegInfo->getBaseRegister()) 672 .addReg(ARM::SP)); 673 } 674 675 // If the frame has variable sized objects then the epilogue must restore 676 // the sp from fp. We can assume there's an FP here since hasFP already 677 // checks for hasVarSizedObjects. 678 if (MFI->hasVarSizedObjects()) 679 AFI->setShouldRestoreSPFromFP(true); 680 } 681 682 // Resolve TCReturn pseudo-instruction 683 void ARMFrameLowering::fixTCReturn(MachineFunction &MF, 684 MachineBasicBlock &MBB) const { 685 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 686 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks"); 687 unsigned RetOpcode = MBBI->getOpcode(); 688 DebugLoc dl = MBBI->getDebugLoc(); 689 const ARMBaseInstrInfo &TII = 690 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 691 692 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri)) 693 return; 694 695 // Tail call return: adjust the stack pointer and jump to callee. 696 MBBI = MBB.getLastNonDebugInstr(); 697 MachineOperand &JumpTarget = MBBI->getOperand(0); 698 699 // Jump to label or value in register. 700 if (RetOpcode == ARM::TCRETURNdi) { 701 unsigned TCOpcode = STI.isThumb() ? 702 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) : 703 ARM::TAILJMPd; 704 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode)); 705 if (JumpTarget.isGlobal()) 706 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), 707 JumpTarget.getTargetFlags()); 708 else { 709 assert(JumpTarget.isSymbol()); 710 MIB.addExternalSymbol(JumpTarget.getSymbolName(), 711 JumpTarget.getTargetFlags()); 712 } 713 714 // Add the default predicate in Thumb mode. 715 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0); 716 } else if (RetOpcode == ARM::TCRETURNri) { 717 BuildMI(MBB, MBBI, dl, 718 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)). 719 addReg(JumpTarget.getReg(), RegState::Kill); 720 } 721 722 MachineInstr *NewMI = std::prev(MBBI); 723 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i) 724 NewMI->addOperand(MBBI->getOperand(i)); 725 726 // Delete the pseudo instruction TCRETURN. 727 MBB.erase(MBBI); 728 MBBI = NewMI; 729 } 730 731 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 732 MachineBasicBlock &MBB) const { 733 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 734 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks"); 735 DebugLoc dl = MBBI->getDebugLoc(); 736 MachineFrameInfo *MFI = MF.getFrameInfo(); 737 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 738 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 739 const ARMBaseInstrInfo &TII = 740 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 741 assert(!AFI->isThumb1OnlyFunction() && 742 "This emitEpilogue does not support Thumb1!"); 743 bool isARM = !AFI->isThumbFunction(); 744 745 unsigned Align = STI.getFrameLowering()->getStackAlignment(); 746 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 747 int NumBytes = (int)MFI->getStackSize(); 748 unsigned FramePtr = RegInfo->getFrameRegister(MF); 749 750 // All calls are tail calls in GHC calling conv, and functions have no 751 // prologue/epilogue. 752 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) { 753 fixTCReturn(MF, MBB); 754 return; 755 } 756 757 if (!AFI->hasStackFrame()) { 758 if (NumBytes - ArgRegsSaveSize != 0) 759 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize); 760 } else { 761 // Unwind MBBI to point to first LDR / VLDRD. 762 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 763 if (MBBI != MBB.begin()) { 764 do { 765 --MBBI; 766 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs)); 767 if (!isCSRestore(MBBI, TII, CSRegs)) 768 ++MBBI; 769 } 770 771 // Move SP to start of FP callee save spill area. 772 NumBytes -= (ArgRegsSaveSize + 773 AFI->getGPRCalleeSavedArea1Size() + 774 AFI->getGPRCalleeSavedArea2Size() + 775 AFI->getDPRCalleeSavedGapSize() + 776 AFI->getDPRCalleeSavedAreaSize()); 777 778 // Reset SP based on frame pointer only if the stack frame extends beyond 779 // frame pointer stack slot or target is ELF and the function has FP. 780 if (AFI->shouldRestoreSPFromFP()) { 781 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 782 if (NumBytes) { 783 if (isARM) 784 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 785 ARMCC::AL, 0, TII); 786 else { 787 // It's not possible to restore SP from FP in a single instruction. 788 // For iOS, this looks like: 789 // mov sp, r7 790 // sub sp, #24 791 // This is bad, if an interrupt is taken after the mov, sp is in an 792 // inconsistent state. 793 // Use the first callee-saved register as a scratch register. 794 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) && 795 "No scratch register to restore SP from FP!"); 796 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 797 ARMCC::AL, 0, TII); 798 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 799 ARM::SP) 800 .addReg(ARM::R4)); 801 } 802 } else { 803 // Thumb2 or ARM. 804 if (isARM) 805 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 806 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 807 else 808 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 809 ARM::SP) 810 .addReg(FramePtr)); 811 } 812 } else if (NumBytes && 813 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes)) 814 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 815 816 // Increment past our save areas. 817 if (AFI->getDPRCalleeSavedAreaSize()) { 818 MBBI++; 819 // Since vpop register list cannot have gaps, there may be multiple vpop 820 // instructions in the epilogue. 821 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD) 822 MBBI++; 823 } 824 if (AFI->getDPRCalleeSavedGapSize()) { 825 assert(AFI->getDPRCalleeSavedGapSize() == 4 && 826 "unexpected DPR alignment gap"); 827 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize()); 828 } 829 830 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++; 831 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 832 } 833 834 fixTCReturn(MF, MBB); 835 836 if (ArgRegsSaveSize) 837 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize); 838 } 839 840 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 841 /// debug info. It's the same as what we use for resolving the code-gen 842 /// references for now. FIXME: This can go wrong when references are 843 /// SP-relative and simple call frames aren't used. 844 int 845 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 846 unsigned &FrameReg) const { 847 return ResolveFrameIndexReference(MF, FI, FrameReg, 0); 848 } 849 850 int 851 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 852 int FI, unsigned &FrameReg, 853 int SPAdj) const { 854 const MachineFrameInfo *MFI = MF.getFrameInfo(); 855 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 856 MF.getSubtarget().getRegisterInfo()); 857 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 858 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize(); 859 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 860 bool isFixed = MFI->isFixedObjectIndex(FI); 861 862 FrameReg = ARM::SP; 863 Offset += SPAdj; 864 865 // SP can move around if there are allocas. We may also lose track of SP 866 // when emergency spilling inside a non-reserved call frame setup. 867 bool hasMovingSP = !hasReservedCallFrame(MF); 868 869 // When dynamically realigning the stack, use the frame pointer for 870 // parameters, and the stack/base pointer for locals. 871 if (RegInfo->needsStackRealignment(MF)) { 872 assert (hasFP(MF) && "dynamic stack realignment without a FP!"); 873 if (isFixed) { 874 FrameReg = RegInfo->getFrameRegister(MF); 875 Offset = FPOffset; 876 } else if (hasMovingSP) { 877 assert(RegInfo->hasBasePointer(MF) && 878 "VLAs and dynamic stack alignment, but missing base pointer!"); 879 FrameReg = RegInfo->getBaseRegister(); 880 } 881 return Offset; 882 } 883 884 // If there is a frame pointer, use it when we can. 885 if (hasFP(MF) && AFI->hasStackFrame()) { 886 // Use frame pointer to reference fixed objects. Use it for locals if 887 // there are VLAs (and thus the SP isn't reliable as a base). 888 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) { 889 FrameReg = RegInfo->getFrameRegister(MF); 890 return FPOffset; 891 } else if (hasMovingSP) { 892 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 893 if (AFI->isThumb2Function()) { 894 // Try to use the frame pointer if we can, else use the base pointer 895 // since it's available. This is handy for the emergency spill slot, in 896 // particular. 897 if (FPOffset >= -255 && FPOffset < 0) { 898 FrameReg = RegInfo->getFrameRegister(MF); 899 return FPOffset; 900 } 901 } 902 } else if (AFI->isThumb2Function()) { 903 // Use add <rd>, sp, #<imm8> 904 // ldr <rd>, [sp, #<imm8>] 905 // if at all possible to save space. 906 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020) 907 return Offset; 908 // In Thumb2 mode, the negative offset is very limited. Try to avoid 909 // out of range references. ldr <rt>,[<rn>, #-<imm8>] 910 if (FPOffset >= -255 && FPOffset < 0) { 911 FrameReg = RegInfo->getFrameRegister(MF); 912 return FPOffset; 913 } 914 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 915 // Otherwise, use SP or FP, whichever is closer to the stack slot. 916 FrameReg = RegInfo->getFrameRegister(MF); 917 return FPOffset; 918 } 919 } 920 // Use the base pointer if we have one. 921 if (RegInfo->hasBasePointer(MF)) 922 FrameReg = RegInfo->getBaseRegister(); 923 return Offset; 924 } 925 926 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF, 927 int FI) const { 928 unsigned FrameReg; 929 return getFrameIndexReference(MF, FI, FrameReg); 930 } 931 932 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 933 MachineBasicBlock::iterator MI, 934 const std::vector<CalleeSavedInfo> &CSI, 935 unsigned StmOpc, unsigned StrOpc, 936 bool NoGap, 937 bool(*Func)(unsigned, bool), 938 unsigned NumAlignedDPRCS2Regs, 939 unsigned MIFlags) const { 940 MachineFunction &MF = *MBB.getParent(); 941 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 942 943 DebugLoc DL; 944 if (MI != MBB.end()) DL = MI->getDebugLoc(); 945 946 SmallVector<std::pair<unsigned,bool>, 4> Regs; 947 unsigned i = CSI.size(); 948 while (i != 0) { 949 unsigned LastReg = 0; 950 for (; i != 0; --i) { 951 unsigned Reg = CSI[i-1].getReg(); 952 if (!(Func)(Reg, STI.isTargetDarwin())) continue; 953 954 // D-registers in the aligned area DPRCS2 are NOT spilled here. 955 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 956 continue; 957 958 // Add the callee-saved register as live-in unless it's LR and 959 // @llvm.returnaddress is called. If LR is returned for 960 // @llvm.returnaddress then it's already added to the function and 961 // entry block live-in sets. 962 bool isKill = true; 963 if (Reg == ARM::LR) { 964 if (MF.getFrameInfo()->isReturnAddressTaken() && 965 MF.getRegInfo().isLiveIn(Reg)) 966 isKill = false; 967 } 968 969 if (isKill) 970 MBB.addLiveIn(Reg); 971 972 // If NoGap is true, push consecutive registers and then leave the rest 973 // for other instructions. e.g. 974 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 975 if (NoGap && LastReg && LastReg != Reg-1) 976 break; 977 LastReg = Reg; 978 Regs.push_back(std::make_pair(Reg, isKill)); 979 } 980 981 if (Regs.empty()) 982 continue; 983 if (Regs.size() > 1 || StrOpc== 0) { 984 MachineInstrBuilder MIB = 985 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 986 .addReg(ARM::SP).setMIFlags(MIFlags)); 987 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 988 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 989 } else if (Regs.size() == 1) { 990 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc), 991 ARM::SP) 992 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 993 .addReg(ARM::SP).setMIFlags(MIFlags) 994 .addImm(-4); 995 AddDefaultPred(MIB); 996 } 997 Regs.clear(); 998 999 // Put any subsequent vpush instructions before this one: they will refer to 1000 // higher register numbers so need to be pushed first in order to preserve 1001 // monotonicity. 1002 --MI; 1003 } 1004 } 1005 1006 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 1007 MachineBasicBlock::iterator MI, 1008 const std::vector<CalleeSavedInfo> &CSI, 1009 unsigned LdmOpc, unsigned LdrOpc, 1010 bool isVarArg, bool NoGap, 1011 bool(*Func)(unsigned, bool), 1012 unsigned NumAlignedDPRCS2Regs) const { 1013 MachineFunction &MF = *MBB.getParent(); 1014 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1015 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1016 DebugLoc DL = MI->getDebugLoc(); 1017 unsigned RetOpcode = MI->getOpcode(); 1018 bool isTailCall = (RetOpcode == ARM::TCRETURNdi || 1019 RetOpcode == ARM::TCRETURNri); 1020 bool isInterrupt = 1021 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR; 1022 1023 SmallVector<unsigned, 4> Regs; 1024 unsigned i = CSI.size(); 1025 while (i != 0) { 1026 unsigned LastReg = 0; 1027 bool DeleteRet = false; 1028 for (; i != 0; --i) { 1029 unsigned Reg = CSI[i-1].getReg(); 1030 if (!(Func)(Reg, STI.isTargetDarwin())) continue; 1031 1032 // The aligned reloads from area DPRCS2 are not inserted here. 1033 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 1034 continue; 1035 1036 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt && 1037 STI.hasV5TOps()) { 1038 Reg = ARM::PC; 1039 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 1040 // Fold the return instruction into the LDM. 1041 DeleteRet = true; 1042 } 1043 1044 // If NoGap is true, pop consecutive registers and then leave the rest 1045 // for other instructions. e.g. 1046 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 1047 if (NoGap && LastReg && LastReg != Reg-1) 1048 break; 1049 1050 LastReg = Reg; 1051 Regs.push_back(Reg); 1052 } 1053 1054 if (Regs.empty()) 1055 continue; 1056 if (Regs.size() > 1 || LdrOpc == 0) { 1057 MachineInstrBuilder MIB = 1058 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 1059 .addReg(ARM::SP)); 1060 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 1061 MIB.addReg(Regs[i], getDefRegState(true)); 1062 if (DeleteRet) { 1063 MIB.copyImplicitOps(&*MI); 1064 MI->eraseFromParent(); 1065 } 1066 MI = MIB; 1067 } else if (Regs.size() == 1) { 1068 // If we adjusted the reg to PC from LR above, switch it back here. We 1069 // only do that for LDM. 1070 if (Regs[0] == ARM::PC) 1071 Regs[0] = ARM::LR; 1072 MachineInstrBuilder MIB = 1073 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 1074 .addReg(ARM::SP, RegState::Define) 1075 .addReg(ARM::SP); 1076 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 1077 // that refactoring is complete (eventually). 1078 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) { 1079 MIB.addReg(0); 1080 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 1081 } else 1082 MIB.addImm(4); 1083 AddDefaultPred(MIB); 1084 } 1085 Regs.clear(); 1086 1087 // Put any subsequent vpop instructions after this one: they will refer to 1088 // higher register numbers so need to be popped afterwards. 1089 ++MI; 1090 } 1091 } 1092 1093 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers 1094 /// starting from d8. Also insert stack realignment code and leave the stack 1095 /// pointer pointing to the d8 spill slot. 1096 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, 1097 MachineBasicBlock::iterator MI, 1098 unsigned NumAlignedDPRCS2Regs, 1099 const std::vector<CalleeSavedInfo> &CSI, 1100 const TargetRegisterInfo *TRI) { 1101 MachineFunction &MF = *MBB.getParent(); 1102 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1103 DebugLoc DL = MI->getDebugLoc(); 1104 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1105 MachineFrameInfo &MFI = *MF.getFrameInfo(); 1106 1107 // Mark the D-register spill slots as properly aligned. Since MFI computes 1108 // stack slot layout backwards, this can actually mean that the d-reg stack 1109 // slot offsets can be wrong. The offset for d8 will always be correct. 1110 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 1111 unsigned DNum = CSI[i].getReg() - ARM::D8; 1112 if (DNum >= 8) 1113 continue; 1114 int FI = CSI[i].getFrameIdx(); 1115 // The even-numbered registers will be 16-byte aligned, the odd-numbered 1116 // registers will be 8-byte aligned. 1117 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16); 1118 1119 // The stack slot for D8 needs to be maximally aligned because this is 1120 // actually the point where we align the stack pointer. MachineFrameInfo 1121 // computes all offsets relative to the incoming stack pointer which is a 1122 // bit weird when realigning the stack. Any extra padding for this 1123 // over-alignment is not realized because the code inserted below adjusts 1124 // the stack pointer by numregs * 8 before aligning the stack pointer. 1125 if (DNum == 0) 1126 MFI.setObjectAlignment(FI, MFI.getMaxAlignment()); 1127 } 1128 1129 // Move the stack pointer to the d8 spill slot, and align it at the same 1130 // time. Leave the stack slot address in the scratch register r4. 1131 // 1132 // sub r4, sp, #numregs * 8 1133 // bic r4, r4, #align - 1 1134 // mov sp, r4 1135 // 1136 bool isThumb = AFI->isThumbFunction(); 1137 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1138 AFI->setShouldRestoreSPFromFP(true); 1139 1140 // sub r4, sp, #numregs * 8 1141 // The immediate is <= 64, so it doesn't need any special encoding. 1142 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri; 1143 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1144 .addReg(ARM::SP) 1145 .addImm(8 * NumAlignedDPRCS2Regs))); 1146 1147 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment(); 1148 // We must set parameter MustBeSingleInstruction to true, since 1149 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform 1150 // stack alignment. Luckily, this can always be done since all ARM 1151 // architecture versions that support Neon also support the BFC 1152 // instruction. 1153 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true); 1154 1155 // mov sp, r4 1156 // The stack pointer must be adjusted before spilling anything, otherwise 1157 // the stack slots could be clobbered by an interrupt handler. 1158 // Leave r4 live, it is used below. 1159 Opc = isThumb ? ARM::tMOVr : ARM::MOVr; 1160 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP) 1161 .addReg(ARM::R4); 1162 MIB = AddDefaultPred(MIB); 1163 if (!isThumb) 1164 AddDefaultCC(MIB); 1165 1166 // Now spill NumAlignedDPRCS2Regs registers starting from d8. 1167 // r4 holds the stack slot address. 1168 unsigned NextReg = ARM::D8; 1169 1170 // 16-byte aligned vst1.64 with 4 d-regs and address writeback. 1171 // The writeback is only needed when emitting two vst1.64 instructions. 1172 if (NumAlignedDPRCS2Regs >= 6) { 1173 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1174 &ARM::QQPRRegClass); 1175 MBB.addLiveIn(SupReg); 1176 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), 1177 ARM::R4) 1178 .addReg(ARM::R4, RegState::Kill).addImm(16) 1179 .addReg(NextReg) 1180 .addReg(SupReg, RegState::ImplicitKill)); 1181 NextReg += 4; 1182 NumAlignedDPRCS2Regs -= 4; 1183 } 1184 1185 // We won't modify r4 beyond this point. It currently points to the next 1186 // register to be spilled. 1187 unsigned R4BaseReg = NextReg; 1188 1189 // 16-byte aligned vst1.64 with 4 d-regs, no writeback. 1190 if (NumAlignedDPRCS2Regs >= 4) { 1191 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1192 &ARM::QQPRRegClass); 1193 MBB.addLiveIn(SupReg); 1194 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q)) 1195 .addReg(ARM::R4).addImm(16).addReg(NextReg) 1196 .addReg(SupReg, RegState::ImplicitKill)); 1197 NextReg += 4; 1198 NumAlignedDPRCS2Regs -= 4; 1199 } 1200 1201 // 16-byte aligned vst1.64 with 2 d-regs. 1202 if (NumAlignedDPRCS2Regs >= 2) { 1203 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1204 &ARM::QPRRegClass); 1205 MBB.addLiveIn(SupReg); 1206 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64)) 1207 .addReg(ARM::R4).addImm(16).addReg(SupReg)); 1208 NextReg += 2; 1209 NumAlignedDPRCS2Regs -= 2; 1210 } 1211 1212 // Finally, use a vanilla vstr.64 for the odd last register. 1213 if (NumAlignedDPRCS2Regs) { 1214 MBB.addLiveIn(NextReg); 1215 // vstr.64 uses addrmode5 which has an offset scale of 4. 1216 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD)) 1217 .addReg(NextReg) 1218 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2)); 1219 } 1220 1221 // The last spill instruction inserted should kill the scratch register r4. 1222 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1223 } 1224 1225 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an 1226 /// iterator to the following instruction. 1227 static MachineBasicBlock::iterator 1228 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 1229 unsigned NumAlignedDPRCS2Regs) { 1230 // sub r4, sp, #numregs * 8 1231 // bic r4, r4, #align - 1 1232 // mov sp, r4 1233 ++MI; ++MI; ++MI; 1234 assert(MI->mayStore() && "Expecting spill instruction"); 1235 1236 // These switches all fall through. 1237 switch(NumAlignedDPRCS2Regs) { 1238 case 7: 1239 ++MI; 1240 assert(MI->mayStore() && "Expecting spill instruction"); 1241 default: 1242 ++MI; 1243 assert(MI->mayStore() && "Expecting spill instruction"); 1244 case 1: 1245 case 2: 1246 case 4: 1247 assert(MI->killsRegister(ARM::R4) && "Missed kill flag"); 1248 ++MI; 1249 } 1250 return MI; 1251 } 1252 1253 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers 1254 /// starting from d8. These instructions are assumed to execute while the 1255 /// stack is still aligned, unlike the code inserted by emitPopInst. 1256 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, 1257 MachineBasicBlock::iterator MI, 1258 unsigned NumAlignedDPRCS2Regs, 1259 const std::vector<CalleeSavedInfo> &CSI, 1260 const TargetRegisterInfo *TRI) { 1261 MachineFunction &MF = *MBB.getParent(); 1262 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1263 DebugLoc DL = MI->getDebugLoc(); 1264 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1265 1266 // Find the frame index assigned to d8. 1267 int D8SpillFI = 0; 1268 for (unsigned i = 0, e = CSI.size(); i != e; ++i) 1269 if (CSI[i].getReg() == ARM::D8) { 1270 D8SpillFI = CSI[i].getFrameIdx(); 1271 break; 1272 } 1273 1274 // Materialize the address of the d8 spill slot into the scratch register r4. 1275 // This can be fairly complicated if the stack frame is large, so just use 1276 // the normal frame index elimination mechanism to do it. This code runs as 1277 // the initial part of the epilog where the stack and base pointers haven't 1278 // been changed yet. 1279 bool isThumb = AFI->isThumbFunction(); 1280 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1281 1282 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri; 1283 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1284 .addFrameIndex(D8SpillFI).addImm(0))); 1285 1286 // Now restore NumAlignedDPRCS2Regs registers starting from d8. 1287 unsigned NextReg = ARM::D8; 1288 1289 // 16-byte aligned vld1.64 with 4 d-regs and writeback. 1290 if (NumAlignedDPRCS2Regs >= 6) { 1291 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1292 &ARM::QQPRRegClass); 1293 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg) 1294 .addReg(ARM::R4, RegState::Define) 1295 .addReg(ARM::R4, RegState::Kill).addImm(16) 1296 .addReg(SupReg, RegState::ImplicitDefine)); 1297 NextReg += 4; 1298 NumAlignedDPRCS2Regs -= 4; 1299 } 1300 1301 // We won't modify r4 beyond this point. It currently points to the next 1302 // register to be spilled. 1303 unsigned R4BaseReg = NextReg; 1304 1305 // 16-byte aligned vld1.64 with 4 d-regs, no writeback. 1306 if (NumAlignedDPRCS2Regs >= 4) { 1307 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1308 &ARM::QQPRRegClass); 1309 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg) 1310 .addReg(ARM::R4).addImm(16) 1311 .addReg(SupReg, RegState::ImplicitDefine)); 1312 NextReg += 4; 1313 NumAlignedDPRCS2Regs -= 4; 1314 } 1315 1316 // 16-byte aligned vld1.64 with 2 d-regs. 1317 if (NumAlignedDPRCS2Regs >= 2) { 1318 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1319 &ARM::QPRRegClass); 1320 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg) 1321 .addReg(ARM::R4).addImm(16)); 1322 NextReg += 2; 1323 NumAlignedDPRCS2Regs -= 2; 1324 } 1325 1326 // Finally, use a vanilla vldr.64 for the remaining odd register. 1327 if (NumAlignedDPRCS2Regs) 1328 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg) 1329 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg))); 1330 1331 // Last store kills r4. 1332 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1333 } 1334 1335 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB, 1336 MachineBasicBlock::iterator MI, 1337 const std::vector<CalleeSavedInfo> &CSI, 1338 const TargetRegisterInfo *TRI) const { 1339 if (CSI.empty()) 1340 return false; 1341 1342 MachineFunction &MF = *MBB.getParent(); 1343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1344 1345 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 1346 unsigned PushOneOpc = AFI->isThumbFunction() ? 1347 ARM::t2STR_PRE : ARM::STR_PRE_IMM; 1348 unsigned FltOpc = ARM::VSTMDDB_UPD; 1349 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1350 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0, 1351 MachineInstr::FrameSetup); 1352 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0, 1353 MachineInstr::FrameSetup); 1354 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register, 1355 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup); 1356 1357 // The code above does not insert spill code for the aligned DPRCS2 registers. 1358 // The stack realignment code will be inserted between the push instructions 1359 // and these spills. 1360 if (NumAlignedDPRCS2Regs) 1361 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1362 1363 return true; 1364 } 1365 1366 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB, 1367 MachineBasicBlock::iterator MI, 1368 const std::vector<CalleeSavedInfo> &CSI, 1369 const TargetRegisterInfo *TRI) const { 1370 if (CSI.empty()) 1371 return false; 1372 1373 MachineFunction &MF = *MBB.getParent(); 1374 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1375 bool isVarArg = AFI->getArgRegsSaveSize() > 0; 1376 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1377 1378 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2 1379 // registers. Do that here instead. 1380 if (NumAlignedDPRCS2Regs) 1381 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1382 1383 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 1384 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM; 1385 unsigned FltOpc = ARM::VLDMDIA_UPD; 1386 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register, 1387 NumAlignedDPRCS2Regs); 1388 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1389 &isARMArea2Register, 0); 1390 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1391 &isARMArea1Register, 0); 1392 1393 return true; 1394 } 1395 1396 // FIXME: Make generic? 1397 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF, 1398 const ARMBaseInstrInfo &TII) { 1399 unsigned FnSize = 0; 1400 for (auto &MBB : MF) { 1401 for (auto &MI : MBB) 1402 FnSize += TII.GetInstSizeInBytes(&MI); 1403 } 1404 return FnSize; 1405 } 1406 1407 /// estimateRSStackSizeLimit - Look at each instruction that references stack 1408 /// frames and return the stack size limit beyond which some of these 1409 /// instructions will require a scratch register during their expansion later. 1410 // FIXME: Move to TII? 1411 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 1412 const TargetFrameLowering *TFI) { 1413 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1414 unsigned Limit = (1 << 12) - 1; 1415 for (auto &MBB : MF) { 1416 for (auto &MI : MBB) { 1417 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1418 if (!MI.getOperand(i).isFI()) 1419 continue; 1420 1421 // When using ADDri to get the address of a stack object, 255 is the 1422 // largest offset guaranteed to fit in the immediate offset. 1423 if (MI.getOpcode() == ARM::ADDri) { 1424 Limit = std::min(Limit, (1U << 8) - 1); 1425 break; 1426 } 1427 1428 // Otherwise check the addressing mode. 1429 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) { 1430 case ARMII::AddrMode3: 1431 case ARMII::AddrModeT2_i8: 1432 Limit = std::min(Limit, (1U << 8) - 1); 1433 break; 1434 case ARMII::AddrMode5: 1435 case ARMII::AddrModeT2_i8s4: 1436 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 1437 break; 1438 case ARMII::AddrModeT2_i12: 1439 // i12 supports only positive offset so these will be converted to 1440 // i8 opcodes. See llvm::rewriteT2FrameIndex. 1441 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 1442 Limit = std::min(Limit, (1U << 8) - 1); 1443 break; 1444 case ARMII::AddrMode4: 1445 case ARMII::AddrMode6: 1446 // Addressing modes 4 & 6 (load/store) instructions can't encode an 1447 // immediate offset for stack references. 1448 return 0; 1449 default: 1450 break; 1451 } 1452 break; // At most one FI per instruction 1453 } 1454 } 1455 } 1456 1457 return Limit; 1458 } 1459 1460 // In functions that realign the stack, it can be an advantage to spill the 1461 // callee-saved vector registers after realigning the stack. The vst1 and vld1 1462 // instructions take alignment hints that can improve performance. 1463 // 1464 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) { 1465 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0); 1466 if (!SpillAlignedNEONRegs) 1467 return; 1468 1469 // Naked functions don't spill callee-saved registers. 1470 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1471 Attribute::Naked)) 1472 return; 1473 1474 // We are planning to use NEON instructions vst1 / vld1. 1475 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON()) 1476 return; 1477 1478 // Don't bother if the default stack alignment is sufficiently high. 1479 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8) 1480 return; 1481 1482 // Aligned spills require stack realignment. 1483 if (!static_cast<const ARMBaseRegisterInfo *>( 1484 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF)) 1485 return; 1486 1487 // We always spill contiguous d-registers starting from d8. Count how many 1488 // needs spilling. The register allocator will almost always use the 1489 // callee-saved registers in order, but it can happen that there are holes in 1490 // the range. Registers above the hole will be spilled to the standard DPRCS 1491 // area. 1492 MachineRegisterInfo &MRI = MF.getRegInfo(); 1493 unsigned NumSpills = 0; 1494 for (; NumSpills < 8; ++NumSpills) 1495 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills)) 1496 break; 1497 1498 // Don't do this for just one d-register. It's not worth it. 1499 if (NumSpills < 2) 1500 return; 1501 1502 // Spill the first NumSpills D-registers after realigning the stack. 1503 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills); 1504 1505 // A scratch register is required for the vst1 / vld1 instructions. 1506 MF.getRegInfo().setPhysRegUsed(ARM::R4); 1507 } 1508 1509 void 1510 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF, 1511 RegScavenger *RS) const { 1512 // This tells PEI to spill the FP as if it is any other callee-save register 1513 // to take advantage the eliminateFrameIndex machinery. This also ensures it 1514 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 1515 // to combine multiple loads / stores. 1516 bool CanEliminateFrame = true; 1517 bool CS1Spilled = false; 1518 bool LRSpilled = false; 1519 unsigned NumGPRSpills = 0; 1520 SmallVector<unsigned, 4> UnspilledCS1GPRs; 1521 SmallVector<unsigned, 4> UnspilledCS2GPRs; 1522 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 1523 MF.getSubtarget().getRegisterInfo()); 1524 const ARMBaseInstrInfo &TII = 1525 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1526 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1527 MachineFrameInfo *MFI = MF.getFrameInfo(); 1528 MachineRegisterInfo &MRI = MF.getRegInfo(); 1529 unsigned FramePtr = RegInfo->getFrameRegister(MF); 1530 1531 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 1532 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 1533 // since it's not always possible to restore sp from fp in a single 1534 // instruction. 1535 // FIXME: It will be better just to find spare register here. 1536 if (AFI->isThumb2Function() && 1537 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF))) 1538 MRI.setPhysRegUsed(ARM::R4); 1539 1540 if (AFI->isThumb1OnlyFunction()) { 1541 // Spill LR if Thumb1 function uses variable length argument lists. 1542 if (AFI->getArgRegsSaveSize() > 0) 1543 MRI.setPhysRegUsed(ARM::LR); 1544 1545 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know 1546 // for sure what the stack size will be, but for this, an estimate is good 1547 // enough. If there anything changes it, it'll be a spill, which implies 1548 // we've used all the registers and so R4 is already used, so not marking 1549 // it here will be OK. 1550 // FIXME: It will be better just to find spare register here. 1551 unsigned StackSize = MFI->estimateStackSize(MF); 1552 if (MFI->hasVarSizedObjects() || StackSize > 508) 1553 MRI.setPhysRegUsed(ARM::R4); 1554 } 1555 1556 // See if we can spill vector registers to aligned stack. 1557 checkNumAlignedDPRCS2Regs(MF); 1558 1559 // Spill the BasePtr if it's used. 1560 if (RegInfo->hasBasePointer(MF)) 1561 MRI.setPhysRegUsed(RegInfo->getBaseRegister()); 1562 1563 // Don't spill FP if the frame can be eliminated. This is determined 1564 // by scanning the callee-save registers to see if any is used. 1565 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 1566 for (unsigned i = 0; CSRegs[i]; ++i) { 1567 unsigned Reg = CSRegs[i]; 1568 bool Spilled = false; 1569 if (MRI.isPhysRegUsed(Reg)) { 1570 Spilled = true; 1571 CanEliminateFrame = false; 1572 } 1573 1574 if (!ARM::GPRRegClass.contains(Reg)) 1575 continue; 1576 1577 if (Spilled) { 1578 NumGPRSpills++; 1579 1580 if (!STI.isTargetDarwin()) { 1581 if (Reg == ARM::LR) 1582 LRSpilled = true; 1583 CS1Spilled = true; 1584 continue; 1585 } 1586 1587 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 1588 switch (Reg) { 1589 case ARM::LR: 1590 LRSpilled = true; 1591 // Fallthrough 1592 case ARM::R0: case ARM::R1: 1593 case ARM::R2: case ARM::R3: 1594 case ARM::R4: case ARM::R5: 1595 case ARM::R6: case ARM::R7: 1596 CS1Spilled = true; 1597 break; 1598 default: 1599 break; 1600 } 1601 } else { 1602 if (!STI.isTargetDarwin()) { 1603 UnspilledCS1GPRs.push_back(Reg); 1604 continue; 1605 } 1606 1607 switch (Reg) { 1608 case ARM::R0: case ARM::R1: 1609 case ARM::R2: case ARM::R3: 1610 case ARM::R4: case ARM::R5: 1611 case ARM::R6: case ARM::R7: 1612 case ARM::LR: 1613 UnspilledCS1GPRs.push_back(Reg); 1614 break; 1615 default: 1616 UnspilledCS2GPRs.push_back(Reg); 1617 break; 1618 } 1619 } 1620 } 1621 1622 bool ForceLRSpill = false; 1623 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 1624 unsigned FnSize = GetFunctionSizeInBytes(MF, TII); 1625 // Force LR to be spilled if the Thumb function size is > 2048. This enables 1626 // use of BL to implement far jump. If it turns out that it's not needed 1627 // then the branch fix up path will undo it. 1628 if (FnSize >= (1 << 11)) { 1629 CanEliminateFrame = false; 1630 ForceLRSpill = true; 1631 } 1632 } 1633 1634 // If any of the stack slot references may be out of range of an immediate 1635 // offset, make sure a register (or a spill slot) is available for the 1636 // register scavenger. Note that if we're indexing off the frame pointer, the 1637 // effective stack size is 4 bytes larger since the FP points to the stack 1638 // slot of the previous FP. Also, if we have variable sized objects in the 1639 // function, stack slot references will often be negative, and some of 1640 // our instructions are positive-offset only, so conservatively consider 1641 // that case to want a spill slot (or register) as well. Similarly, if 1642 // the function adjusts the stack pointer during execution and the 1643 // adjustments aren't already part of our stack size estimate, our offset 1644 // calculations may be off, so be conservative. 1645 // FIXME: We could add logic to be more precise about negative offsets 1646 // and which instructions will need a scratch register for them. Is it 1647 // worth the effort and added fragility? 1648 bool BigStack = 1649 (RS && 1650 (MFI->estimateStackSize(MF) + 1651 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >= 1652 estimateRSStackSizeLimit(MF, this))) 1653 || MFI->hasVarSizedObjects() 1654 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF)); 1655 1656 bool ExtraCSSpill = false; 1657 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 1658 AFI->setHasStackFrame(true); 1659 1660 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 1661 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 1662 if (!LRSpilled && CS1Spilled) { 1663 MRI.setPhysRegUsed(ARM::LR); 1664 NumGPRSpills++; 1665 SmallVectorImpl<unsigned>::iterator LRPos; 1666 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(), 1667 (unsigned)ARM::LR); 1668 if (LRPos != UnspilledCS1GPRs.end()) 1669 UnspilledCS1GPRs.erase(LRPos); 1670 1671 ForceLRSpill = false; 1672 ExtraCSSpill = true; 1673 } 1674 1675 if (hasFP(MF)) { 1676 MRI.setPhysRegUsed(FramePtr); 1677 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(), 1678 FramePtr); 1679 if (FPPos != UnspilledCS1GPRs.end()) 1680 UnspilledCS1GPRs.erase(FPPos); 1681 NumGPRSpills++; 1682 } 1683 1684 // If stack and double are 8-byte aligned and we are spilling an odd number 1685 // of GPRs, spill one extra callee save GPR so we won't have to pad between 1686 // the integer and double callee save areas. 1687 unsigned TargetAlign = getStackAlignment(); 1688 if (TargetAlign >= 8 && (NumGPRSpills & 1)) { 1689 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 1690 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) { 1691 unsigned Reg = UnspilledCS1GPRs[i]; 1692 // Don't spill high register if the function is thumb1 1693 if (!AFI->isThumb1OnlyFunction() || 1694 isARMLowRegister(Reg) || Reg == ARM::LR) { 1695 MRI.setPhysRegUsed(Reg); 1696 if (!MRI.isReserved(Reg)) 1697 ExtraCSSpill = true; 1698 break; 1699 } 1700 } 1701 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 1702 unsigned Reg = UnspilledCS2GPRs.front(); 1703 MRI.setPhysRegUsed(Reg); 1704 if (!MRI.isReserved(Reg)) 1705 ExtraCSSpill = true; 1706 } 1707 } 1708 1709 // Estimate if we might need to scavenge a register at some point in order 1710 // to materialize a stack offset. If so, either spill one additional 1711 // callee-saved register or reserve a special spill slot to facilitate 1712 // register scavenging. Thumb1 needs a spill slot for stack pointer 1713 // adjustments also, even when the frame itself is small. 1714 if (BigStack && !ExtraCSSpill) { 1715 // If any non-reserved CS register isn't spilled, just spill one or two 1716 // extra. That should take care of it! 1717 unsigned NumExtras = TargetAlign / 4; 1718 SmallVector<unsigned, 2> Extras; 1719 while (NumExtras && !UnspilledCS1GPRs.empty()) { 1720 unsigned Reg = UnspilledCS1GPRs.back(); 1721 UnspilledCS1GPRs.pop_back(); 1722 if (!MRI.isReserved(Reg) && 1723 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) || 1724 Reg == ARM::LR)) { 1725 Extras.push_back(Reg); 1726 NumExtras--; 1727 } 1728 } 1729 // For non-Thumb1 functions, also check for hi-reg CS registers 1730 if (!AFI->isThumb1OnlyFunction()) { 1731 while (NumExtras && !UnspilledCS2GPRs.empty()) { 1732 unsigned Reg = UnspilledCS2GPRs.back(); 1733 UnspilledCS2GPRs.pop_back(); 1734 if (!MRI.isReserved(Reg)) { 1735 Extras.push_back(Reg); 1736 NumExtras--; 1737 } 1738 } 1739 } 1740 if (Extras.size() && NumExtras == 0) { 1741 for (unsigned i = 0, e = Extras.size(); i != e; ++i) { 1742 MRI.setPhysRegUsed(Extras[i]); 1743 } 1744 } else if (!AFI->isThumb1OnlyFunction()) { 1745 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot 1746 // closest to SP or frame pointer. 1747 const TargetRegisterClass *RC = &ARM::GPRRegClass; 1748 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(), 1749 RC->getAlignment(), 1750 false)); 1751 } 1752 } 1753 } 1754 1755 if (ForceLRSpill) { 1756 MRI.setPhysRegUsed(ARM::LR); 1757 AFI->setLRIsSpilledForFarJump(true); 1758 } 1759 } 1760 1761 1762 void ARMFrameLowering:: 1763 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, 1764 MachineBasicBlock::iterator I) const { 1765 const ARMBaseInstrInfo &TII = 1766 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1767 if (!hasReservedCallFrame(MF)) { 1768 // If we have alloca, convert as follows: 1769 // ADJCALLSTACKDOWN -> sub, sp, sp, amount 1770 // ADJCALLSTACKUP -> add, sp, sp, amount 1771 MachineInstr *Old = I; 1772 DebugLoc dl = Old->getDebugLoc(); 1773 unsigned Amount = Old->getOperand(0).getImm(); 1774 if (Amount != 0) { 1775 // We need to keep the stack aligned properly. To do this, we round the 1776 // amount of space needed for the outgoing arguments up to the next 1777 // alignment boundary. 1778 unsigned Align = getStackAlignment(); 1779 Amount = (Amount+Align-1)/Align*Align; 1780 1781 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1782 assert(!AFI->isThumb1OnlyFunction() && 1783 "This eliminateCallFramePseudoInstr does not support Thumb1!"); 1784 bool isARM = !AFI->isThumbFunction(); 1785 1786 // Replace the pseudo instruction with a new instruction... 1787 unsigned Opc = Old->getOpcode(); 1788 int PIdx = Old->findFirstPredOperandIdx(); 1789 ARMCC::CondCodes Pred = (PIdx == -1) 1790 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm(); 1791 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) { 1792 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN. 1793 unsigned PredReg = Old->getOperand(2).getReg(); 1794 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags, 1795 Pred, PredReg); 1796 } else { 1797 // Note: PredReg is operand 3 for ADJCALLSTACKUP. 1798 unsigned PredReg = Old->getOperand(3).getReg(); 1799 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP); 1800 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags, 1801 Pred, PredReg); 1802 } 1803 } 1804 } 1805 MBB.erase(I); 1806 } 1807 1808 /// Get the minimum constant for ARM that is greater than or equal to the 1809 /// argument. In ARM, constants can have any value that can be produced by 1810 /// rotating an 8-bit value to the right by an even number of bits within a 1811 /// 32-bit word. 1812 static uint32_t alignToARMConstant(uint32_t Value) { 1813 unsigned Shifted = 0; 1814 1815 if (Value == 0) 1816 return 0; 1817 1818 while (!(Value & 0xC0000000)) { 1819 Value = Value << 2; 1820 Shifted += 2; 1821 } 1822 1823 bool Carry = (Value & 0x00FFFFFF); 1824 Value = ((Value & 0xFF000000) >> 24) + Carry; 1825 1826 if (Value & 0x0000100) 1827 Value = Value & 0x000001FC; 1828 1829 if (Shifted > 24) 1830 Value = Value >> (Shifted - 24); 1831 else 1832 Value = Value << (24 - Shifted); 1833 1834 return Value; 1835 } 1836 1837 // The stack limit in the TCB is set to this many bytes above the actual 1838 // stack limit. 1839 static const uint64_t kSplitStackAvailable = 256; 1840 1841 // Adjust the function prologue to enable split stacks. This currently only 1842 // supports android and linux. 1843 // 1844 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but 1845 // must be well defined in order to allow for consistent implementations of the 1846 // __morestack helper function. The ABI is also not a normal ABI in that it 1847 // doesn't follow the normal calling conventions because this allows the 1848 // prologue of each function to be optimized further. 1849 // 1850 // Currently, the ABI looks like (when calling __morestack) 1851 // 1852 // * r4 holds the minimum stack size requested for this function call 1853 // * r5 holds the stack size of the arguments to the function 1854 // * the beginning of the function is 3 instructions after the call to 1855 // __morestack 1856 // 1857 // Implementations of __morestack should use r4 to allocate a new stack, r5 to 1858 // place the arguments on to the new stack, and the 3-instruction knowledge to 1859 // jump directly to the body of the function when working on the new stack. 1860 // 1861 // An old (and possibly no longer compatible) implementation of __morestack for 1862 // ARM can be found at [1]. 1863 // 1864 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S 1865 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const { 1866 unsigned Opcode; 1867 unsigned CFIIndex; 1868 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>(); 1869 bool Thumb = ST->isThumb(); 1870 1871 // Sadly, this currently doesn't support varargs, platforms other than 1872 // android/linux. Note that thumb1/thumb2 are support for android/linux. 1873 if (MF.getFunction()->isVarArg()) 1874 report_fatal_error("Segmented stacks do not support vararg functions."); 1875 if (!ST->isTargetAndroid() && !ST->isTargetLinux()) 1876 report_fatal_error("Segmented stacks not supported on this platform."); 1877 1878 MachineBasicBlock &prologueMBB = MF.front(); 1879 MachineFrameInfo *MFI = MF.getFrameInfo(); 1880 MachineModuleInfo &MMI = MF.getMMI(); 1881 MCContext &Context = MMI.getContext(); 1882 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 1883 const ARMBaseInstrInfo &TII = 1884 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1885 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>(); 1886 DebugLoc DL; 1887 1888 uint64_t StackSize = MFI->getStackSize(); 1889 1890 // Do not generate a prologue for functions with a stack of size zero 1891 if (StackSize == 0) 1892 return; 1893 1894 // Use R4 and R5 as scratch registers. 1895 // We save R4 and R5 before use and restore them before leaving the function. 1896 unsigned ScratchReg0 = ARM::R4; 1897 unsigned ScratchReg1 = ARM::R5; 1898 uint64_t AlignedStackSize; 1899 1900 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock(); 1901 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock(); 1902 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock(); 1903 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock(); 1904 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock(); 1905 1906 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(), 1907 e = prologueMBB.livein_end(); 1908 i != e; ++i) { 1909 AllocMBB->addLiveIn(*i); 1910 GetMBB->addLiveIn(*i); 1911 McrMBB->addLiveIn(*i); 1912 PrevStackMBB->addLiveIn(*i); 1913 PostStackMBB->addLiveIn(*i); 1914 } 1915 1916 MF.push_front(PostStackMBB); 1917 MF.push_front(AllocMBB); 1918 MF.push_front(GetMBB); 1919 MF.push_front(McrMBB); 1920 MF.push_front(PrevStackMBB); 1921 1922 // The required stack size that is aligned to ARM constant criterion. 1923 AlignedStackSize = alignToARMConstant(StackSize); 1924 1925 // When the frame size is less than 256 we just compare the stack 1926 // boundary directly to the value of the stack pointer, per gcc. 1927 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable; 1928 1929 // We will use two of the callee save registers as scratch registers so we 1930 // need to save those registers onto the stack. 1931 // We will use SR0 to hold stack limit and SR1 to hold the stack size 1932 // requested and arguments for __morestack(). 1933 // SR0: Scratch Register #0 1934 // SR1: Scratch Register #1 1935 // push {SR0, SR1} 1936 if (Thumb) { 1937 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))) 1938 .addReg(ScratchReg0).addReg(ScratchReg1); 1939 } else { 1940 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD)) 1941 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP)) 1942 .addReg(ScratchReg0).addReg(ScratchReg1); 1943 } 1944 1945 // Emit the relevant DWARF information about the change in stack pointer as 1946 // well as where to find both r4 and r5 (the callee-save registers) 1947 CFIIndex = 1948 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8)); 1949 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1950 .addCFIIndex(CFIIndex); 1951 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 1952 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4)); 1953 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1954 .addCFIIndex(CFIIndex); 1955 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 1956 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8)); 1957 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1958 .addCFIIndex(CFIIndex); 1959 1960 // mov SR1, sp 1961 if (Thumb) { 1962 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1) 1963 .addReg(ARM::SP)); 1964 } else if (CompareStackPointer) { 1965 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1) 1966 .addReg(ARM::SP)).addReg(0); 1967 } 1968 1969 // sub SR1, sp, #StackSize 1970 if (!CompareStackPointer && Thumb) { 1971 AddDefaultPred( 1972 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)) 1973 .addReg(ScratchReg1).addImm(AlignedStackSize)); 1974 } else if (!CompareStackPointer) { 1975 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1) 1976 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0); 1977 } 1978 1979 if (Thumb && ST->isThumb1Only()) { 1980 unsigned PCLabelId = ARMFI->createPICLabelUId(); 1981 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create( 1982 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0); 1983 MachineConstantPool *MCP = MF.getConstantPool(); 1984 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment()); 1985 1986 // ldr SR0, [pc, offset(STACK_LIMIT)] 1987 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0) 1988 .addConstantPoolIndex(CPI)); 1989 1990 // ldr SR0, [SR0] 1991 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0) 1992 .addReg(ScratchReg0).addImm(0)); 1993 } else { 1994 // Get TLS base address from the coprocessor 1995 // mrc p15, #0, SR0, c13, c0, #3 1996 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0) 1997 .addImm(15) 1998 .addImm(0) 1999 .addImm(13) 2000 .addImm(0) 2001 .addImm(3)); 2002 2003 // Use the last tls slot on android and a private field of the TCP on linux. 2004 assert(ST->isTargetAndroid() || ST->isTargetLinux()); 2005 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1; 2006 2007 // Get the stack limit from the right offset 2008 // ldr SR0, [sr0, #4 * TlsOffset] 2009 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0) 2010 .addReg(ScratchReg0).addImm(4 * TlsOffset)); 2011 } 2012 2013 // Compare stack limit with stack size requested. 2014 // cmp SR0, SR1 2015 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr; 2016 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode)) 2017 .addReg(ScratchReg0) 2018 .addReg(ScratchReg1)); 2019 2020 // This jump is taken if StackLimit < SP - stack required. 2021 Opcode = Thumb ? ARM::tBcc : ARM::Bcc; 2022 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB) 2023 .addImm(ARMCC::LO) 2024 .addReg(ARM::CPSR); 2025 2026 2027 // Calling __morestack(StackSize, Size of stack arguments). 2028 // __morestack knows that the stack size requested is in SR0(r4) 2029 // and amount size of stack arguments is in SR1(r5). 2030 2031 // Pass first argument for the __morestack by Scratch Register #0. 2032 // The amount size of stack required 2033 if (Thumb) { 2034 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), 2035 ScratchReg0)).addImm(AlignedStackSize)); 2036 } else { 2037 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0) 2038 .addImm(AlignedStackSize)).addReg(0); 2039 } 2040 // Pass second argument for the __morestack by Scratch Register #1. 2041 // The amount size of stack consumed to save function arguments. 2042 if (Thumb) { 2043 AddDefaultPred( 2044 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)) 2045 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))); 2046 } else { 2047 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1) 2048 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))) 2049 .addReg(0); 2050 } 2051 2052 // push {lr} - Save return address of this function. 2053 if (Thumb) { 2054 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))) 2055 .addReg(ARM::LR); 2056 } else { 2057 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD)) 2058 .addReg(ARM::SP, RegState::Define) 2059 .addReg(ARM::SP)) 2060 .addReg(ARM::LR); 2061 } 2062 2063 // Emit the DWARF info about the change in stack as well as where to find the 2064 // previous link register 2065 CFIIndex = 2066 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12)); 2067 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2068 .addCFIIndex(CFIIndex); 2069 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 2070 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12)); 2071 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2072 .addCFIIndex(CFIIndex); 2073 2074 // Call __morestack(). 2075 if (Thumb) { 2076 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL))) 2077 .addExternalSymbol("__morestack"); 2078 } else { 2079 BuildMI(AllocMBB, DL, TII.get(ARM::BL)) 2080 .addExternalSymbol("__morestack"); 2081 } 2082 2083 // pop {lr} - Restore return address of this original function. 2084 if (Thumb) { 2085 if (ST->isThumb1Only()) { 2086 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))) 2087 .addReg(ScratchReg0); 2088 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR) 2089 .addReg(ScratchReg0)); 2090 } else { 2091 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST)) 2092 .addReg(ARM::LR, RegState::Define) 2093 .addReg(ARM::SP, RegState::Define) 2094 .addReg(ARM::SP) 2095 .addImm(4)); 2096 } 2097 } else { 2098 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 2099 .addReg(ARM::SP, RegState::Define) 2100 .addReg(ARM::SP)) 2101 .addReg(ARM::LR); 2102 } 2103 2104 // Restore SR0 and SR1 in case of __morestack() was called. 2105 // __morestack() will skip PostStackMBB block so we need to restore 2106 // scratch registers from here. 2107 // pop {SR0, SR1} 2108 if (Thumb) { 2109 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))) 2110 .addReg(ScratchReg0) 2111 .addReg(ScratchReg1); 2112 } else { 2113 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 2114 .addReg(ARM::SP, RegState::Define) 2115 .addReg(ARM::SP)) 2116 .addReg(ScratchReg0) 2117 .addReg(ScratchReg1); 2118 } 2119 2120 // Update the CFA offset now that we've popped 2121 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0)); 2122 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2123 .addCFIIndex(CFIIndex); 2124 2125 // bx lr - Return from this function. 2126 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET; 2127 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode))); 2128 2129 // Restore SR0 and SR1 in case of __morestack() was not called. 2130 // pop {SR0, SR1} 2131 if (Thumb) { 2132 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))) 2133 .addReg(ScratchReg0) 2134 .addReg(ScratchReg1); 2135 } else { 2136 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD)) 2137 .addReg(ARM::SP, RegState::Define) 2138 .addReg(ARM::SP)) 2139 .addReg(ScratchReg0) 2140 .addReg(ScratchReg1); 2141 } 2142 2143 // Update the CFA offset now that we've popped 2144 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0)); 2145 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2146 .addCFIIndex(CFIIndex); 2147 2148 // Tell debuggers that r4 and r5 are now the same as they were in the 2149 // previous function, that they're the "Same Value". 2150 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue( 2151 nullptr, MRI->getDwarfRegNum(ScratchReg0, true))); 2152 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2153 .addCFIIndex(CFIIndex); 2154 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue( 2155 nullptr, MRI->getDwarfRegNum(ScratchReg1, true))); 2156 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2157 .addCFIIndex(CFIIndex); 2158 2159 // Organizing MBB lists 2160 PostStackMBB->addSuccessor(&prologueMBB); 2161 2162 AllocMBB->addSuccessor(PostStackMBB); 2163 2164 GetMBB->addSuccessor(PostStackMBB); 2165 GetMBB->addSuccessor(AllocMBB); 2166 2167 McrMBB->addSuccessor(GetMBB); 2168 2169 PrevStackMBB->addSuccessor(McrMBB); 2170 2171 #ifdef XDEBUG 2172 MF.verify(); 2173 #endif 2174 } 2175