1 //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the ARM implementation of TargetFrameLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 // 13 // This file contains the ARM implementation of TargetFrameLowering class. 14 // 15 // On ARM, stack frames are structured as follows: 16 // 17 // The stack grows downward. 18 // 19 // All of the individual frame areas on the frame below are optional, i.e. it's 20 // possible to create a function so that the particular area isn't present 21 // in the frame. 22 // 23 // At function entry, the "frame" looks as follows: 24 // 25 // | | Higher address 26 // |-----------------------------------| 27 // | | 28 // | arguments passed on the stack | 29 // | | 30 // |-----------------------------------| <- sp 31 // | | Lower address 32 // 33 // 34 // After the prologue has run, the frame has the following general structure. 35 // Technically the last frame area (VLAs) doesn't get created until in the 36 // main function body, after the prologue is run. However, it's depicted here 37 // for completeness. 38 // 39 // | | Higher address 40 // |-----------------------------------| 41 // | | 42 // | arguments passed on the stack | 43 // | | 44 // |-----------------------------------| <- (sp at function entry) 45 // | | 46 // | varargs from registers | 47 // | | 48 // |-----------------------------------| 49 // | | 50 // | prev_fp, prev_lr | 51 // | (a.k.a. "frame record") | 52 // | | 53 // |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11) 54 // | | 55 // | callee-saved gpr registers | 56 // | | 57 // |-----------------------------------| 58 // | | 59 // | callee-saved fp/simd regs | 60 // | | 61 // |-----------------------------------| 62 // |.empty.space.to.make.part.below....| 63 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at 64 // |.the.standard.8-byte.alignment.....| compile time; if present) 65 // |-----------------------------------| 66 // | | 67 // | local variables of fixed size | 68 // | including spill slots | 69 // |-----------------------------------| <- base pointer (not defined by ABI, 70 // |.variable-sized.local.variables....| LLVM chooses r6) 71 // |.(VLAs)............................| (size of this area is unknown at 72 // |...................................| compile time) 73 // |-----------------------------------| <- sp 74 // | | Lower address 75 // 76 // 77 // To access the data in a frame, at-compile time, a constant offset must be 78 // computable from one of the pointers (fp, bp, sp) to access it. The size 79 // of the areas with a dotted background cannot be computed at compile-time 80 // if they are present, making it required to have all three of fp, bp and 81 // sp to be set up to be able to access all contents in the frame areas, 82 // assuming all of the frame areas are non-empty. 83 // 84 // For most functions, some of the frame areas are empty. For those functions, 85 // it may not be necessary to set up fp or bp: 86 // * A base pointer is definitely needed when there are both VLAs and local 87 // variables with more-than-default alignment requirements. 88 // * A frame pointer is definitely needed when there are local variables with 89 // more-than-default alignment requirements. 90 // 91 // In some cases when a base pointer is not strictly needed, it is generated 92 // anyway when offsets from the frame pointer to access local variables become 93 // so large that the offset can't be encoded in the immediate fields of loads 94 // or stores. 95 // 96 // The frame pointer might be chosen to be r7 or r11, depending on the target 97 // architecture and operating system. See ARMSubtarget::getFramePointerReg for 98 // details. 99 // 100 // Outgoing function arguments must be at the bottom of the stack frame when 101 // calling another function. If we do not have variable-sized stack objects, we 102 // can allocate a "reserved call frame" area at the bottom of the local 103 // variable area, large enough for all outgoing calls. If we do have VLAs, then 104 // the stack pointer must be decremented and incremented around each call to 105 // make space for the arguments below the VLAs. 106 // 107 //===----------------------------------------------------------------------===// 108 109 #include "ARMFrameLowering.h" 110 #include "ARMBaseInstrInfo.h" 111 #include "ARMBaseRegisterInfo.h" 112 #include "ARMConstantPoolValue.h" 113 #include "ARMMachineFunctionInfo.h" 114 #include "ARMSubtarget.h" 115 #include "MCTargetDesc/ARMAddressingModes.h" 116 #include "MCTargetDesc/ARMBaseInfo.h" 117 #include "Utils/ARMBaseInfo.h" 118 #include "llvm/ADT/BitVector.h" 119 #include "llvm/ADT/STLExtras.h" 120 #include "llvm/ADT/SmallPtrSet.h" 121 #include "llvm/ADT/SmallVector.h" 122 #include "llvm/CodeGen/MachineBasicBlock.h" 123 #include "llvm/CodeGen/MachineConstantPool.h" 124 #include "llvm/CodeGen/MachineFrameInfo.h" 125 #include "llvm/CodeGen/MachineFunction.h" 126 #include "llvm/CodeGen/MachineInstr.h" 127 #include "llvm/CodeGen/MachineInstrBuilder.h" 128 #include "llvm/CodeGen/MachineJumpTableInfo.h" 129 #include "llvm/CodeGen/MachineModuleInfo.h" 130 #include "llvm/CodeGen/MachineOperand.h" 131 #include "llvm/CodeGen/MachineRegisterInfo.h" 132 #include "llvm/CodeGen/RegisterScavenging.h" 133 #include "llvm/CodeGen/TargetInstrInfo.h" 134 #include "llvm/CodeGen/TargetOpcodes.h" 135 #include "llvm/CodeGen/TargetRegisterInfo.h" 136 #include "llvm/CodeGen/TargetSubtargetInfo.h" 137 #include "llvm/IR/Attributes.h" 138 #include "llvm/IR/CallingConv.h" 139 #include "llvm/IR/DebugLoc.h" 140 #include "llvm/IR/Function.h" 141 #include "llvm/MC/MCContext.h" 142 #include "llvm/MC/MCDwarf.h" 143 #include "llvm/MC/MCInstrDesc.h" 144 #include "llvm/MC/MCRegisterInfo.h" 145 #include "llvm/Support/CodeGen.h" 146 #include "llvm/Support/CommandLine.h" 147 #include "llvm/Support/Compiler.h" 148 #include "llvm/Support/Debug.h" 149 #include "llvm/Support/ErrorHandling.h" 150 #include "llvm/Support/MathExtras.h" 151 #include "llvm/Support/raw_ostream.h" 152 #include "llvm/Target/TargetMachine.h" 153 #include "llvm/Target/TargetOptions.h" 154 #include <algorithm> 155 #include <cassert> 156 #include <cstddef> 157 #include <cstdint> 158 #include <iterator> 159 #include <utility> 160 #include <vector> 161 162 #define DEBUG_TYPE "arm-frame-lowering" 163 164 using namespace llvm; 165 166 static cl::opt<bool> 167 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), 168 cl::desc("Align ARM NEON spills in prolog and epilog")); 169 170 static MachineBasicBlock::iterator 171 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 172 unsigned NumAlignedDPRCS2Regs); 173 174 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti) 175 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)), 176 STI(sti) {} 177 178 bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const { 179 // iOS always has a FP for backtracking, force other targets to keep their FP 180 // when doing FastISel. The emitted code is currently superior, and in cases 181 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated. 182 return MF.getSubtarget<ARMSubtarget>().useFastISel(); 183 } 184 185 /// Returns true if the target can safely skip saving callee-saved registers 186 /// for noreturn nounwind functions. 187 bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const { 188 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) && 189 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) && 190 !MF.getFunction().hasFnAttribute(Attribute::UWTable)); 191 192 // Frame pointer and link register are not treated as normal CSR, thus we 193 // can always skip CSR saves for nonreturning functions. 194 return true; 195 } 196 197 /// hasFP - Return true if the specified function should have a dedicated frame 198 /// pointer register. This is true if the function has variable sized allocas 199 /// or if frame pointer elimination is disabled. 200 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const { 201 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 202 const MachineFrameInfo &MFI = MF.getFrameInfo(); 203 204 // ABI-required frame pointer. 205 if (MF.getTarget().Options.DisableFramePointerElim(MF)) 206 return true; 207 208 // Frame pointer required for use within this function. 209 return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() || 210 MFI.isFrameAddressTaken()); 211 } 212 213 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 214 /// not required, we reserve argument space for call sites in the function 215 /// immediately on entry to the current function. This eliminates the need for 216 /// add/sub sp brackets around call sites. Returns true if the call frame is 217 /// included as part of the stack frame. 218 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 219 const MachineFrameInfo &MFI = MF.getFrameInfo(); 220 unsigned CFSize = MFI.getMaxCallFrameSize(); 221 // It's not always a good idea to include the call frame as part of the 222 // stack frame. ARM (especially Thumb) has small immediate offset to 223 // address the stack frame. So a large call frame can cause poor codegen 224 // and may even makes it impossible to scavenge a register. 225 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 226 return false; 227 228 return !MFI.hasVarSizedObjects(); 229 } 230 231 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 232 /// call frame pseudos can be simplified. Unlike most targets, having a FP 233 /// is not sufficient here since we still may reference some objects via SP 234 /// even when FP is available in Thumb2 mode. 235 bool 236 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 237 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects(); 238 } 239 240 // Returns how much of the incoming argument stack area we should clean up in an 241 // epilogue. For the C calling convention this will be 0, for guaranteed tail 242 // call conventions it can be positive (a normal return or a tail call to a 243 // function that uses less stack space for arguments) or negative (for a tail 244 // call to a function that needs more stack space than us for arguments). 245 static int getArgumentStackToRestore(MachineFunction &MF, 246 MachineBasicBlock &MBB) { 247 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 248 bool IsTailCallReturn = false; 249 if (MBB.end() != MBBI) { 250 unsigned RetOpcode = MBBI->getOpcode(); 251 IsTailCallReturn = RetOpcode == ARM::TCRETURNdi || 252 RetOpcode == ARM::TCRETURNri; 253 } 254 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 255 256 int ArgumentPopSize = 0; 257 if (IsTailCallReturn) { 258 MachineOperand &StackAdjust = MBBI->getOperand(1); 259 260 // For a tail-call in a callee-pops-arguments environment, some or all of 261 // the stack may actually be in use for the call's arguments, this is 262 // calculated during LowerCall and consumed here... 263 ArgumentPopSize = StackAdjust.getImm(); 264 } else { 265 // ... otherwise the amount to pop is *all* of the argument space, 266 // conveniently stored in the MachineFunctionInfo by 267 // LowerFormalArguments. This will, of course, be zero for the C calling 268 // convention. 269 ArgumentPopSize = AFI->getArgumentStackToRestore(); 270 } 271 272 return ArgumentPopSize; 273 } 274 275 static void emitRegPlusImmediate( 276 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, 277 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg, 278 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags, 279 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) { 280 if (isARM) 281 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 282 Pred, PredReg, TII, MIFlags); 283 else 284 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 285 Pred, PredReg, TII, MIFlags); 286 } 287 288 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, 289 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, 290 const ARMBaseInstrInfo &TII, int NumBytes, 291 unsigned MIFlags = MachineInstr::NoFlags, 292 ARMCC::CondCodes Pred = ARMCC::AL, 293 unsigned PredReg = 0) { 294 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes, 295 MIFlags, Pred, PredReg); 296 } 297 298 static int sizeOfSPAdjustment(const MachineInstr &MI) { 299 int RegSize; 300 switch (MI.getOpcode()) { 301 case ARM::VSTMDDB_UPD: 302 RegSize = 8; 303 break; 304 case ARM::STMDB_UPD: 305 case ARM::t2STMDB_UPD: 306 RegSize = 4; 307 break; 308 case ARM::t2STR_PRE: 309 case ARM::STR_PRE_IMM: 310 return 4; 311 default: 312 llvm_unreachable("Unknown push or pop like instruction"); 313 } 314 315 int count = 0; 316 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 317 // pred) so the list starts at 4. 318 for (int i = MI.getNumOperands() - 1; i >= 4; --i) 319 count += RegSize; 320 return count; 321 } 322 323 static bool WindowsRequiresStackProbe(const MachineFunction &MF, 324 size_t StackSizeInBytes) { 325 const MachineFrameInfo &MFI = MF.getFrameInfo(); 326 const Function &F = MF.getFunction(); 327 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096; 328 if (F.hasFnAttribute("stack-probe-size")) 329 F.getFnAttribute("stack-probe-size") 330 .getValueAsString() 331 .getAsInteger(0, StackProbeSize); 332 return (StackSizeInBytes >= StackProbeSize) && 333 !F.hasFnAttribute("no-stack-arg-probe"); 334 } 335 336 namespace { 337 338 struct StackAdjustingInsts { 339 struct InstInfo { 340 MachineBasicBlock::iterator I; 341 unsigned SPAdjust; 342 bool BeforeFPSet; 343 }; 344 345 SmallVector<InstInfo, 4> Insts; 346 347 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust, 348 bool BeforeFPSet = false) { 349 InstInfo Info = {I, SPAdjust, BeforeFPSet}; 350 Insts.push_back(Info); 351 } 352 353 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) { 354 auto Info = 355 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; }); 356 assert(Info != Insts.end() && "invalid sp adjusting instruction"); 357 Info->SPAdjust += ExtraBytes; 358 } 359 360 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl, 361 const ARMBaseInstrInfo &TII, bool HasFP) { 362 MachineFunction &MF = *MBB.getParent(); 363 unsigned CFAOffset = 0; 364 for (auto &Info : Insts) { 365 if (HasFP && !Info.BeforeFPSet) 366 return; 367 368 CFAOffset += Info.SPAdjust; 369 unsigned CFIIndex = MF.addFrameInst( 370 MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset)); 371 BuildMI(MBB, std::next(Info.I), dl, 372 TII.get(TargetOpcode::CFI_INSTRUCTION)) 373 .addCFIIndex(CFIIndex) 374 .setMIFlags(MachineInstr::FrameSetup); 375 } 376 } 377 }; 378 379 } // end anonymous namespace 380 381 /// Emit an instruction sequence that will align the address in 382 /// register Reg by zero-ing out the lower bits. For versions of the 383 /// architecture that support Neon, this must be done in a single 384 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a 385 /// single instruction. That function only gets called when optimizing 386 /// spilling of D registers on a core with the Neon instruction set 387 /// present. 388 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI, 389 const TargetInstrInfo &TII, 390 MachineBasicBlock &MBB, 391 MachineBasicBlock::iterator MBBI, 392 const DebugLoc &DL, const unsigned Reg, 393 const Align Alignment, 394 const bool MustBeSingleInstruction) { 395 const ARMSubtarget &AST = MF.getSubtarget<ARMSubtarget>(); 396 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops(); 397 const unsigned AlignMask = Alignment.value() - 1U; 398 const unsigned NrBitsToZero = Log2(Alignment); 399 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported"); 400 if (!AFI->isThumbFunction()) { 401 // if the BFC instruction is available, use that to zero the lower 402 // bits: 403 // bfc Reg, #0, log2(Alignment) 404 // otherwise use BIC, if the mask to zero the required number of bits 405 // can be encoded in the bic immediate field 406 // bic Reg, Reg, Alignment-1 407 // otherwise, emit 408 // lsr Reg, Reg, log2(Alignment) 409 // lsl Reg, Reg, log2(Alignment) 410 if (CanUseBFC) { 411 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg) 412 .addReg(Reg, RegState::Kill) 413 .addImm(~AlignMask) 414 .add(predOps(ARMCC::AL)); 415 } else if (AlignMask <= 255) { 416 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg) 417 .addReg(Reg, RegState::Kill) 418 .addImm(AlignMask) 419 .add(predOps(ARMCC::AL)) 420 .add(condCodeOp()); 421 } else { 422 assert(!MustBeSingleInstruction && 423 "Shouldn't call emitAligningInstructions demanding a single " 424 "instruction to be emitted for large stack alignment for a target " 425 "without BFC."); 426 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 427 .addReg(Reg, RegState::Kill) 428 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero)) 429 .add(predOps(ARMCC::AL)) 430 .add(condCodeOp()); 431 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 432 .addReg(Reg, RegState::Kill) 433 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero)) 434 .add(predOps(ARMCC::AL)) 435 .add(condCodeOp()); 436 } 437 } else { 438 // Since this is only reached for Thumb-2 targets, the BFC instruction 439 // should always be available. 440 assert(CanUseBFC); 441 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg) 442 .addReg(Reg, RegState::Kill) 443 .addImm(~AlignMask) 444 .add(predOps(ARMCC::AL)); 445 } 446 } 447 448 /// We need the offset of the frame pointer relative to other MachineFrameInfo 449 /// offsets which are encoded relative to SP at function begin. 450 /// See also emitPrologue() for how the FP is set up. 451 /// Unfortunately we cannot determine this value in determineCalleeSaves() yet 452 /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use 453 /// this to produce a conservative estimate that we check in an assert() later. 454 static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI) { 455 // For Thumb1, push.w isn't available, so the first push will always push 456 // r7 and lr onto the stack first. 457 if (AFI.isThumb1OnlyFunction()) 458 return -AFI.getArgRegsSaveSize() - (2 * 4); 459 // This is a conservative estimation: Assume the frame pointer being r7 and 460 // pc("r15") up to r8 getting spilled before (= 8 registers). 461 int FPCXTSaveSize = (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0; 462 return - FPCXTSaveSize - AFI.getArgRegsSaveSize() - (8 * 4); 463 } 464 465 void ARMFrameLowering::emitPrologue(MachineFunction &MF, 466 MachineBasicBlock &MBB) const { 467 MachineBasicBlock::iterator MBBI = MBB.begin(); 468 MachineFrameInfo &MFI = MF.getFrameInfo(); 469 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 470 MachineModuleInfo &MMI = MF.getMMI(); 471 MCContext &Context = MMI.getContext(); 472 const TargetMachine &TM = MF.getTarget(); 473 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 474 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo(); 475 const ARMBaseInstrInfo &TII = *STI.getInstrInfo(); 476 assert(!AFI->isThumb1OnlyFunction() && 477 "This emitPrologue does not support Thumb1!"); 478 bool isARM = !AFI->isThumbFunction(); 479 Align Alignment = STI.getFrameLowering()->getStackAlign(); 480 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(); 481 unsigned NumBytes = MFI.getStackSize(); 482 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 483 int FPCXTSaveSize = 0; 484 485 // Debug location must be unknown since the first debug location is used 486 // to determine the end of the prologue. 487 DebugLoc dl; 488 489 Register FramePtr = RegInfo->getFrameRegister(MF); 490 491 // Determine the sizes of each callee-save spill areas and record which frame 492 // belongs to which callee-save spill areas. 493 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 494 int FramePtrSpillFI = 0; 495 int D8SpillFI = 0; 496 497 // All calls are tail calls in GHC calling conv, and functions have no 498 // prologue/epilogue. 499 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 500 return; 501 502 StackAdjustingInsts DefCFAOffsetCandidates; 503 bool HasFP = hasFP(MF); 504 505 if (!AFI->hasStackFrame() && 506 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) { 507 if (NumBytes != 0) { 508 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 509 MachineInstr::FrameSetup); 510 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes, true); 511 } 512 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP); 513 return; 514 } 515 516 // Determine spill area sizes. 517 for (const CalleeSavedInfo &I : CSI) { 518 Register Reg = I.getReg(); 519 int FI = I.getFrameIdx(); 520 switch (Reg) { 521 case ARM::R8: 522 case ARM::R9: 523 case ARM::R10: 524 case ARM::R11: 525 case ARM::R12: 526 if (STI.splitFramePushPop(MF)) { 527 GPRCS2Size += 4; 528 break; 529 } 530 LLVM_FALLTHROUGH; 531 case ARM::R0: 532 case ARM::R1: 533 case ARM::R2: 534 case ARM::R3: 535 case ARM::R4: 536 case ARM::R5: 537 case ARM::R6: 538 case ARM::R7: 539 case ARM::LR: 540 if (Reg == FramePtr) 541 FramePtrSpillFI = FI; 542 GPRCS1Size += 4; 543 break; 544 case ARM::FPCXTNS: 545 FPCXTSaveSize = 4; 546 break; 547 default: 548 // This is a DPR. Exclude the aligned DPRCS2 spills. 549 if (Reg == ARM::D8) 550 D8SpillFI = FI; 551 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) 552 DPRCSSize += 8; 553 } 554 } 555 556 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push; 557 558 // Move past the PAC computation. 559 if (AFI->shouldSignReturnAddress()) 560 LastPush = MBBI++; 561 562 // Move past FPCXT area. 563 if (FPCXTSaveSize > 0) { 564 LastPush = MBBI++; 565 DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, true); 566 } 567 568 // Allocate the vararg register save area. 569 if (ArgRegsSaveSize) { 570 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize, 571 MachineInstr::FrameSetup); 572 LastPush = std::prev(MBBI); 573 DefCFAOffsetCandidates.addInst(LastPush, ArgRegsSaveSize, true); 574 } 575 576 // Move past area 1. 577 if (GPRCS1Size > 0) { 578 GPRCS1Push = LastPush = MBBI++; 579 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true); 580 } 581 582 // Determine starting offsets of spill areas. 583 unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize; 584 unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size; 585 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size; 586 Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4); 587 unsigned DPRGapSize = 588 (GPRCS1Size + GPRCS2Size + FPCXTSaveSize + ArgRegsSaveSize) % 589 DPRAlign.value(); 590 591 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize; 592 int FramePtrOffsetInPush = 0; 593 if (HasFP) { 594 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI); 595 assert(getMaxFPOffset(STI, *AFI) <= FPOffset && 596 "Max FP estimation is wrong"); 597 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize + FPCXTSaveSize; 598 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) + 599 NumBytes); 600 } 601 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 602 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 603 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 604 605 // Move past area 2. 606 if (GPRCS2Size > 0) { 607 GPRCS2Push = LastPush = MBBI++; 608 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size); 609 } 610 611 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our 612 // .cfi_offset operations will reflect that. 613 if (DPRGapSize) { 614 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs"); 615 if (LastPush != MBB.end() && 616 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize)) 617 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize); 618 else { 619 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize, 620 MachineInstr::FrameSetup); 621 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize); 622 } 623 } 624 625 // Move past area 3. 626 if (DPRCSSize > 0) { 627 // Since vpush register list cannot have gaps, there may be multiple vpush 628 // instructions in the prologue. 629 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) { 630 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI)); 631 LastPush = MBBI++; 632 } 633 } 634 635 // Move past the aligned DPRCS2 area. 636 if (AFI->getNumAlignedDPRCS2Regs() > 0) { 637 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs()); 638 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and 639 // leaves the stack pointer pointing to the DPRCS2 area. 640 // 641 // Adjust NumBytes to represent the stack slots below the DPRCS2 area. 642 NumBytes += MFI.getObjectOffset(D8SpillFI); 643 } else 644 NumBytes = DPRCSOffset; 645 646 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) { 647 uint32_t NumWords = NumBytes >> 2; 648 649 if (NumWords < 65536) 650 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4) 651 .addImm(NumWords) 652 .setMIFlags(MachineInstr::FrameSetup) 653 .add(predOps(ARMCC::AL)); 654 else 655 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4) 656 .addImm(NumWords) 657 .setMIFlags(MachineInstr::FrameSetup); 658 659 switch (TM.getCodeModel()) { 660 case CodeModel::Tiny: 661 llvm_unreachable("Tiny code model not available on ARM."); 662 case CodeModel::Small: 663 case CodeModel::Medium: 664 case CodeModel::Kernel: 665 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL)) 666 .add(predOps(ARMCC::AL)) 667 .addExternalSymbol("__chkstk") 668 .addReg(ARM::R4, RegState::Implicit) 669 .setMIFlags(MachineInstr::FrameSetup); 670 break; 671 case CodeModel::Large: 672 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12) 673 .addExternalSymbol("__chkstk") 674 .setMIFlags(MachineInstr::FrameSetup); 675 676 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr)) 677 .add(predOps(ARMCC::AL)) 678 .addReg(ARM::R12, RegState::Kill) 679 .addReg(ARM::R4, RegState::Implicit) 680 .setMIFlags(MachineInstr::FrameSetup); 681 break; 682 } 683 684 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP) 685 .addReg(ARM::SP, RegState::Kill) 686 .addReg(ARM::R4, RegState::Kill) 687 .setMIFlags(MachineInstr::FrameSetup) 688 .add(predOps(ARMCC::AL)) 689 .add(condCodeOp()); 690 NumBytes = 0; 691 } 692 693 if (NumBytes) { 694 // Adjust SP after all the callee-save spills. 695 if (AFI->getNumAlignedDPRCS2Regs() == 0 && 696 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes)) 697 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes); 698 else { 699 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 700 MachineInstr::FrameSetup); 701 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes); 702 } 703 704 if (HasFP && isARM) 705 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 706 // Note it's not safe to do this in Thumb2 mode because it would have 707 // taken two instructions: 708 // mov sp, r7 709 // sub sp, #24 710 // If an interrupt is taken between the two instructions, then sp is in 711 // an inconsistent state (pointing to the middle of callee-saved area). 712 // The interrupt handler can end up clobbering the registers. 713 AFI->setShouldRestoreSPFromFP(true); 714 } 715 716 // Set FP to point to the stack slot that contains the previous FP. 717 // For iOS, FP is R7, which has now been stored in spill area 1. 718 // Otherwise, if this is not iOS, all the callee-saved registers go 719 // into spill area 1, including the FP in R11. In either case, it 720 // is in area one and the adjustment needs to take place just after 721 // that push. 722 if (HasFP) { 723 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push); 724 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push); 725 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, 726 dl, TII, FramePtr, ARM::SP, 727 PushSize + FramePtrOffsetInPush, 728 MachineInstr::FrameSetup); 729 if (FramePtrOffsetInPush + PushSize != 0) { 730 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa( 731 nullptr, MRI->getDwarfRegNum(FramePtr, true), 732 FPCXTSaveSize + ArgRegsSaveSize - FramePtrOffsetInPush)); 733 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 734 .addCFIIndex(CFIIndex) 735 .setMIFlags(MachineInstr::FrameSetup); 736 } else { 737 unsigned CFIIndex = 738 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister( 739 nullptr, MRI->getDwarfRegNum(FramePtr, true))); 740 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 741 .addCFIIndex(CFIIndex) 742 .setMIFlags(MachineInstr::FrameSetup); 743 } 744 } 745 746 // Now that the prologue's actual instructions are finalised, we can insert 747 // the necessary DWARF cf instructions to describe the situation. Start by 748 // recording where each register ended up: 749 if (GPRCS1Size > 0) { 750 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push); 751 int CFIIndex; 752 for (const auto &Entry : CSI) { 753 Register Reg = Entry.getReg(); 754 int FI = Entry.getFrameIdx(); 755 switch (Reg) { 756 case ARM::R8: 757 case ARM::R9: 758 case ARM::R10: 759 case ARM::R11: 760 case ARM::R12: 761 if (STI.splitFramePushPop(MF)) 762 break; 763 LLVM_FALLTHROUGH; 764 case ARM::R0: 765 case ARM::R1: 766 case ARM::R2: 767 case ARM::R3: 768 case ARM::R4: 769 case ARM::R5: 770 case ARM::R6: 771 case ARM::R7: 772 case ARM::LR: 773 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 774 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI))); 775 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 776 .addCFIIndex(CFIIndex) 777 .setMIFlags(MachineInstr::FrameSetup); 778 break; 779 } 780 } 781 } 782 783 if (GPRCS2Size > 0) { 784 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push); 785 for (const auto &Entry : CSI) { 786 Register Reg = Entry.getReg(); 787 int FI = Entry.getFrameIdx(); 788 switch (Reg) { 789 case ARM::R8: 790 case ARM::R9: 791 case ARM::R10: 792 case ARM::R11: 793 case ARM::R12: 794 if (STI.splitFramePushPop(MF)) { 795 unsigned DwarfReg = MRI->getDwarfRegNum( 796 Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg, true); 797 unsigned Offset = MFI.getObjectOffset(FI); 798 unsigned CFIIndex = MF.addFrameInst( 799 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 800 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 801 .addCFIIndex(CFIIndex) 802 .setMIFlags(MachineInstr::FrameSetup); 803 } 804 break; 805 } 806 } 807 } 808 809 if (DPRCSSize > 0) { 810 // Since vpush register list cannot have gaps, there may be multiple vpush 811 // instructions in the prologue. 812 MachineBasicBlock::iterator Pos = std::next(LastPush); 813 for (const auto &Entry : CSI) { 814 Register Reg = Entry.getReg(); 815 int FI = Entry.getFrameIdx(); 816 if ((Reg >= ARM::D0 && Reg <= ARM::D31) && 817 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) { 818 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 819 unsigned Offset = MFI.getObjectOffset(FI); 820 unsigned CFIIndex = MF.addFrameInst( 821 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 822 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 823 .addCFIIndex(CFIIndex) 824 .setMIFlags(MachineInstr::FrameSetup); 825 } 826 } 827 } 828 829 // Now we can emit descriptions of where the canonical frame address was 830 // throughout the process. If we have a frame pointer, it takes over the job 831 // half-way through, so only the first few .cfi_def_cfa_offset instructions 832 // actually get emitted. 833 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP); 834 835 if (STI.isTargetELF() && hasFP(MF)) 836 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() - 837 AFI->getFramePtrSpillOffset()); 838 839 AFI->setFPCXTSaveAreaSize(FPCXTSaveSize); 840 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 841 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 842 AFI->setDPRCalleeSavedGapSize(DPRGapSize); 843 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 844 845 // If we need dynamic stack realignment, do it here. Be paranoid and make 846 // sure if we also have VLAs, we have a base pointer for frame access. 847 // If aligned NEON registers were spilled, the stack has already been 848 // realigned. 849 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) { 850 Align MaxAlign = MFI.getMaxAlign(); 851 assert(!AFI->isThumb1OnlyFunction()); 852 if (!AFI->isThumbFunction()) { 853 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign, 854 false); 855 } else { 856 // We cannot use sp as source/dest register here, thus we're using r4 to 857 // perform the calculations. We're emitting the following sequence: 858 // mov r4, sp 859 // -- use emitAligningInstructions to produce best sequence to zero 860 // -- out lower bits in r4 861 // mov sp, r4 862 // FIXME: It will be better just to find spare register here. 863 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4) 864 .addReg(ARM::SP, RegState::Kill) 865 .add(predOps(ARMCC::AL)); 866 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign, 867 false); 868 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 869 .addReg(ARM::R4, RegState::Kill) 870 .add(predOps(ARMCC::AL)); 871 } 872 873 AFI->setShouldRestoreSPFromFP(true); 874 } 875 876 // If we need a base pointer, set it up here. It's whatever the value 877 // of the stack pointer is at this point. Any variable size objects 878 // will be allocated after this, so we can still use the base pointer 879 // to reference locals. 880 // FIXME: Clarify FrameSetup flags here. 881 if (RegInfo->hasBasePointer(MF)) { 882 if (isARM) 883 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 884 .addReg(ARM::SP) 885 .add(predOps(ARMCC::AL)) 886 .add(condCodeOp()); 887 else 888 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister()) 889 .addReg(ARM::SP) 890 .add(predOps(ARMCC::AL)); 891 } 892 893 // If the frame has variable sized objects then the epilogue must restore 894 // the sp from fp. We can assume there's an FP here since hasFP already 895 // checks for hasVarSizedObjects. 896 if (MFI.hasVarSizedObjects()) 897 AFI->setShouldRestoreSPFromFP(true); 898 } 899 900 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 901 MachineBasicBlock &MBB) const { 902 MachineFrameInfo &MFI = MF.getFrameInfo(); 903 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 904 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 905 const ARMBaseInstrInfo &TII = 906 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 907 assert(!AFI->isThumb1OnlyFunction() && 908 "This emitEpilogue does not support Thumb1!"); 909 bool isARM = !AFI->isThumbFunction(); 910 911 // Amount of stack space we reserved next to incoming args for either 912 // varargs registers or stack arguments in tail calls made by this function. 913 unsigned ReservedArgStack = AFI->getArgRegsSaveSize(); 914 915 // How much of the stack used by incoming arguments this function is expected 916 // to restore in this particular epilogue. 917 int IncomingArgStackToRestore = getArgumentStackToRestore(MF, MBB); 918 int NumBytes = (int)MFI.getStackSize(); 919 Register FramePtr = RegInfo->getFrameRegister(MF); 920 921 // All calls are tail calls in GHC calling conv, and functions have no 922 // prologue/epilogue. 923 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 924 return; 925 926 // First put ourselves on the first (from top) terminator instructions. 927 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); 928 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 929 930 if (!AFI->hasStackFrame()) { 931 if (NumBytes + IncomingArgStackToRestore != 0) 932 emitSPUpdate(isARM, MBB, MBBI, dl, TII, 933 NumBytes + IncomingArgStackToRestore, 934 MachineInstr::FrameDestroy); 935 } else { 936 // Unwind MBBI to point to first LDR / VLDRD. 937 if (MBBI != MBB.begin()) { 938 do { 939 --MBBI; 940 } while (MBBI != MBB.begin() && 941 MBBI->getFlag(MachineInstr::FrameDestroy)); 942 if (!MBBI->getFlag(MachineInstr::FrameDestroy)) 943 ++MBBI; 944 } 945 946 // Move SP to start of FP callee save spill area. 947 NumBytes -= (ReservedArgStack + 948 AFI->getFPCXTSaveAreaSize() + 949 AFI->getGPRCalleeSavedArea1Size() + 950 AFI->getGPRCalleeSavedArea2Size() + 951 AFI->getDPRCalleeSavedGapSize() + 952 AFI->getDPRCalleeSavedAreaSize()); 953 954 // Reset SP based on frame pointer only if the stack frame extends beyond 955 // frame pointer stack slot or target is ELF and the function has FP. 956 if (AFI->shouldRestoreSPFromFP()) { 957 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 958 if (NumBytes) { 959 if (isARM) 960 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 961 ARMCC::AL, 0, TII, 962 MachineInstr::FrameDestroy); 963 else { 964 // It's not possible to restore SP from FP in a single instruction. 965 // For iOS, this looks like: 966 // mov sp, r7 967 // sub sp, #24 968 // This is bad, if an interrupt is taken after the mov, sp is in an 969 // inconsistent state. 970 // Use the first callee-saved register as a scratch register. 971 assert(!MFI.getPristineRegs(MF).test(ARM::R4) && 972 "No scratch register to restore SP from FP!"); 973 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 974 ARMCC::AL, 0, TII, MachineInstr::FrameDestroy); 975 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 976 .addReg(ARM::R4) 977 .add(predOps(ARMCC::AL)) 978 .setMIFlag(MachineInstr::FrameDestroy); 979 } 980 } else { 981 // Thumb2 or ARM. 982 if (isARM) 983 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 984 .addReg(FramePtr) 985 .add(predOps(ARMCC::AL)) 986 .add(condCodeOp()) 987 .setMIFlag(MachineInstr::FrameDestroy); 988 else 989 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 990 .addReg(FramePtr) 991 .add(predOps(ARMCC::AL)) 992 .setMIFlag(MachineInstr::FrameDestroy); 993 } 994 } else if (NumBytes && 995 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes)) 996 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes, 997 MachineInstr::FrameDestroy); 998 999 // Increment past our save areas. 1000 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) { 1001 MBBI++; 1002 // Since vpop register list cannot have gaps, there may be multiple vpop 1003 // instructions in the epilogue. 1004 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD) 1005 MBBI++; 1006 } 1007 if (AFI->getDPRCalleeSavedGapSize()) { 1008 assert(AFI->getDPRCalleeSavedGapSize() == 4 && 1009 "unexpected DPR alignment gap"); 1010 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(), 1011 MachineInstr::FrameDestroy); 1012 } 1013 1014 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++; 1015 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 1016 1017 if (ReservedArgStack || IncomingArgStackToRestore) { 1018 assert((int)ReservedArgStack + IncomingArgStackToRestore >= 0 && 1019 "attempting to restore negative stack amount"); 1020 emitSPUpdate(isARM, MBB, MBBI, dl, TII, 1021 ReservedArgStack + IncomingArgStackToRestore, 1022 MachineInstr::FrameDestroy); 1023 } 1024 1025 // Validate PAC, It should have been already popped into R12. For CMSE entry 1026 // function, the validation instruction is emitted during expansion of the 1027 // tBXNS_RET, since the validation must use the value of SP at function 1028 // entry, before saving, resp. after restoring, FPCXTNS. 1029 if (AFI->shouldSignReturnAddress() && !AFI->isCmseNSEntryFunction()) 1030 BuildMI(MBB, MBBI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2AUT)); 1031 } 1032 } 1033 1034 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 1035 /// debug info. It's the same as what we use for resolving the code-gen 1036 /// references for now. FIXME: This can go wrong when references are 1037 /// SP-relative and simple call frames aren't used. 1038 StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, 1039 int FI, 1040 Register &FrameReg) const { 1041 return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0)); 1042 } 1043 1044 int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 1045 int FI, Register &FrameReg, 1046 int SPAdj) const { 1047 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1048 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 1049 MF.getSubtarget().getRegisterInfo()); 1050 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1051 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize(); 1052 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 1053 bool isFixed = MFI.isFixedObjectIndex(FI); 1054 1055 FrameReg = ARM::SP; 1056 Offset += SPAdj; 1057 1058 // SP can move around if there are allocas. We may also lose track of SP 1059 // when emergency spilling inside a non-reserved call frame setup. 1060 bool hasMovingSP = !hasReservedCallFrame(MF); 1061 1062 // When dynamically realigning the stack, use the frame pointer for 1063 // parameters, and the stack/base pointer for locals. 1064 if (RegInfo->hasStackRealignment(MF)) { 1065 assert(hasFP(MF) && "dynamic stack realignment without a FP!"); 1066 if (isFixed) { 1067 FrameReg = RegInfo->getFrameRegister(MF); 1068 Offset = FPOffset; 1069 } else if (hasMovingSP) { 1070 assert(RegInfo->hasBasePointer(MF) && 1071 "VLAs and dynamic stack alignment, but missing base pointer!"); 1072 FrameReg = RegInfo->getBaseRegister(); 1073 Offset -= SPAdj; 1074 } 1075 return Offset; 1076 } 1077 1078 // If there is a frame pointer, use it when we can. 1079 if (hasFP(MF) && AFI->hasStackFrame()) { 1080 // Use frame pointer to reference fixed objects. Use it for locals if 1081 // there are VLAs (and thus the SP isn't reliable as a base). 1082 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) { 1083 FrameReg = RegInfo->getFrameRegister(MF); 1084 return FPOffset; 1085 } else if (hasMovingSP) { 1086 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 1087 if (AFI->isThumb2Function()) { 1088 // Try to use the frame pointer if we can, else use the base pointer 1089 // since it's available. This is handy for the emergency spill slot, in 1090 // particular. 1091 if (FPOffset >= -255 && FPOffset < 0) { 1092 FrameReg = RegInfo->getFrameRegister(MF); 1093 return FPOffset; 1094 } 1095 } 1096 } else if (AFI->isThumbFunction()) { 1097 // Prefer SP to base pointer, if the offset is suitably aligned and in 1098 // range as the effective range of the immediate offset is bigger when 1099 // basing off SP. 1100 // Use add <rd>, sp, #<imm8> 1101 // ldr <rd>, [sp, #<imm8>] 1102 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020) 1103 return Offset; 1104 // In Thumb2 mode, the negative offset is very limited. Try to avoid 1105 // out of range references. ldr <rt>,[<rn>, #-<imm8>] 1106 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) { 1107 FrameReg = RegInfo->getFrameRegister(MF); 1108 return FPOffset; 1109 } 1110 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 1111 // Otherwise, use SP or FP, whichever is closer to the stack slot. 1112 FrameReg = RegInfo->getFrameRegister(MF); 1113 return FPOffset; 1114 } 1115 } 1116 // Use the base pointer if we have one. 1117 // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper? 1118 // That can happen if we forced a base pointer for a large call frame. 1119 if (RegInfo->hasBasePointer(MF)) { 1120 FrameReg = RegInfo->getBaseRegister(); 1121 Offset -= SPAdj; 1122 } 1123 return Offset; 1124 } 1125 1126 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 1127 MachineBasicBlock::iterator MI, 1128 ArrayRef<CalleeSavedInfo> CSI, 1129 unsigned StmOpc, unsigned StrOpc, 1130 bool NoGap, bool (*Func)(unsigned, bool), 1131 unsigned NumAlignedDPRCS2Regs, 1132 unsigned MIFlags) const { 1133 MachineFunction &MF = *MBB.getParent(); 1134 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1135 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 1136 1137 DebugLoc DL; 1138 1139 using RegAndKill = std::pair<unsigned, bool>; 1140 1141 SmallVector<RegAndKill, 4> Regs; 1142 unsigned i = CSI.size(); 1143 while (i != 0) { 1144 unsigned LastReg = 0; 1145 for (; i != 0; --i) { 1146 Register Reg = CSI[i-1].getReg(); 1147 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue; 1148 1149 // D-registers in the aligned area DPRCS2 are NOT spilled here. 1150 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 1151 continue; 1152 1153 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1154 bool isLiveIn = MRI.isLiveIn(Reg); 1155 if (!isLiveIn && !MRI.isReserved(Reg)) 1156 MBB.addLiveIn(Reg); 1157 // If NoGap is true, push consecutive registers and then leave the rest 1158 // for other instructions. e.g. 1159 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 1160 if (NoGap && LastReg && LastReg != Reg-1) 1161 break; 1162 LastReg = Reg; 1163 // Do not set a kill flag on values that are also marked as live-in. This 1164 // happens with the @llvm-returnaddress intrinsic and with arguments 1165 // passed in callee saved registers. 1166 // Omitting the kill flags is conservatively correct even if the live-in 1167 // is not used after all. 1168 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn)); 1169 } 1170 1171 if (Regs.empty()) 1172 continue; 1173 1174 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) { 1175 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first); 1176 }); 1177 1178 if (Regs.size() > 1 || StrOpc== 0) { 1179 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 1180 .addReg(ARM::SP) 1181 .setMIFlags(MIFlags) 1182 .add(predOps(ARMCC::AL)); 1183 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 1184 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 1185 } else if (Regs.size() == 1) { 1186 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP) 1187 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 1188 .addReg(ARM::SP) 1189 .setMIFlags(MIFlags) 1190 .addImm(-4) 1191 .add(predOps(ARMCC::AL)); 1192 } 1193 Regs.clear(); 1194 1195 // Put any subsequent vpush instructions before this one: they will refer to 1196 // higher register numbers so need to be pushed first in order to preserve 1197 // monotonicity. 1198 if (MI != MBB.begin()) 1199 --MI; 1200 } 1201 } 1202 1203 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 1204 MachineBasicBlock::iterator MI, 1205 MutableArrayRef<CalleeSavedInfo> CSI, 1206 unsigned LdmOpc, unsigned LdrOpc, 1207 bool isVarArg, bool NoGap, 1208 bool (*Func)(unsigned, bool), 1209 unsigned NumAlignedDPRCS2Regs) const { 1210 MachineFunction &MF = *MBB.getParent(); 1211 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1212 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 1213 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1214 bool hasPAC = AFI->shouldSignReturnAddress(); 1215 DebugLoc DL; 1216 bool isTailCall = false; 1217 bool isInterrupt = false; 1218 bool isTrap = false; 1219 bool isCmseEntry = false; 1220 if (MBB.end() != MI) { 1221 DL = MI->getDebugLoc(); 1222 unsigned RetOpcode = MI->getOpcode(); 1223 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri); 1224 isInterrupt = 1225 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR; 1226 isTrap = 1227 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl || 1228 RetOpcode == ARM::tTRAP; 1229 isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET); 1230 } 1231 1232 SmallVector<unsigned, 4> Regs; 1233 unsigned i = CSI.size(); 1234 while (i != 0) { 1235 unsigned LastReg = 0; 1236 bool DeleteRet = false; 1237 for (; i != 0; --i) { 1238 CalleeSavedInfo &Info = CSI[i-1]; 1239 Register Reg = Info.getReg(); 1240 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue; 1241 1242 // The aligned reloads from area DPRCS2 are not inserted here. 1243 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 1244 continue; 1245 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt && 1246 !isCmseEntry && !isTrap && AFI->getArgumentStackToRestore() == 0 && 1247 STI.hasV5TOps() && MBB.succ_empty() && !hasPAC) { 1248 Reg = ARM::PC; 1249 // Fold the return instruction into the LDM. 1250 DeleteRet = true; 1251 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 1252 // We 'restore' LR into PC so it is not live out of the return block: 1253 // Clear Restored bit. 1254 Info.setRestored(false); 1255 } 1256 1257 // If NoGap is true, pop consecutive registers and then leave the rest 1258 // for other instructions. e.g. 1259 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 1260 if (NoGap && LastReg && LastReg != Reg-1) 1261 break; 1262 1263 LastReg = Reg; 1264 Regs.push_back(Reg); 1265 } 1266 1267 if (Regs.empty()) 1268 continue; 1269 1270 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) { 1271 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS); 1272 }); 1273 1274 if (Regs.size() > 1 || LdrOpc == 0) { 1275 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 1276 .addReg(ARM::SP) 1277 .add(predOps(ARMCC::AL)) 1278 .setMIFlags(MachineInstr::FrameDestroy); 1279 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 1280 MIB.addReg(Regs[i], getDefRegState(true)); 1281 if (DeleteRet) { 1282 if (MI != MBB.end()) { 1283 MIB.copyImplicitOps(*MI); 1284 MI->eraseFromParent(); 1285 } 1286 } 1287 MI = MIB; 1288 } else if (Regs.size() == 1) { 1289 // If we adjusted the reg to PC from LR above, switch it back here. We 1290 // only do that for LDM. 1291 if (Regs[0] == ARM::PC) 1292 Regs[0] = ARM::LR; 1293 MachineInstrBuilder MIB = 1294 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 1295 .addReg(ARM::SP, RegState::Define) 1296 .addReg(ARM::SP) 1297 .setMIFlags(MachineInstr::FrameDestroy); 1298 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 1299 // that refactoring is complete (eventually). 1300 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) { 1301 MIB.addReg(0); 1302 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 1303 } else 1304 MIB.addImm(4); 1305 MIB.add(predOps(ARMCC::AL)); 1306 } 1307 Regs.clear(); 1308 1309 // Put any subsequent vpop instructions after this one: they will refer to 1310 // higher register numbers so need to be popped afterwards. 1311 if (MI != MBB.end()) 1312 ++MI; 1313 } 1314 } 1315 1316 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers 1317 /// starting from d8. Also insert stack realignment code and leave the stack 1318 /// pointer pointing to the d8 spill slot. 1319 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, 1320 MachineBasicBlock::iterator MI, 1321 unsigned NumAlignedDPRCS2Regs, 1322 ArrayRef<CalleeSavedInfo> CSI, 1323 const TargetRegisterInfo *TRI) { 1324 MachineFunction &MF = *MBB.getParent(); 1325 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1326 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc(); 1327 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1328 MachineFrameInfo &MFI = MF.getFrameInfo(); 1329 1330 // Mark the D-register spill slots as properly aligned. Since MFI computes 1331 // stack slot layout backwards, this can actually mean that the d-reg stack 1332 // slot offsets can be wrong. The offset for d8 will always be correct. 1333 for (const CalleeSavedInfo &I : CSI) { 1334 unsigned DNum = I.getReg() - ARM::D8; 1335 if (DNum > NumAlignedDPRCS2Regs - 1) 1336 continue; 1337 int FI = I.getFrameIdx(); 1338 // The even-numbered registers will be 16-byte aligned, the odd-numbered 1339 // registers will be 8-byte aligned. 1340 MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16)); 1341 1342 // The stack slot for D8 needs to be maximally aligned because this is 1343 // actually the point where we align the stack pointer. MachineFrameInfo 1344 // computes all offsets relative to the incoming stack pointer which is a 1345 // bit weird when realigning the stack. Any extra padding for this 1346 // over-alignment is not realized because the code inserted below adjusts 1347 // the stack pointer by numregs * 8 before aligning the stack pointer. 1348 if (DNum == 0) 1349 MFI.setObjectAlignment(FI, MFI.getMaxAlign()); 1350 } 1351 1352 // Move the stack pointer to the d8 spill slot, and align it at the same 1353 // time. Leave the stack slot address in the scratch register r4. 1354 // 1355 // sub r4, sp, #numregs * 8 1356 // bic r4, r4, #align - 1 1357 // mov sp, r4 1358 // 1359 bool isThumb = AFI->isThumbFunction(); 1360 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1361 AFI->setShouldRestoreSPFromFP(true); 1362 1363 // sub r4, sp, #numregs * 8 1364 // The immediate is <= 64, so it doesn't need any special encoding. 1365 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri; 1366 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1367 .addReg(ARM::SP) 1368 .addImm(8 * NumAlignedDPRCS2Regs) 1369 .add(predOps(ARMCC::AL)) 1370 .add(condCodeOp()); 1371 1372 Align MaxAlign = MF.getFrameInfo().getMaxAlign(); 1373 // We must set parameter MustBeSingleInstruction to true, since 1374 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform 1375 // stack alignment. Luckily, this can always be done since all ARM 1376 // architecture versions that support Neon also support the BFC 1377 // instruction. 1378 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true); 1379 1380 // mov sp, r4 1381 // The stack pointer must be adjusted before spilling anything, otherwise 1382 // the stack slots could be clobbered by an interrupt handler. 1383 // Leave r4 live, it is used below. 1384 Opc = isThumb ? ARM::tMOVr : ARM::MOVr; 1385 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP) 1386 .addReg(ARM::R4) 1387 .add(predOps(ARMCC::AL)); 1388 if (!isThumb) 1389 MIB.add(condCodeOp()); 1390 1391 // Now spill NumAlignedDPRCS2Regs registers starting from d8. 1392 // r4 holds the stack slot address. 1393 unsigned NextReg = ARM::D8; 1394 1395 // 16-byte aligned vst1.64 with 4 d-regs and address writeback. 1396 // The writeback is only needed when emitting two vst1.64 instructions. 1397 if (NumAlignedDPRCS2Regs >= 6) { 1398 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1399 &ARM::QQPRRegClass); 1400 MBB.addLiveIn(SupReg); 1401 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4) 1402 .addReg(ARM::R4, RegState::Kill) 1403 .addImm(16) 1404 .addReg(NextReg) 1405 .addReg(SupReg, RegState::ImplicitKill) 1406 .add(predOps(ARMCC::AL)); 1407 NextReg += 4; 1408 NumAlignedDPRCS2Regs -= 4; 1409 } 1410 1411 // We won't modify r4 beyond this point. It currently points to the next 1412 // register to be spilled. 1413 unsigned R4BaseReg = NextReg; 1414 1415 // 16-byte aligned vst1.64 with 4 d-regs, no writeback. 1416 if (NumAlignedDPRCS2Regs >= 4) { 1417 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1418 &ARM::QQPRRegClass); 1419 MBB.addLiveIn(SupReg); 1420 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q)) 1421 .addReg(ARM::R4) 1422 .addImm(16) 1423 .addReg(NextReg) 1424 .addReg(SupReg, RegState::ImplicitKill) 1425 .add(predOps(ARMCC::AL)); 1426 NextReg += 4; 1427 NumAlignedDPRCS2Regs -= 4; 1428 } 1429 1430 // 16-byte aligned vst1.64 with 2 d-regs. 1431 if (NumAlignedDPRCS2Regs >= 2) { 1432 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1433 &ARM::QPRRegClass); 1434 MBB.addLiveIn(SupReg); 1435 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64)) 1436 .addReg(ARM::R4) 1437 .addImm(16) 1438 .addReg(SupReg) 1439 .add(predOps(ARMCC::AL)); 1440 NextReg += 2; 1441 NumAlignedDPRCS2Regs -= 2; 1442 } 1443 1444 // Finally, use a vanilla vstr.64 for the odd last register. 1445 if (NumAlignedDPRCS2Regs) { 1446 MBB.addLiveIn(NextReg); 1447 // vstr.64 uses addrmode5 which has an offset scale of 4. 1448 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD)) 1449 .addReg(NextReg) 1450 .addReg(ARM::R4) 1451 .addImm((NextReg - R4BaseReg) * 2) 1452 .add(predOps(ARMCC::AL)); 1453 } 1454 1455 // The last spill instruction inserted should kill the scratch register r4. 1456 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1457 } 1458 1459 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an 1460 /// iterator to the following instruction. 1461 static MachineBasicBlock::iterator 1462 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 1463 unsigned NumAlignedDPRCS2Regs) { 1464 // sub r4, sp, #numregs * 8 1465 // bic r4, r4, #align - 1 1466 // mov sp, r4 1467 ++MI; ++MI; ++MI; 1468 assert(MI->mayStore() && "Expecting spill instruction"); 1469 1470 // These switches all fall through. 1471 switch(NumAlignedDPRCS2Regs) { 1472 case 7: 1473 ++MI; 1474 assert(MI->mayStore() && "Expecting spill instruction"); 1475 LLVM_FALLTHROUGH; 1476 default: 1477 ++MI; 1478 assert(MI->mayStore() && "Expecting spill instruction"); 1479 LLVM_FALLTHROUGH; 1480 case 1: 1481 case 2: 1482 case 4: 1483 assert(MI->killsRegister(ARM::R4) && "Missed kill flag"); 1484 ++MI; 1485 } 1486 return MI; 1487 } 1488 1489 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers 1490 /// starting from d8. These instructions are assumed to execute while the 1491 /// stack is still aligned, unlike the code inserted by emitPopInst. 1492 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, 1493 MachineBasicBlock::iterator MI, 1494 unsigned NumAlignedDPRCS2Regs, 1495 ArrayRef<CalleeSavedInfo> CSI, 1496 const TargetRegisterInfo *TRI) { 1497 MachineFunction &MF = *MBB.getParent(); 1498 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1499 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc(); 1500 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1501 1502 // Find the frame index assigned to d8. 1503 int D8SpillFI = 0; 1504 for (const CalleeSavedInfo &I : CSI) 1505 if (I.getReg() == ARM::D8) { 1506 D8SpillFI = I.getFrameIdx(); 1507 break; 1508 } 1509 1510 // Materialize the address of the d8 spill slot into the scratch register r4. 1511 // This can be fairly complicated if the stack frame is large, so just use 1512 // the normal frame index elimination mechanism to do it. This code runs as 1513 // the initial part of the epilog where the stack and base pointers haven't 1514 // been changed yet. 1515 bool isThumb = AFI->isThumbFunction(); 1516 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1517 1518 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri; 1519 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1520 .addFrameIndex(D8SpillFI) 1521 .addImm(0) 1522 .add(predOps(ARMCC::AL)) 1523 .add(condCodeOp()); 1524 1525 // Now restore NumAlignedDPRCS2Regs registers starting from d8. 1526 unsigned NextReg = ARM::D8; 1527 1528 // 16-byte aligned vld1.64 with 4 d-regs and writeback. 1529 if (NumAlignedDPRCS2Regs >= 6) { 1530 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1531 &ARM::QQPRRegClass); 1532 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg) 1533 .addReg(ARM::R4, RegState::Define) 1534 .addReg(ARM::R4, RegState::Kill) 1535 .addImm(16) 1536 .addReg(SupReg, RegState::ImplicitDefine) 1537 .add(predOps(ARMCC::AL)); 1538 NextReg += 4; 1539 NumAlignedDPRCS2Regs -= 4; 1540 } 1541 1542 // We won't modify r4 beyond this point. It currently points to the next 1543 // register to be spilled. 1544 unsigned R4BaseReg = NextReg; 1545 1546 // 16-byte aligned vld1.64 with 4 d-regs, no writeback. 1547 if (NumAlignedDPRCS2Regs >= 4) { 1548 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1549 &ARM::QQPRRegClass); 1550 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg) 1551 .addReg(ARM::R4) 1552 .addImm(16) 1553 .addReg(SupReg, RegState::ImplicitDefine) 1554 .add(predOps(ARMCC::AL)); 1555 NextReg += 4; 1556 NumAlignedDPRCS2Regs -= 4; 1557 } 1558 1559 // 16-byte aligned vld1.64 with 2 d-regs. 1560 if (NumAlignedDPRCS2Regs >= 2) { 1561 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1562 &ARM::QPRRegClass); 1563 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg) 1564 .addReg(ARM::R4) 1565 .addImm(16) 1566 .add(predOps(ARMCC::AL)); 1567 NextReg += 2; 1568 NumAlignedDPRCS2Regs -= 2; 1569 } 1570 1571 // Finally, use a vanilla vldr.64 for the remaining odd register. 1572 if (NumAlignedDPRCS2Regs) 1573 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg) 1574 .addReg(ARM::R4) 1575 .addImm(2 * (NextReg - R4BaseReg)) 1576 .add(predOps(ARMCC::AL)); 1577 1578 // Last store kills r4. 1579 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1580 } 1581 1582 bool ARMFrameLowering::spillCalleeSavedRegisters( 1583 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 1584 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 1585 if (CSI.empty()) 1586 return false; 1587 1588 MachineFunction &MF = *MBB.getParent(); 1589 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1590 1591 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 1592 unsigned PushOneOpc = AFI->isThumbFunction() ? 1593 ARM::t2STR_PRE : ARM::STR_PRE_IMM; 1594 unsigned FltOpc = ARM::VSTMDDB_UPD; 1595 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1596 // Compute PAC in R12. 1597 if (AFI->shouldSignReturnAddress()) { 1598 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2PAC)) 1599 .setMIFlags(MachineInstr::FrameSetup); 1600 } 1601 // Save the non-secure floating point context. 1602 if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) { 1603 return C.getReg() == ARM::FPCXTNS; 1604 })) { 1605 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre), 1606 ARM::SP) 1607 .addReg(ARM::SP) 1608 .addImm(-4) 1609 .add(predOps(ARMCC::AL)); 1610 } 1611 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0, 1612 MachineInstr::FrameSetup); 1613 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0, 1614 MachineInstr::FrameSetup); 1615 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register, 1616 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup); 1617 1618 // The code above does not insert spill code for the aligned DPRCS2 registers. 1619 // The stack realignment code will be inserted between the push instructions 1620 // and these spills. 1621 if (NumAlignedDPRCS2Regs) 1622 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1623 1624 return true; 1625 } 1626 1627 bool ARMFrameLowering::restoreCalleeSavedRegisters( 1628 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 1629 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 1630 if (CSI.empty()) 1631 return false; 1632 1633 MachineFunction &MF = *MBB.getParent(); 1634 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1635 bool isVarArg = AFI->getArgRegsSaveSize() > 0; 1636 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1637 1638 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2 1639 // registers. Do that here instead. 1640 if (NumAlignedDPRCS2Regs) 1641 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1642 1643 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 1644 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM; 1645 unsigned FltOpc = ARM::VLDMDIA_UPD; 1646 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register, 1647 NumAlignedDPRCS2Regs); 1648 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1649 &isARMArea2Register, 0); 1650 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1651 &isARMArea1Register, 0); 1652 1653 return true; 1654 } 1655 1656 // FIXME: Make generic? 1657 static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF, 1658 const ARMBaseInstrInfo &TII) { 1659 unsigned FnSize = 0; 1660 for (auto &MBB : MF) { 1661 for (auto &MI : MBB) 1662 FnSize += TII.getInstSizeInBytes(MI); 1663 } 1664 if (MF.getJumpTableInfo()) 1665 for (auto &Table: MF.getJumpTableInfo()->getJumpTables()) 1666 FnSize += Table.MBBs.size() * 4; 1667 FnSize += MF.getConstantPool()->getConstants().size() * 4; 1668 return FnSize; 1669 } 1670 1671 /// estimateRSStackSizeLimit - Look at each instruction that references stack 1672 /// frames and return the stack size limit beyond which some of these 1673 /// instructions will require a scratch register during their expansion later. 1674 // FIXME: Move to TII? 1675 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 1676 const TargetFrameLowering *TFI, 1677 bool &HasNonSPFrameIndex) { 1678 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1679 const ARMBaseInstrInfo &TII = 1680 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1681 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1682 unsigned Limit = (1 << 12) - 1; 1683 for (auto &MBB : MF) { 1684 for (auto &MI : MBB) { 1685 if (MI.isDebugInstr()) 1686 continue; 1687 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1688 if (!MI.getOperand(i).isFI()) 1689 continue; 1690 1691 // When using ADDri to get the address of a stack object, 255 is the 1692 // largest offset guaranteed to fit in the immediate offset. 1693 if (MI.getOpcode() == ARM::ADDri) { 1694 Limit = std::min(Limit, (1U << 8) - 1); 1695 break; 1696 } 1697 // t2ADDri will not require an extra register, it can reuse the 1698 // destination. 1699 if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12) 1700 break; 1701 1702 const MCInstrDesc &MCID = MI.getDesc(); 1703 const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF); 1704 if (RegClass && !RegClass->contains(ARM::SP)) 1705 HasNonSPFrameIndex = true; 1706 1707 // Otherwise check the addressing mode. 1708 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) { 1709 case ARMII::AddrMode_i12: 1710 case ARMII::AddrMode2: 1711 // Default 12 bit limit. 1712 break; 1713 case ARMII::AddrMode3: 1714 case ARMII::AddrModeT2_i8neg: 1715 Limit = std::min(Limit, (1U << 8) - 1); 1716 break; 1717 case ARMII::AddrMode5FP16: 1718 Limit = std::min(Limit, ((1U << 8) - 1) * 2); 1719 break; 1720 case ARMII::AddrMode5: 1721 case ARMII::AddrModeT2_i8s4: 1722 case ARMII::AddrModeT2_ldrex: 1723 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 1724 break; 1725 case ARMII::AddrModeT2_i12: 1726 // i12 supports only positive offset so these will be converted to 1727 // i8 opcodes. See llvm::rewriteT2FrameIndex. 1728 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 1729 Limit = std::min(Limit, (1U << 8) - 1); 1730 break; 1731 case ARMII::AddrMode4: 1732 case ARMII::AddrMode6: 1733 // Addressing modes 4 & 6 (load/store) instructions can't encode an 1734 // immediate offset for stack references. 1735 return 0; 1736 case ARMII::AddrModeT2_i7: 1737 Limit = std::min(Limit, ((1U << 7) - 1) * 1); 1738 break; 1739 case ARMII::AddrModeT2_i7s2: 1740 Limit = std::min(Limit, ((1U << 7) - 1) * 2); 1741 break; 1742 case ARMII::AddrModeT2_i7s4: 1743 Limit = std::min(Limit, ((1U << 7) - 1) * 4); 1744 break; 1745 default: 1746 llvm_unreachable("Unhandled addressing mode in stack size limit calculation"); 1747 } 1748 break; // At most one FI per instruction 1749 } 1750 } 1751 } 1752 1753 return Limit; 1754 } 1755 1756 // In functions that realign the stack, it can be an advantage to spill the 1757 // callee-saved vector registers after realigning the stack. The vst1 and vld1 1758 // instructions take alignment hints that can improve performance. 1759 static void 1760 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) { 1761 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0); 1762 if (!SpillAlignedNEONRegs) 1763 return; 1764 1765 // Naked functions don't spill callee-saved registers. 1766 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 1767 return; 1768 1769 // We are planning to use NEON instructions vst1 / vld1. 1770 if (!MF.getSubtarget<ARMSubtarget>().hasNEON()) 1771 return; 1772 1773 // Don't bother if the default stack alignment is sufficiently high. 1774 if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8)) 1775 return; 1776 1777 // Aligned spills require stack realignment. 1778 if (!static_cast<const ARMBaseRegisterInfo *>( 1779 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF)) 1780 return; 1781 1782 // We always spill contiguous d-registers starting from d8. Count how many 1783 // needs spilling. The register allocator will almost always use the 1784 // callee-saved registers in order, but it can happen that there are holes in 1785 // the range. Registers above the hole will be spilled to the standard DPRCS 1786 // area. 1787 unsigned NumSpills = 0; 1788 for (; NumSpills < 8; ++NumSpills) 1789 if (!SavedRegs.test(ARM::D8 + NumSpills)) 1790 break; 1791 1792 // Don't do this for just one d-register. It's not worth it. 1793 if (NumSpills < 2) 1794 return; 1795 1796 // Spill the first NumSpills D-registers after realigning the stack. 1797 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills); 1798 1799 // A scratch register is required for the vst1 / vld1 instructions. 1800 SavedRegs.set(ARM::R4); 1801 } 1802 1803 bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const { 1804 // For CMSE entry functions, we want to save the FPCXT_NS immediately 1805 // upon function entry (resp. restore it immmediately before return) 1806 if (STI.hasV8_1MMainlineOps() && 1807 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) 1808 return false; 1809 1810 // We are disabling shrinkwrapping for now when PAC is enabled, as 1811 // shrinkwrapping can cause clobbering of r12 when the PAC code is 1812 // generated. A follow-up patch will fix this in a more performant manner. 1813 if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress( 1814 true /* SpillsLR */)) 1815 return false; 1816 1817 return true; 1818 } 1819 1820 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF, 1821 BitVector &SavedRegs, 1822 RegScavenger *RS) const { 1823 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 1824 // This tells PEI to spill the FP as if it is any other callee-save register 1825 // to take advantage the eliminateFrameIndex machinery. This also ensures it 1826 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 1827 // to combine multiple loads / stores. 1828 bool CanEliminateFrame = true; 1829 bool CS1Spilled = false; 1830 bool LRSpilled = false; 1831 unsigned NumGPRSpills = 0; 1832 unsigned NumFPRSpills = 0; 1833 SmallVector<unsigned, 4> UnspilledCS1GPRs; 1834 SmallVector<unsigned, 4> UnspilledCS2GPRs; 1835 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 1836 MF.getSubtarget().getRegisterInfo()); 1837 const ARMBaseInstrInfo &TII = 1838 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1839 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1840 MachineFrameInfo &MFI = MF.getFrameInfo(); 1841 MachineRegisterInfo &MRI = MF.getRegInfo(); 1842 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1843 (void)TRI; // Silence unused warning in non-assert builds. 1844 Register FramePtr = RegInfo->getFrameRegister(MF); 1845 1846 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 1847 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 1848 // since it's not always possible to restore sp from fp in a single 1849 // instruction. 1850 // FIXME: It will be better just to find spare register here. 1851 if (AFI->isThumb2Function() && 1852 (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))) 1853 SavedRegs.set(ARM::R4); 1854 1855 // If a stack probe will be emitted, spill R4 and LR, since they are 1856 // clobbered by the stack probe call. 1857 // This estimate should be a safe, conservative estimate. The actual 1858 // stack probe is enabled based on the size of the local objects; 1859 // this estimate also includes the varargs store size. 1860 if (STI.isTargetWindows() && 1861 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) { 1862 SavedRegs.set(ARM::R4); 1863 SavedRegs.set(ARM::LR); 1864 } 1865 1866 if (AFI->isThumb1OnlyFunction()) { 1867 // Spill LR if Thumb1 function uses variable length argument lists. 1868 if (AFI->getArgRegsSaveSize() > 0) 1869 SavedRegs.set(ARM::LR); 1870 1871 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function 1872 // requires stack alignment. We don't know for sure what the stack size 1873 // will be, but for this, an estimate is good enough. If there anything 1874 // changes it, it'll be a spill, which implies we've used all the registers 1875 // and so R4 is already used, so not marking it here will be OK. 1876 // FIXME: It will be better just to find spare register here. 1877 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) || 1878 MFI.estimateStackSize(MF) > 508) 1879 SavedRegs.set(ARM::R4); 1880 } 1881 1882 // See if we can spill vector registers to aligned stack. 1883 checkNumAlignedDPRCS2Regs(MF, SavedRegs); 1884 1885 // Spill the BasePtr if it's used. 1886 if (RegInfo->hasBasePointer(MF)) 1887 SavedRegs.set(RegInfo->getBaseRegister()); 1888 1889 // On v8.1-M.Main CMSE entry functions save/restore FPCXT. 1890 if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction()) 1891 CanEliminateFrame = false; 1892 1893 // Don't spill FP if the frame can be eliminated. This is determined 1894 // by scanning the callee-save registers to see if any is modified. 1895 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 1896 for (unsigned i = 0; CSRegs[i]; ++i) { 1897 unsigned Reg = CSRegs[i]; 1898 bool Spilled = false; 1899 if (SavedRegs.test(Reg)) { 1900 Spilled = true; 1901 CanEliminateFrame = false; 1902 } 1903 1904 if (!ARM::GPRRegClass.contains(Reg)) { 1905 if (Spilled) { 1906 if (ARM::SPRRegClass.contains(Reg)) 1907 NumFPRSpills++; 1908 else if (ARM::DPRRegClass.contains(Reg)) 1909 NumFPRSpills += 2; 1910 else if (ARM::QPRRegClass.contains(Reg)) 1911 NumFPRSpills += 4; 1912 } 1913 continue; 1914 } 1915 1916 if (Spilled) { 1917 NumGPRSpills++; 1918 1919 if (!STI.splitFramePushPop(MF)) { 1920 if (Reg == ARM::LR) 1921 LRSpilled = true; 1922 CS1Spilled = true; 1923 continue; 1924 } 1925 1926 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 1927 switch (Reg) { 1928 case ARM::LR: 1929 LRSpilled = true; 1930 LLVM_FALLTHROUGH; 1931 case ARM::R0: case ARM::R1: 1932 case ARM::R2: case ARM::R3: 1933 case ARM::R4: case ARM::R5: 1934 case ARM::R6: case ARM::R7: 1935 CS1Spilled = true; 1936 break; 1937 default: 1938 break; 1939 } 1940 } else { 1941 if (!STI.splitFramePushPop(MF)) { 1942 UnspilledCS1GPRs.push_back(Reg); 1943 continue; 1944 } 1945 1946 switch (Reg) { 1947 case ARM::R0: case ARM::R1: 1948 case ARM::R2: case ARM::R3: 1949 case ARM::R4: case ARM::R5: 1950 case ARM::R6: case ARM::R7: 1951 case ARM::LR: 1952 UnspilledCS1GPRs.push_back(Reg); 1953 break; 1954 default: 1955 UnspilledCS2GPRs.push_back(Reg); 1956 break; 1957 } 1958 } 1959 } 1960 1961 bool ForceLRSpill = false; 1962 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 1963 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII); 1964 // Force LR to be spilled if the Thumb function size is > 2048. This enables 1965 // use of BL to implement far jump. 1966 if (FnSize >= (1 << 11)) { 1967 CanEliminateFrame = false; 1968 ForceLRSpill = true; 1969 } 1970 } 1971 1972 // If any of the stack slot references may be out of range of an immediate 1973 // offset, make sure a register (or a spill slot) is available for the 1974 // register scavenger. Note that if we're indexing off the frame pointer, the 1975 // effective stack size is 4 bytes larger since the FP points to the stack 1976 // slot of the previous FP. Also, if we have variable sized objects in the 1977 // function, stack slot references will often be negative, and some of 1978 // our instructions are positive-offset only, so conservatively consider 1979 // that case to want a spill slot (or register) as well. Similarly, if 1980 // the function adjusts the stack pointer during execution and the 1981 // adjustments aren't already part of our stack size estimate, our offset 1982 // calculations may be off, so be conservative. 1983 // FIXME: We could add logic to be more precise about negative offsets 1984 // and which instructions will need a scratch register for them. Is it 1985 // worth the effort and added fragility? 1986 unsigned EstimatedStackSize = 1987 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills); 1988 1989 // Determine biggest (positive) SP offset in MachineFrameInfo. 1990 int MaxFixedOffset = 0; 1991 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) { 1992 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I); 1993 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset); 1994 } 1995 1996 bool HasFP = hasFP(MF); 1997 if (HasFP) { 1998 if (AFI->hasStackFrame()) 1999 EstimatedStackSize += 4; 2000 } else { 2001 // If FP is not used, SP will be used to access arguments, so count the 2002 // size of arguments into the estimation. 2003 EstimatedStackSize += MaxFixedOffset; 2004 } 2005 EstimatedStackSize += 16; // For possible paddings. 2006 2007 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit; 2008 bool HasNonSPFrameIndex = false; 2009 if (AFI->isThumb1OnlyFunction()) { 2010 // For Thumb1, don't bother to iterate over the function. The only 2011 // instruction that requires an emergency spill slot is a store to a 2012 // frame index. 2013 // 2014 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned 2015 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has 2016 // a 5-bit unsigned immediate. 2017 // 2018 // We could try to check if the function actually contains a tSTRspi 2019 // that might need the spill slot, but it's not really important. 2020 // Functions with VLAs or extremely large call frames are rare, and 2021 // if a function is allocating more than 1KB of stack, an extra 4-byte 2022 // slot probably isn't relevant. 2023 if (RegInfo->hasBasePointer(MF)) 2024 EstimatedRSStackSizeLimit = (1U << 5) * 4; 2025 else 2026 EstimatedRSStackSizeLimit = (1U << 8) * 4; 2027 EstimatedRSFixedSizeLimit = (1U << 5) * 4; 2028 } else { 2029 EstimatedRSStackSizeLimit = 2030 estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex); 2031 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit; 2032 } 2033 // Final estimate of whether sp or bp-relative accesses might require 2034 // scavenging. 2035 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit; 2036 2037 // If the stack pointer moves and we don't have a base pointer, the 2038 // estimate logic doesn't work. The actual offsets might be larger when 2039 // we're constructing a call frame, or we might need to use negative 2040 // offsets from fp. 2041 bool HasMovingSP = MFI.hasVarSizedObjects() || 2042 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)); 2043 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP; 2044 2045 // If we have a frame pointer, we assume arguments will be accessed 2046 // relative to the frame pointer. Check whether fp-relative accesses to 2047 // arguments require scavenging. 2048 // 2049 // We could do slightly better on Thumb1; in some cases, an sp-relative 2050 // offset would be legal even though an fp-relative offset is not. 2051 int MaxFPOffset = getMaxFPOffset(STI, *AFI); 2052 bool HasLargeArgumentList = 2053 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit; 2054 2055 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP || 2056 HasLargeArgumentList || HasNonSPFrameIndex; 2057 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit 2058 << "; EstimatedStack: " << EstimatedStackSize 2059 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset 2060 << "; BigFrameOffsets: " << BigFrameOffsets << "\n"); 2061 if (BigFrameOffsets || 2062 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 2063 AFI->setHasStackFrame(true); 2064 2065 if (HasFP) { 2066 SavedRegs.set(FramePtr); 2067 // If the frame pointer is required by the ABI, also spill LR so that we 2068 // emit a complete frame record. 2069 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) { 2070 SavedRegs.set(ARM::LR); 2071 LRSpilled = true; 2072 NumGPRSpills++; 2073 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR); 2074 if (LRPos != UnspilledCS1GPRs.end()) 2075 UnspilledCS1GPRs.erase(LRPos); 2076 } 2077 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr); 2078 if (FPPos != UnspilledCS1GPRs.end()) 2079 UnspilledCS1GPRs.erase(FPPos); 2080 NumGPRSpills++; 2081 if (FramePtr == ARM::R7) 2082 CS1Spilled = true; 2083 } 2084 2085 // This is true when we inserted a spill for a callee-save GPR which is 2086 // not otherwise used by the function. This guaranteees it is possible 2087 // to scavenge a register to hold the address of a stack slot. On Thumb1, 2088 // the register must be a valid operand to tSTRi, i.e. r4-r7. For other 2089 // subtargets, this is any GPR, i.e. r4-r11 or lr. 2090 // 2091 // If we don't insert a spill, we instead allocate an emergency spill 2092 // slot, which can be used by scavenging to spill an arbitrary register. 2093 // 2094 // We currently don't try to figure out whether any specific instruction 2095 // requires scavening an additional register. 2096 bool ExtraCSSpill = false; 2097 2098 if (AFI->isThumb1OnlyFunction()) { 2099 // For Thumb1-only targets, we need some low registers when we save and 2100 // restore the high registers (which aren't allocatable, but could be 2101 // used by inline assembly) because the push/pop instructions can not 2102 // access high registers. If necessary, we might need to push more low 2103 // registers to ensure that there is at least one free that can be used 2104 // for the saving & restoring, and preferably we should ensure that as 2105 // many as are needed are available so that fewer push/pop instructions 2106 // are required. 2107 2108 // Low registers which are not currently pushed, but could be (r4-r7). 2109 SmallVector<unsigned, 4> AvailableRegs; 2110 2111 // Unused argument registers (r0-r3) can be clobbered in the prologue for 2112 // free. 2113 int EntryRegDeficit = 0; 2114 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) { 2115 if (!MF.getRegInfo().isLiveIn(Reg)) { 2116 --EntryRegDeficit; 2117 LLVM_DEBUG(dbgs() 2118 << printReg(Reg, TRI) 2119 << " is unused argument register, EntryRegDeficit = " 2120 << EntryRegDeficit << "\n"); 2121 } 2122 } 2123 2124 // Unused return registers can be clobbered in the epilogue for free. 2125 int ExitRegDeficit = AFI->getReturnRegsCount() - 4; 2126 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount() 2127 << " return regs used, ExitRegDeficit = " 2128 << ExitRegDeficit << "\n"); 2129 2130 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit); 2131 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n"); 2132 2133 // r4-r6 can be used in the prologue if they are pushed by the first push 2134 // instruction. 2135 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) { 2136 if (SavedRegs.test(Reg)) { 2137 --RegDeficit; 2138 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) 2139 << " is saved low register, RegDeficit = " 2140 << RegDeficit << "\n"); 2141 } else { 2142 AvailableRegs.push_back(Reg); 2143 LLVM_DEBUG( 2144 dbgs() 2145 << printReg(Reg, TRI) 2146 << " is non-saved low register, adding to AvailableRegs\n"); 2147 } 2148 } 2149 2150 // r7 can be used if it is not being used as the frame pointer. 2151 if (!HasFP) { 2152 if (SavedRegs.test(ARM::R7)) { 2153 --RegDeficit; 2154 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = " 2155 << RegDeficit << "\n"); 2156 } else { 2157 AvailableRegs.push_back(ARM::R7); 2158 LLVM_DEBUG( 2159 dbgs() 2160 << "%r7 is non-saved low register, adding to AvailableRegs\n"); 2161 } 2162 } 2163 2164 // Each of r8-r11 needs to be copied to a low register, then pushed. 2165 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) { 2166 if (SavedRegs.test(Reg)) { 2167 ++RegDeficit; 2168 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) 2169 << " is saved high register, RegDeficit = " 2170 << RegDeficit << "\n"); 2171 } 2172 } 2173 2174 // LR can only be used by PUSH, not POP, and can't be used at all if the 2175 // llvm.returnaddress intrinsic is used. This is only worth doing if we 2176 // are more limited at function entry than exit. 2177 if ((EntryRegDeficit > ExitRegDeficit) && 2178 !(MF.getRegInfo().isLiveIn(ARM::LR) && 2179 MF.getFrameInfo().isReturnAddressTaken())) { 2180 if (SavedRegs.test(ARM::LR)) { 2181 --RegDeficit; 2182 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = " 2183 << RegDeficit << "\n"); 2184 } else { 2185 AvailableRegs.push_back(ARM::LR); 2186 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n"); 2187 } 2188 } 2189 2190 // If there are more high registers that need pushing than low registers 2191 // available, push some more low registers so that we can use fewer push 2192 // instructions. This might not reduce RegDeficit all the way to zero, 2193 // because we can only guarantee that r4-r6 are available, but r8-r11 may 2194 // need saving. 2195 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n"); 2196 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) { 2197 unsigned Reg = AvailableRegs.pop_back_val(); 2198 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2199 << " to make up reg deficit\n"); 2200 SavedRegs.set(Reg); 2201 NumGPRSpills++; 2202 CS1Spilled = true; 2203 assert(!MRI.isReserved(Reg) && "Should not be reserved"); 2204 if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg)) 2205 ExtraCSSpill = true; 2206 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg)); 2207 if (Reg == ARM::LR) 2208 LRSpilled = true; 2209 } 2210 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit 2211 << "\n"); 2212 } 2213 2214 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to 2215 // restore LR in that case. 2216 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall(); 2217 2218 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 2219 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 2220 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) { 2221 SavedRegs.set(ARM::LR); 2222 NumGPRSpills++; 2223 SmallVectorImpl<unsigned>::iterator LRPos; 2224 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR); 2225 if (LRPos != UnspilledCS1GPRs.end()) 2226 UnspilledCS1GPRs.erase(LRPos); 2227 2228 ForceLRSpill = false; 2229 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) && 2230 !AFI->isThumb1OnlyFunction()) 2231 ExtraCSSpill = true; 2232 } 2233 2234 // If stack and double are 8-byte aligned and we are spilling an odd number 2235 // of GPRs, spill one extra callee save GPR so we won't have to pad between 2236 // the integer and double callee save areas. 2237 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n"); 2238 const Align TargetAlign = getStackAlign(); 2239 if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) { 2240 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 2241 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) { 2242 unsigned Reg = UnspilledCS1GPRs[i]; 2243 // Don't spill high register if the function is thumb. In the case of 2244 // Windows on ARM, accept R11 (frame pointer) 2245 if (!AFI->isThumbFunction() || 2246 (STI.isTargetWindows() && Reg == ARM::R11) || 2247 isARMLowRegister(Reg) || 2248 (Reg == ARM::LR && !ExpensiveLRRestore)) { 2249 SavedRegs.set(Reg); 2250 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2251 << " to make up alignment\n"); 2252 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) && 2253 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction())) 2254 ExtraCSSpill = true; 2255 break; 2256 } 2257 } 2258 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 2259 unsigned Reg = UnspilledCS2GPRs.front(); 2260 SavedRegs.set(Reg); 2261 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2262 << " to make up alignment\n"); 2263 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg)) 2264 ExtraCSSpill = true; 2265 } 2266 } 2267 2268 // Estimate if we might need to scavenge a register at some point in order 2269 // to materialize a stack offset. If so, either spill one additional 2270 // callee-saved register or reserve a special spill slot to facilitate 2271 // register scavenging. Thumb1 needs a spill slot for stack pointer 2272 // adjustments also, even when the frame itself is small. 2273 if (BigFrameOffsets && !ExtraCSSpill) { 2274 // If any non-reserved CS register isn't spilled, just spill one or two 2275 // extra. That should take care of it! 2276 unsigned NumExtras = TargetAlign.value() / 4; 2277 SmallVector<unsigned, 2> Extras; 2278 while (NumExtras && !UnspilledCS1GPRs.empty()) { 2279 unsigned Reg = UnspilledCS1GPRs.pop_back_val(); 2280 if (!MRI.isReserved(Reg) && 2281 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) { 2282 Extras.push_back(Reg); 2283 NumExtras--; 2284 } 2285 } 2286 // For non-Thumb1 functions, also check for hi-reg CS registers 2287 if (!AFI->isThumb1OnlyFunction()) { 2288 while (NumExtras && !UnspilledCS2GPRs.empty()) { 2289 unsigned Reg = UnspilledCS2GPRs.pop_back_val(); 2290 if (!MRI.isReserved(Reg)) { 2291 Extras.push_back(Reg); 2292 NumExtras--; 2293 } 2294 } 2295 } 2296 if (NumExtras == 0) { 2297 for (unsigned Reg : Extras) { 2298 SavedRegs.set(Reg); 2299 if (!MRI.isPhysRegUsed(Reg)) 2300 ExtraCSSpill = true; 2301 } 2302 } 2303 if (!ExtraCSSpill && RS) { 2304 // Reserve a slot closest to SP or frame pointer. 2305 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n"); 2306 const TargetRegisterClass &RC = ARM::GPRRegClass; 2307 unsigned Size = TRI->getSpillSize(RC); 2308 Align Alignment = TRI->getSpillAlign(RC); 2309 RS->addScavengingFrameIndex( 2310 MFI.CreateStackObject(Size, Alignment, false)); 2311 } 2312 } 2313 } 2314 2315 if (ForceLRSpill) 2316 SavedRegs.set(ARM::LR); 2317 AFI->setLRIsSpilled(SavedRegs.test(ARM::LR)); 2318 } 2319 2320 void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF, 2321 BitVector &SavedRegs) const { 2322 TargetFrameLowering::getCalleeSaves(MF, SavedRegs); 2323 2324 // If we have the "returned" parameter attribute which guarantees that we 2325 // return the value which was passed in r0 unmodified (e.g. C++ 'structors), 2326 // record that fact for IPRA. 2327 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2328 if (AFI->getPreservesR0()) 2329 SavedRegs.set(ARM::R0); 2330 } 2331 2332 bool ARMFrameLowering::assignCalleeSavedSpillSlots( 2333 MachineFunction &MF, const TargetRegisterInfo *TRI, 2334 std::vector<CalleeSavedInfo> &CSI) const { 2335 // For CMSE entry functions, handle floating-point context as if it was a 2336 // callee-saved register. 2337 if (STI.hasV8_1MMainlineOps() && 2338 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) { 2339 CSI.emplace_back(ARM::FPCXTNS); 2340 CSI.back().setRestored(false); 2341 } 2342 2343 // For functions, which sign their return address, upon function entry, the 2344 // return address PAC is computed in R12. Treat R12 as a callee-saved register 2345 // in this case. 2346 const auto &AFI = *MF.getInfo<ARMFunctionInfo>(); 2347 if (AFI.shouldSignReturnAddress()) { 2348 // The order of register must match the order we push them, because the 2349 // PEI assigns frame indices in that order. When compiling for return 2350 // address sign and authenication, we use split push, therefore the orders 2351 // we want are: 2352 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8 2353 CSI.insert(find_if(CSI, 2354 [=](const auto &CS) { 2355 Register Reg = CS.getReg(); 2356 return Reg == ARM::R10 || Reg == ARM::R11 || 2357 Reg == ARM::R8 || Reg == ARM::R9 || 2358 ARM::DPRRegClass.contains(Reg); 2359 }), 2360 CalleeSavedInfo(ARM::R12)); 2361 } 2362 2363 return false; 2364 } 2365 2366 const TargetFrameLowering::SpillSlot * 2367 ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const { 2368 static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}}; 2369 NumEntries = array_lengthof(FixedSpillOffsets); 2370 return FixedSpillOffsets; 2371 } 2372 2373 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr( 2374 MachineFunction &MF, MachineBasicBlock &MBB, 2375 MachineBasicBlock::iterator I) const { 2376 const ARMBaseInstrInfo &TII = 2377 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 2378 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2379 bool isARM = !AFI->isThumbFunction(); 2380 DebugLoc dl = I->getDebugLoc(); 2381 unsigned Opc = I->getOpcode(); 2382 bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode(); 2383 unsigned CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0; 2384 2385 assert(!AFI->isThumb1OnlyFunction() && 2386 "This eliminateCallFramePseudoInstr does not support Thumb1!"); 2387 2388 int PIdx = I->findFirstPredOperandIdx(); 2389 ARMCC::CondCodes Pred = (PIdx == -1) 2390 ? ARMCC::AL 2391 : (ARMCC::CondCodes)I->getOperand(PIdx).getImm(); 2392 unsigned PredReg = TII.getFramePred(*I); 2393 2394 if (!hasReservedCallFrame(MF)) { 2395 // Bail early if the callee is expected to do the adjustment. 2396 if (IsDestroy && CalleePopAmount != -1U) 2397 return MBB.erase(I); 2398 2399 // If we have alloca, convert as follows: 2400 // ADJCALLSTACKDOWN -> sub, sp, sp, amount 2401 // ADJCALLSTACKUP -> add, sp, sp, amount 2402 unsigned Amount = TII.getFrameSize(*I); 2403 if (Amount != 0) { 2404 // We need to keep the stack aligned properly. To do this, we round the 2405 // amount of space needed for the outgoing arguments up to the next 2406 // alignment boundary. 2407 Amount = alignSPAdjust(Amount); 2408 2409 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) { 2410 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags, 2411 Pred, PredReg); 2412 } else { 2413 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP); 2414 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags, 2415 Pred, PredReg); 2416 } 2417 } 2418 } else if (CalleePopAmount != -1U) { 2419 // If the calling convention demands that the callee pops arguments from the 2420 // stack, we want to add it back if we have a reserved call frame. 2421 emitSPUpdate(isARM, MBB, I, dl, TII, -CalleePopAmount, 2422 MachineInstr::NoFlags, Pred, PredReg); 2423 } 2424 return MBB.erase(I); 2425 } 2426 2427 /// Get the minimum constant for ARM that is greater than or equal to the 2428 /// argument. In ARM, constants can have any value that can be produced by 2429 /// rotating an 8-bit value to the right by an even number of bits within a 2430 /// 32-bit word. 2431 static uint32_t alignToARMConstant(uint32_t Value) { 2432 unsigned Shifted = 0; 2433 2434 if (Value == 0) 2435 return 0; 2436 2437 while (!(Value & 0xC0000000)) { 2438 Value = Value << 2; 2439 Shifted += 2; 2440 } 2441 2442 bool Carry = (Value & 0x00FFFFFF); 2443 Value = ((Value & 0xFF000000) >> 24) + Carry; 2444 2445 if (Value & 0x0000100) 2446 Value = Value & 0x000001FC; 2447 2448 if (Shifted > 24) 2449 Value = Value >> (Shifted - 24); 2450 else 2451 Value = Value << (24 - Shifted); 2452 2453 return Value; 2454 } 2455 2456 // The stack limit in the TCB is set to this many bytes above the actual 2457 // stack limit. 2458 static const uint64_t kSplitStackAvailable = 256; 2459 2460 // Adjust the function prologue to enable split stacks. This currently only 2461 // supports android and linux. 2462 // 2463 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but 2464 // must be well defined in order to allow for consistent implementations of the 2465 // __morestack helper function. The ABI is also not a normal ABI in that it 2466 // doesn't follow the normal calling conventions because this allows the 2467 // prologue of each function to be optimized further. 2468 // 2469 // Currently, the ABI looks like (when calling __morestack) 2470 // 2471 // * r4 holds the minimum stack size requested for this function call 2472 // * r5 holds the stack size of the arguments to the function 2473 // * the beginning of the function is 3 instructions after the call to 2474 // __morestack 2475 // 2476 // Implementations of __morestack should use r4 to allocate a new stack, r5 to 2477 // place the arguments on to the new stack, and the 3-instruction knowledge to 2478 // jump directly to the body of the function when working on the new stack. 2479 // 2480 // An old (and possibly no longer compatible) implementation of __morestack for 2481 // ARM can be found at [1]. 2482 // 2483 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S 2484 void ARMFrameLowering::adjustForSegmentedStacks( 2485 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 2486 unsigned Opcode; 2487 unsigned CFIIndex; 2488 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>(); 2489 bool Thumb = ST->isThumb(); 2490 bool Thumb2 = ST->isThumb2(); 2491 2492 // Sadly, this currently doesn't support varargs, platforms other than 2493 // android/linux. Note that thumb1/thumb2 are support for android/linux. 2494 if (MF.getFunction().isVarArg()) 2495 report_fatal_error("Segmented stacks do not support vararg functions."); 2496 if (!ST->isTargetAndroid() && !ST->isTargetLinux()) 2497 report_fatal_error("Segmented stacks not supported on this platform."); 2498 2499 MachineFrameInfo &MFI = MF.getFrameInfo(); 2500 MachineModuleInfo &MMI = MF.getMMI(); 2501 MCContext &Context = MMI.getContext(); 2502 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 2503 const ARMBaseInstrInfo &TII = 2504 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 2505 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>(); 2506 DebugLoc DL; 2507 2508 if (!MFI.needsSplitStackProlog()) 2509 return; 2510 2511 uint64_t StackSize = MFI.getStackSize(); 2512 2513 // Use R4 and R5 as scratch registers. 2514 // We save R4 and R5 before use and restore them before leaving the function. 2515 unsigned ScratchReg0 = ARM::R4; 2516 unsigned ScratchReg1 = ARM::R5; 2517 uint64_t AlignedStackSize; 2518 2519 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock(); 2520 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock(); 2521 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock(); 2522 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock(); 2523 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock(); 2524 2525 // Grab everything that reaches PrologueMBB to update there liveness as well. 2526 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion; 2527 SmallVector<MachineBasicBlock *, 2> WalkList; 2528 WalkList.push_back(&PrologueMBB); 2529 2530 do { 2531 MachineBasicBlock *CurMBB = WalkList.pop_back_val(); 2532 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) { 2533 if (BeforePrologueRegion.insert(PredBB).second) 2534 WalkList.push_back(PredBB); 2535 } 2536 } while (!WalkList.empty()); 2537 2538 // The order in that list is important. 2539 // The blocks will all be inserted before PrologueMBB using that order. 2540 // Therefore the block that should appear first in the CFG should appear 2541 // first in the list. 2542 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB, 2543 PostStackMBB}; 2544 2545 for (MachineBasicBlock *B : AddedBlocks) 2546 BeforePrologueRegion.insert(B); 2547 2548 for (const auto &LI : PrologueMBB.liveins()) { 2549 for (MachineBasicBlock *PredBB : BeforePrologueRegion) 2550 PredBB->addLiveIn(LI); 2551 } 2552 2553 // Remove the newly added blocks from the list, since we know 2554 // we do not have to do the following updates for them. 2555 for (MachineBasicBlock *B : AddedBlocks) { 2556 BeforePrologueRegion.erase(B); 2557 MF.insert(PrologueMBB.getIterator(), B); 2558 } 2559 2560 for (MachineBasicBlock *MBB : BeforePrologueRegion) { 2561 // Make sure the LiveIns are still sorted and unique. 2562 MBB->sortUniqueLiveIns(); 2563 // Replace the edges to PrologueMBB by edges to the sequences 2564 // we are about to add, but only update for immediate predecessors. 2565 if (MBB->isSuccessor(&PrologueMBB)) 2566 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]); 2567 } 2568 2569 // The required stack size that is aligned to ARM constant criterion. 2570 AlignedStackSize = alignToARMConstant(StackSize); 2571 2572 // When the frame size is less than 256 we just compare the stack 2573 // boundary directly to the value of the stack pointer, per gcc. 2574 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable; 2575 2576 // We will use two of the callee save registers as scratch registers so we 2577 // need to save those registers onto the stack. 2578 // We will use SR0 to hold stack limit and SR1 to hold the stack size 2579 // requested and arguments for __morestack(). 2580 // SR0: Scratch Register #0 2581 // SR1: Scratch Register #1 2582 // push {SR0, SR1} 2583 if (Thumb) { 2584 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)) 2585 .add(predOps(ARMCC::AL)) 2586 .addReg(ScratchReg0) 2587 .addReg(ScratchReg1); 2588 } else { 2589 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD)) 2590 .addReg(ARM::SP, RegState::Define) 2591 .addReg(ARM::SP) 2592 .add(predOps(ARMCC::AL)) 2593 .addReg(ScratchReg0) 2594 .addReg(ScratchReg1); 2595 } 2596 2597 // Emit the relevant DWARF information about the change in stack pointer as 2598 // well as where to find both r4 and r5 (the callee-save registers) 2599 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8)); 2600 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2601 .addCFIIndex(CFIIndex); 2602 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 2603 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4)); 2604 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2605 .addCFIIndex(CFIIndex); 2606 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 2607 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8)); 2608 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2609 .addCFIIndex(CFIIndex); 2610 2611 // mov SR1, sp 2612 if (Thumb) { 2613 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1) 2614 .addReg(ARM::SP) 2615 .add(predOps(ARMCC::AL)); 2616 } else if (CompareStackPointer) { 2617 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1) 2618 .addReg(ARM::SP) 2619 .add(predOps(ARMCC::AL)) 2620 .add(condCodeOp()); 2621 } 2622 2623 // sub SR1, sp, #StackSize 2624 if (!CompareStackPointer && Thumb) { 2625 if (AlignedStackSize < 256) { 2626 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1) 2627 .add(condCodeOp()) 2628 .addReg(ScratchReg1) 2629 .addImm(AlignedStackSize) 2630 .add(predOps(ARMCC::AL)); 2631 } else { 2632 if (Thumb2) { 2633 BuildMI(McrMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg0) 2634 .addImm(AlignedStackSize); 2635 } else { 2636 auto MBBI = McrMBB->end(); 2637 auto RegInfo = STI.getRegisterInfo(); 2638 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0, 2639 AlignedStackSize); 2640 } 2641 BuildMI(McrMBB, DL, TII.get(ARM::tSUBrr), ScratchReg1) 2642 .add(condCodeOp()) 2643 .addReg(ScratchReg1) 2644 .addReg(ScratchReg0) 2645 .add(predOps(ARMCC::AL)); 2646 } 2647 } else if (!CompareStackPointer) { 2648 if (AlignedStackSize < 256) { 2649 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1) 2650 .addReg(ARM::SP) 2651 .addImm(AlignedStackSize) 2652 .add(predOps(ARMCC::AL)) 2653 .add(condCodeOp()); 2654 } else { 2655 auto MBBI = McrMBB->end(); 2656 auto RegInfo = STI.getRegisterInfo(); 2657 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0, 2658 AlignedStackSize); 2659 BuildMI(McrMBB, DL, TII.get(ARM::SUBrr), ScratchReg1) 2660 .addReg(ARM::SP) 2661 .addReg(ScratchReg0) 2662 .add(predOps(ARMCC::AL)) 2663 .add(condCodeOp()); 2664 } 2665 } 2666 2667 if (Thumb && ST->isThumb1Only()) { 2668 unsigned PCLabelId = ARMFI->createPICLabelUId(); 2669 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create( 2670 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0); 2671 MachineConstantPool *MCP = MF.getConstantPool(); 2672 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4)); 2673 2674 // ldr SR0, [pc, offset(STACK_LIMIT)] 2675 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0) 2676 .addConstantPoolIndex(CPI) 2677 .add(predOps(ARMCC::AL)); 2678 2679 // ldr SR0, [SR0] 2680 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0) 2681 .addReg(ScratchReg0) 2682 .addImm(0) 2683 .add(predOps(ARMCC::AL)); 2684 } else { 2685 // Get TLS base address from the coprocessor 2686 // mrc p15, #0, SR0, c13, c0, #3 2687 BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC), 2688 ScratchReg0) 2689 .addImm(15) 2690 .addImm(0) 2691 .addImm(13) 2692 .addImm(0) 2693 .addImm(3) 2694 .add(predOps(ARMCC::AL)); 2695 2696 // Use the last tls slot on android and a private field of the TCP on linux. 2697 assert(ST->isTargetAndroid() || ST->isTargetLinux()); 2698 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1; 2699 2700 // Get the stack limit from the right offset 2701 // ldr SR0, [sr0, #4 * TlsOffset] 2702 BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12), 2703 ScratchReg0) 2704 .addReg(ScratchReg0) 2705 .addImm(4 * TlsOffset) 2706 .add(predOps(ARMCC::AL)); 2707 } 2708 2709 // Compare stack limit with stack size requested. 2710 // cmp SR0, SR1 2711 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr; 2712 BuildMI(GetMBB, DL, TII.get(Opcode)) 2713 .addReg(ScratchReg0) 2714 .addReg(ScratchReg1) 2715 .add(predOps(ARMCC::AL)); 2716 2717 // This jump is taken if StackLimit < SP - stack required. 2718 Opcode = Thumb ? ARM::tBcc : ARM::Bcc; 2719 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB) 2720 .addImm(ARMCC::LO) 2721 .addReg(ARM::CPSR); 2722 2723 2724 // Calling __morestack(StackSize, Size of stack arguments). 2725 // __morestack knows that the stack size requested is in SR0(r4) 2726 // and amount size of stack arguments is in SR1(r5). 2727 2728 // Pass first argument for the __morestack by Scratch Register #0. 2729 // The amount size of stack required 2730 if (Thumb) { 2731 if (AlignedStackSize < 256) { 2732 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0) 2733 .add(condCodeOp()) 2734 .addImm(AlignedStackSize) 2735 .add(predOps(ARMCC::AL)); 2736 } else { 2737 if (Thumb2) { 2738 BuildMI(AllocMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg0) 2739 .addImm(AlignedStackSize); 2740 } else { 2741 auto MBBI = AllocMBB->end(); 2742 auto RegInfo = STI.getRegisterInfo(); 2743 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0, 2744 AlignedStackSize); 2745 } 2746 } 2747 } else { 2748 if (AlignedStackSize < 256) { 2749 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0) 2750 .addImm(AlignedStackSize) 2751 .add(predOps(ARMCC::AL)) 2752 .add(condCodeOp()); 2753 } else { 2754 auto MBBI = AllocMBB->end(); 2755 auto RegInfo = STI.getRegisterInfo(); 2756 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0, 2757 AlignedStackSize); 2758 } 2759 } 2760 2761 // Pass second argument for the __morestack by Scratch Register #1. 2762 // The amount size of stack consumed to save function arguments. 2763 if (Thumb) { 2764 if (ARMFI->getArgumentStackSize() < 256) { 2765 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1) 2766 .add(condCodeOp()) 2767 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())) 2768 .add(predOps(ARMCC::AL)); 2769 } else { 2770 if (Thumb2) { 2771 BuildMI(AllocMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg1) 2772 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())); 2773 } else { 2774 auto MBBI = AllocMBB->end(); 2775 auto RegInfo = STI.getRegisterInfo(); 2776 RegInfo->emitLoadConstPool( 2777 *AllocMBB, MBBI, DL, ScratchReg1, 0, 2778 alignToARMConstant(ARMFI->getArgumentStackSize())); 2779 } 2780 } 2781 } else { 2782 if (alignToARMConstant(ARMFI->getArgumentStackSize()) < 256) { 2783 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1) 2784 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())) 2785 .add(predOps(ARMCC::AL)) 2786 .add(condCodeOp()); 2787 } else { 2788 auto MBBI = AllocMBB->end(); 2789 auto RegInfo = STI.getRegisterInfo(); 2790 RegInfo->emitLoadConstPool( 2791 *AllocMBB, MBBI, DL, ScratchReg1, 0, 2792 alignToARMConstant(ARMFI->getArgumentStackSize())); 2793 } 2794 } 2795 2796 // push {lr} - Save return address of this function. 2797 if (Thumb) { 2798 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)) 2799 .add(predOps(ARMCC::AL)) 2800 .addReg(ARM::LR); 2801 } else { 2802 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD)) 2803 .addReg(ARM::SP, RegState::Define) 2804 .addReg(ARM::SP) 2805 .add(predOps(ARMCC::AL)) 2806 .addReg(ARM::LR); 2807 } 2808 2809 // Emit the DWARF info about the change in stack as well as where to find the 2810 // previous link register 2811 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12)); 2812 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2813 .addCFIIndex(CFIIndex); 2814 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 2815 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12)); 2816 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2817 .addCFIIndex(CFIIndex); 2818 2819 // Call __morestack(). 2820 if (Thumb) { 2821 BuildMI(AllocMBB, DL, TII.get(ARM::tBL)) 2822 .add(predOps(ARMCC::AL)) 2823 .addExternalSymbol("__morestack"); 2824 } else { 2825 BuildMI(AllocMBB, DL, TII.get(ARM::BL)) 2826 .addExternalSymbol("__morestack"); 2827 } 2828 2829 // pop {lr} - Restore return address of this original function. 2830 if (Thumb) { 2831 if (ST->isThumb1Only()) { 2832 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)) 2833 .add(predOps(ARMCC::AL)) 2834 .addReg(ScratchReg0); 2835 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR) 2836 .addReg(ScratchReg0) 2837 .add(predOps(ARMCC::AL)); 2838 } else { 2839 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST)) 2840 .addReg(ARM::LR, RegState::Define) 2841 .addReg(ARM::SP, RegState::Define) 2842 .addReg(ARM::SP) 2843 .addImm(4) 2844 .add(predOps(ARMCC::AL)); 2845 } 2846 } else { 2847 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 2848 .addReg(ARM::SP, RegState::Define) 2849 .addReg(ARM::SP) 2850 .add(predOps(ARMCC::AL)) 2851 .addReg(ARM::LR); 2852 } 2853 2854 // Restore SR0 and SR1 in case of __morestack() was called. 2855 // __morestack() will skip PostStackMBB block so we need to restore 2856 // scratch registers from here. 2857 // pop {SR0, SR1} 2858 if (Thumb) { 2859 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)) 2860 .add(predOps(ARMCC::AL)) 2861 .addReg(ScratchReg0) 2862 .addReg(ScratchReg1); 2863 } else { 2864 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 2865 .addReg(ARM::SP, RegState::Define) 2866 .addReg(ARM::SP) 2867 .add(predOps(ARMCC::AL)) 2868 .addReg(ScratchReg0) 2869 .addReg(ScratchReg1); 2870 } 2871 2872 // Update the CFA offset now that we've popped 2873 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0)); 2874 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2875 .addCFIIndex(CFIIndex); 2876 2877 // Return from this function. 2878 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL)); 2879 2880 // Restore SR0 and SR1 in case of __morestack() was not called. 2881 // pop {SR0, SR1} 2882 if (Thumb) { 2883 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)) 2884 .add(predOps(ARMCC::AL)) 2885 .addReg(ScratchReg0) 2886 .addReg(ScratchReg1); 2887 } else { 2888 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD)) 2889 .addReg(ARM::SP, RegState::Define) 2890 .addReg(ARM::SP) 2891 .add(predOps(ARMCC::AL)) 2892 .addReg(ScratchReg0) 2893 .addReg(ScratchReg1); 2894 } 2895 2896 // Update the CFA offset now that we've popped 2897 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0)); 2898 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2899 .addCFIIndex(CFIIndex); 2900 2901 // Tell debuggers that r4 and r5 are now the same as they were in the 2902 // previous function, that they're the "Same Value". 2903 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue( 2904 nullptr, MRI->getDwarfRegNum(ScratchReg0, true))); 2905 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2906 .addCFIIndex(CFIIndex); 2907 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue( 2908 nullptr, MRI->getDwarfRegNum(ScratchReg1, true))); 2909 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 2910 .addCFIIndex(CFIIndex); 2911 2912 // Organizing MBB lists 2913 PostStackMBB->addSuccessor(&PrologueMBB); 2914 2915 AllocMBB->addSuccessor(PostStackMBB); 2916 2917 GetMBB->addSuccessor(PostStackMBB); 2918 GetMBB->addSuccessor(AllocMBB); 2919 2920 McrMBB->addSuccessor(GetMBB); 2921 2922 PrevStackMBB->addSuccessor(McrMBB); 2923 2924 #ifdef EXPENSIVE_CHECKS 2925 MF.verify(); 2926 #endif 2927 } 2928