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