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