1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====// 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 AArch64 implementation of TargetFrameLowering class. 10 // 11 // On AArch64, stack frames are structured as follows: 12 // 13 // The stack grows downward. 14 // 15 // All of the individual frame areas on the frame below are optional, i.e. it's 16 // possible to create a function so that the particular area isn't present 17 // in the frame. 18 // 19 // At function entry, the "frame" looks as follows: 20 // 21 // | | Higher address 22 // |-----------------------------------| 23 // | | 24 // | arguments passed on the stack | 25 // | | 26 // |-----------------------------------| <- sp 27 // | | Lower address 28 // 29 // 30 // After the prologue has run, the frame has the following general structure. 31 // Note that this doesn't depict the case where a red-zone is used. Also, 32 // technically the last frame area (VLAs) doesn't get created until in the 33 // main function body, after the prologue is run. However, it's depicted here 34 // for completeness. 35 // 36 // | | Higher address 37 // |-----------------------------------| 38 // | | 39 // | arguments passed on the stack | 40 // | | 41 // |-----------------------------------| 42 // | | 43 // | (Win64 only) varargs from reg | 44 // | | 45 // |-----------------------------------| 46 // | | 47 // | callee-saved gpr registers | <--. 48 // | | | On Darwin platforms these 49 // |- - - - - - - - - - - - - - - - - -| | callee saves are swapped, 50 // | prev_lr | | (frame record first) 51 // | prev_fp | <--' 52 // | async context if needed | 53 // | (a.k.a. "frame record") | 54 // |-----------------------------------| <- fp(=x29) 55 // | <hazard padding> | 56 // |-----------------------------------| 57 // | | 58 // | callee-saved fp/simd/SVE regs | 59 // | | 60 // |-----------------------------------| 61 // | | 62 // | SVE stack objects | 63 // | | 64 // |-----------------------------------| 65 // |.empty.space.to.make.part.below....| 66 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at 67 // |.the.standard.16-byte.alignment....| compile time; if present) 68 // |-----------------------------------| 69 // | local variables of fixed size | 70 // | including spill slots | 71 // | <FPR> | 72 // | <hazard padding> | 73 // | <GPR> | 74 // |-----------------------------------| <- bp(not defined by ABI, 75 // |.variable-sized.local.variables....| LLVM chooses X19) 76 // |.(VLAs)............................| (size of this area is unknown at 77 // |...................................| compile time) 78 // |-----------------------------------| <- sp 79 // | | Lower address 80 // 81 // 82 // To access the data in a frame, at-compile time, a constant offset must be 83 // computable from one of the pointers (fp, bp, sp) to access it. The size 84 // of the areas with a dotted background cannot be computed at compile-time 85 // if they are present, making it required to have all three of fp, bp and 86 // sp to be set up to be able to access all contents in the frame areas, 87 // assuming all of the frame areas are non-empty. 88 // 89 // For most functions, some of the frame areas are empty. For those functions, 90 // it may not be necessary to set up fp or bp: 91 // * A base pointer is definitely needed when there are both VLAs and local 92 // variables with more-than-default alignment requirements. 93 // * A frame pointer is definitely needed when there are local variables with 94 // more-than-default alignment requirements. 95 // 96 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the 97 // callee-saved area, since the unwind encoding does not allow for encoding 98 // this dynamically and existing tools depend on this layout. For other 99 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved 100 // area to allow SVE stack objects (allocated directly below the callee-saves, 101 // if available) to be accessed directly from the framepointer. 102 // The SVE spill/fill instructions have VL-scaled addressing modes such 103 // as: 104 // ldr z8, [fp, #-7 mul vl] 105 // For SVE the size of the vector length (VL) is not known at compile-time, so 106 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this 107 // layout, we don't need to add an unscaled offset to the framepointer before 108 // accessing the SVE object in the frame. 109 // 110 // In some cases when a base pointer is not strictly needed, it is generated 111 // anyway when offsets from the frame pointer to access local variables become 112 // so large that the offset can't be encoded in the immediate fields of loads 113 // or stores. 114 // 115 // Outgoing function arguments must be at the bottom of the stack frame when 116 // calling another function. If we do not have variable-sized stack objects, we 117 // can allocate a "reserved call frame" area at the bottom of the local 118 // variable area, large enough for all outgoing calls. If we do have VLAs, then 119 // the stack pointer must be decremented and incremented around each call to 120 // make space for the arguments below the VLAs. 121 // 122 // FIXME: also explain the redzone concept. 123 // 124 // About stack hazards: Under some SME contexts, a coprocessor with its own 125 // separate cache can used for FP operations. This can create hazards if the CPU 126 // and the SME unit try to access the same area of memory, including if the 127 // access is to an area of the stack. To try to alleviate this we attempt to 128 // introduce extra padding into the stack frame between FP and GPR accesses, 129 // controlled by the StackHazardSize option. Without changing the layout of the 130 // stack frame in the diagram above, a stack object of size StackHazardSize is 131 // added between GPR and FPR CSRs. Another is added to the stack objects 132 // section, and stack objects are sorted so that FPR > Hazard padding slot > 133 // GPRs (where possible). Unfortunately some things are not handled well (VLA 134 // area, arguments on the stack, object with both GPR and FPR accesses), but if 135 // those are controlled by the user then the entire stack frame becomes GPR at 136 // the start/end with FPR in the middle, surrounded by Hazard padding. 137 // 138 // An example of the prologue: 139 // 140 // .globl __foo 141 // .align 2 142 // __foo: 143 // Ltmp0: 144 // .cfi_startproc 145 // .cfi_personality 155, ___gxx_personality_v0 146 // Leh_func_begin: 147 // .cfi_lsda 16, Lexception33 148 // 149 // stp xa,bx, [sp, -#offset]! 150 // ... 151 // stp x28, x27, [sp, #offset-32] 152 // stp fp, lr, [sp, #offset-16] 153 // add fp, sp, #offset - 16 154 // sub sp, sp, #1360 155 // 156 // The Stack: 157 // +-------------------------------------------+ 158 // 10000 | ........ | ........ | ........ | ........ | 159 // 10004 | ........ | ........ | ........ | ........ | 160 // +-------------------------------------------+ 161 // 10008 | ........ | ........ | ........ | ........ | 162 // 1000c | ........ | ........ | ........ | ........ | 163 // +===========================================+ 164 // 10010 | X28 Register | 165 // 10014 | X28 Register | 166 // +-------------------------------------------+ 167 // 10018 | X27 Register | 168 // 1001c | X27 Register | 169 // +===========================================+ 170 // 10020 | Frame Pointer | 171 // 10024 | Frame Pointer | 172 // +-------------------------------------------+ 173 // 10028 | Link Register | 174 // 1002c | Link Register | 175 // +===========================================+ 176 // 10030 | ........ | ........ | ........ | ........ | 177 // 10034 | ........ | ........ | ........ | ........ | 178 // +-------------------------------------------+ 179 // 10038 | ........ | ........ | ........ | ........ | 180 // 1003c | ........ | ........ | ........ | ........ | 181 // +-------------------------------------------+ 182 // 183 // [sp] = 10030 :: >>initial value<< 184 // sp = 10020 :: stp fp, lr, [sp, #-16]! 185 // fp = sp == 10020 :: mov fp, sp 186 // [sp] == 10020 :: stp x28, x27, [sp, #-16]! 187 // sp == 10010 :: >>final value<< 188 // 189 // The frame pointer (w29) points to address 10020. If we use an offset of 190 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24 191 // for w27, and -32 for w28: 192 // 193 // Ltmp1: 194 // .cfi_def_cfa w29, 16 195 // Ltmp2: 196 // .cfi_offset w30, -8 197 // Ltmp3: 198 // .cfi_offset w29, -16 199 // Ltmp4: 200 // .cfi_offset w27, -24 201 // Ltmp5: 202 // .cfi_offset w28, -32 203 // 204 //===----------------------------------------------------------------------===// 205 206 #include "AArch64FrameLowering.h" 207 #include "AArch64InstrInfo.h" 208 #include "AArch64MachineFunctionInfo.h" 209 #include "AArch64RegisterInfo.h" 210 #include "AArch64Subtarget.h" 211 #include "AArch64TargetMachine.h" 212 #include "MCTargetDesc/AArch64AddressingModes.h" 213 #include "MCTargetDesc/AArch64MCTargetDesc.h" 214 #include "llvm/ADT/ScopeExit.h" 215 #include "llvm/ADT/SmallVector.h" 216 #include "llvm/ADT/Statistic.h" 217 #include "llvm/Analysis/ValueTracking.h" 218 #include "llvm/CodeGen/LivePhysRegs.h" 219 #include "llvm/CodeGen/MachineBasicBlock.h" 220 #include "llvm/CodeGen/MachineFrameInfo.h" 221 #include "llvm/CodeGen/MachineFunction.h" 222 #include "llvm/CodeGen/MachineInstr.h" 223 #include "llvm/CodeGen/MachineInstrBuilder.h" 224 #include "llvm/CodeGen/MachineMemOperand.h" 225 #include "llvm/CodeGen/MachineModuleInfo.h" 226 #include "llvm/CodeGen/MachineOperand.h" 227 #include "llvm/CodeGen/MachineRegisterInfo.h" 228 #include "llvm/CodeGen/RegisterScavenging.h" 229 #include "llvm/CodeGen/TargetInstrInfo.h" 230 #include "llvm/CodeGen/TargetRegisterInfo.h" 231 #include "llvm/CodeGen/TargetSubtargetInfo.h" 232 #include "llvm/CodeGen/WinEHFuncInfo.h" 233 #include "llvm/IR/Attributes.h" 234 #include "llvm/IR/CallingConv.h" 235 #include "llvm/IR/DataLayout.h" 236 #include "llvm/IR/DebugLoc.h" 237 #include "llvm/IR/Function.h" 238 #include "llvm/MC/MCAsmInfo.h" 239 #include "llvm/MC/MCDwarf.h" 240 #include "llvm/Support/CommandLine.h" 241 #include "llvm/Support/Debug.h" 242 #include "llvm/Support/ErrorHandling.h" 243 #include "llvm/Support/FormatVariadic.h" 244 #include "llvm/Support/MathExtras.h" 245 #include "llvm/Support/raw_ostream.h" 246 #include "llvm/Target/TargetMachine.h" 247 #include "llvm/Target/TargetOptions.h" 248 #include <cassert> 249 #include <cstdint> 250 #include <iterator> 251 #include <optional> 252 #include <vector> 253 254 using namespace llvm; 255 256 #define DEBUG_TYPE "frame-info" 257 258 static cl::opt<bool> EnableRedZone("aarch64-redzone", 259 cl::desc("enable use of redzone on AArch64"), 260 cl::init(false), cl::Hidden); 261 262 static cl::opt<bool> StackTaggingMergeSetTag( 263 "stack-tagging-merge-settag", 264 cl::desc("merge settag instruction in function epilog"), cl::init(true), 265 cl::Hidden); 266 267 static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects", 268 cl::desc("sort stack allocations"), 269 cl::init(true), cl::Hidden); 270 271 cl::opt<bool> EnableHomogeneousPrologEpilog( 272 "homogeneous-prolog-epilog", cl::Hidden, 273 cl::desc("Emit homogeneous prologue and epilogue for the size " 274 "optimization (default = off)")); 275 276 // Stack hazard padding size. 0 = disabled. 277 static cl::opt<unsigned> StackHazardSize("aarch64-stack-hazard-size", 278 cl::init(0), cl::Hidden); 279 // Stack hazard size for analysis remarks. StackHazardSize takes precedence. 280 static cl::opt<unsigned> 281 StackHazardRemarkSize("aarch64-stack-hazard-remark-size", cl::init(0), 282 cl::Hidden); 283 // Whether to insert padding into non-streaming functions (for testing). 284 static cl::opt<bool> 285 StackHazardInNonStreaming("aarch64-stack-hazard-in-non-streaming", 286 cl::init(false), cl::Hidden); 287 288 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone"); 289 290 /// Returns how much of the incoming argument stack area (in bytes) we should 291 /// clean up in an epilogue. For the C calling convention this will be 0, for 292 /// guaranteed tail call conventions it can be positive (a normal return or a 293 /// tail call to a function that uses less stack space for arguments) or 294 /// negative (for a tail call to a function that needs more stack space than us 295 /// for arguments). 296 static int64_t getArgumentStackToRestore(MachineFunction &MF, 297 MachineBasicBlock &MBB) { 298 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 299 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 300 bool IsTailCallReturn = (MBB.end() != MBBI) 301 ? AArch64InstrInfo::isTailCallReturnInst(*MBBI) 302 : false; 303 304 int64_t ArgumentPopSize = 0; 305 if (IsTailCallReturn) { 306 MachineOperand &StackAdjust = MBBI->getOperand(1); 307 308 // For a tail-call in a callee-pops-arguments environment, some or all of 309 // the stack may actually be in use for the call's arguments, this is 310 // calculated during LowerCall and consumed here... 311 ArgumentPopSize = StackAdjust.getImm(); 312 } else { 313 // ... otherwise the amount to pop is *all* of the argument space, 314 // conveniently stored in the MachineFunctionInfo by 315 // LowerFormalArguments. This will, of course, be zero for the C calling 316 // convention. 317 ArgumentPopSize = AFI->getArgumentStackToRestore(); 318 } 319 320 return ArgumentPopSize; 321 } 322 323 static bool produceCompactUnwindFrame(MachineFunction &MF); 324 static bool needsWinCFI(const MachineFunction &MF); 325 static StackOffset getSVEStackSize(const MachineFunction &MF); 326 static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB); 327 328 /// Returns true if a homogeneous prolog or epilog code can be emitted 329 /// for the size optimization. If possible, a frame helper call is injected. 330 /// When Exit block is given, this check is for epilog. 331 bool AArch64FrameLowering::homogeneousPrologEpilog( 332 MachineFunction &MF, MachineBasicBlock *Exit) const { 333 if (!MF.getFunction().hasMinSize()) 334 return false; 335 if (!EnableHomogeneousPrologEpilog) 336 return false; 337 if (EnableRedZone) 338 return false; 339 340 // TODO: Window is supported yet. 341 if (needsWinCFI(MF)) 342 return false; 343 // TODO: SVE is not supported yet. 344 if (getSVEStackSize(MF)) 345 return false; 346 347 // Bail on stack adjustment needed on return for simplicity. 348 const MachineFrameInfo &MFI = MF.getFrameInfo(); 349 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 350 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)) 351 return false; 352 if (Exit && getArgumentStackToRestore(MF, *Exit)) 353 return false; 354 355 auto *AFI = MF.getInfo<AArch64FunctionInfo>(); 356 if (AFI->hasSwiftAsyncContext() || AFI->hasStreamingModeChanges()) 357 return false; 358 359 // If there are an odd number of GPRs before LR and FP in the CSRs list, 360 // they will not be paired into one RegPairInfo, which is incompatible with 361 // the assumption made by the homogeneous prolog epilog pass. 362 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs(); 363 unsigned NumGPRs = 0; 364 for (unsigned I = 0; CSRegs[I]; ++I) { 365 Register Reg = CSRegs[I]; 366 if (Reg == AArch64::LR) { 367 assert(CSRegs[I + 1] == AArch64::FP); 368 if (NumGPRs % 2 != 0) 369 return false; 370 break; 371 } 372 if (AArch64::GPR64RegClass.contains(Reg)) 373 ++NumGPRs; 374 } 375 376 return true; 377 } 378 379 /// Returns true if CSRs should be paired. 380 bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const { 381 return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF); 382 } 383 384 /// This is the biggest offset to the stack pointer we can encode in aarch64 385 /// instructions (without using a separate calculation and a temp register). 386 /// Note that the exception here are vector stores/loads which cannot encode any 387 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()). 388 static const unsigned DefaultSafeSPDisplacement = 255; 389 390 /// Look at each instruction that references stack frames and return the stack 391 /// size limit beyond which some of these instructions will require a scratch 392 /// register during their expansion later. 393 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) { 394 // FIXME: For now, just conservatively guestimate based on unscaled indexing 395 // range. We'll end up allocating an unnecessary spill slot a lot, but 396 // realistically that's not a big deal at this stage of the game. 397 for (MachineBasicBlock &MBB : MF) { 398 for (MachineInstr &MI : MBB) { 399 if (MI.isDebugInstr() || MI.isPseudo() || 400 MI.getOpcode() == AArch64::ADDXri || 401 MI.getOpcode() == AArch64::ADDSXri) 402 continue; 403 404 for (const MachineOperand &MO : MI.operands()) { 405 if (!MO.isFI()) 406 continue; 407 408 StackOffset Offset; 409 if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) == 410 AArch64FrameOffsetCannotUpdate) 411 return 0; 412 } 413 } 414 } 415 return DefaultSafeSPDisplacement; 416 } 417 418 TargetStackID::Value 419 AArch64FrameLowering::getStackIDForScalableVectors() const { 420 return TargetStackID::ScalableVector; 421 } 422 423 /// Returns the size of the fixed object area (allocated next to sp on entry) 424 /// On Win64 this may include a var args area and an UnwindHelp object for EH. 425 static unsigned getFixedObjectSize(const MachineFunction &MF, 426 const AArch64FunctionInfo *AFI, bool IsWin64, 427 bool IsFunclet) { 428 if (!IsWin64 || IsFunclet) { 429 return AFI->getTailCallReservedStack(); 430 } else { 431 if (AFI->getTailCallReservedStack() != 0 && 432 !MF.getFunction().getAttributes().hasAttrSomewhere( 433 Attribute::SwiftAsync)) 434 report_fatal_error("cannot generate ABI-changing tail call for Win64"); 435 // Var args are stored here in the primary function. 436 const unsigned VarArgsArea = AFI->getVarArgsGPRSize(); 437 // To support EH funclets we allocate an UnwindHelp object 438 const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0); 439 return AFI->getTailCallReservedStack() + 440 alignTo(VarArgsArea + UnwindHelpObject, 16); 441 } 442 } 443 444 /// Returns the size of the entire SVE stackframe (calleesaves + spills). 445 static StackOffset getSVEStackSize(const MachineFunction &MF) { 446 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 447 return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE()); 448 } 449 450 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const { 451 if (!EnableRedZone) 452 return false; 453 454 // Don't use the red zone if the function explicitly asks us not to. 455 // This is typically used for kernel code. 456 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 457 const unsigned RedZoneSize = 458 Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction()); 459 if (!RedZoneSize) 460 return false; 461 462 const MachineFrameInfo &MFI = MF.getFrameInfo(); 463 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 464 uint64_t NumBytes = AFI->getLocalStackSize(); 465 466 // If neither NEON or SVE are available, a COPY from one Q-reg to 467 // another requires a spill -> reload sequence. We can do that 468 // using a pre-decrementing store/post-decrementing load, but 469 // if we do so, we can't use the Red Zone. 470 bool LowerQRegCopyThroughMem = Subtarget.hasFPARMv8() && 471 !Subtarget.isNeonAvailable() && 472 !Subtarget.hasSVE(); 473 474 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize || 475 getSVEStackSize(MF) || LowerQRegCopyThroughMem); 476 } 477 478 /// hasFP - Return true if the specified function should have a dedicated frame 479 /// pointer register. 480 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const { 481 const MachineFrameInfo &MFI = MF.getFrameInfo(); 482 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 483 484 // Win64 EH requires a frame pointer if funclets are present, as the locals 485 // are accessed off the frame pointer in both the parent function and the 486 // funclets. 487 if (MF.hasEHFunclets()) 488 return true; 489 // Retain behavior of always omitting the FP for leaf functions when possible. 490 if (MF.getTarget().Options.DisableFramePointerElim(MF)) 491 return true; 492 if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() || 493 MFI.hasStackMap() || MFI.hasPatchPoint() || 494 RegInfo->hasStackRealignment(MF)) 495 return true; 496 // With large callframes around we may need to use FP to access the scavenging 497 // emergency spillslot. 498 // 499 // Unfortunately some calls to hasFP() like machine verifier -> 500 // getReservedReg() -> hasFP in the middle of global isel are too early 501 // to know the max call frame size. Hopefully conservatively returning "true" 502 // in those cases is fine. 503 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs. 504 if (!MFI.isMaxCallFrameSizeComputed() || 505 MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement) 506 return true; 507 508 return false; 509 } 510 511 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 512 /// not required, we reserve argument space for call sites in the function 513 /// immediately on entry to the current function. This eliminates the need for 514 /// add/sub sp brackets around call sites. Returns true if the call frame is 515 /// included as part of the stack frame. 516 bool AArch64FrameLowering::hasReservedCallFrame( 517 const MachineFunction &MF) const { 518 // The stack probing code for the dynamically allocated outgoing arguments 519 // area assumes that the stack is probed at the top - either by the prologue 520 // code, which issues a probe if `hasVarSizedObjects` return true, or by the 521 // most recent variable-sized object allocation. Changing the condition here 522 // may need to be followed up by changes to the probe issuing logic. 523 return !MF.getFrameInfo().hasVarSizedObjects(); 524 } 525 526 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr( 527 MachineFunction &MF, MachineBasicBlock &MBB, 528 MachineBasicBlock::iterator I) const { 529 const AArch64InstrInfo *TII = 530 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo()); 531 const AArch64TargetLowering *TLI = 532 MF.getSubtarget<AArch64Subtarget>().getTargetLowering(); 533 [[maybe_unused]] MachineFrameInfo &MFI = MF.getFrameInfo(); 534 DebugLoc DL = I->getDebugLoc(); 535 unsigned Opc = I->getOpcode(); 536 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode(); 537 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0; 538 539 if (!hasReservedCallFrame(MF)) { 540 int64_t Amount = I->getOperand(0).getImm(); 541 Amount = alignTo(Amount, getStackAlign()); 542 if (!IsDestroy) 543 Amount = -Amount; 544 545 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it 546 // doesn't have to pop anything), then the first operand will be zero too so 547 // this adjustment is a no-op. 548 if (CalleePopAmount == 0) { 549 // FIXME: in-function stack adjustment for calls is limited to 24-bits 550 // because there's no guaranteed temporary register available. 551 // 552 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available. 553 // 1) For offset <= 12-bit, we use LSL #0 554 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses 555 // LSL #0, and the other uses LSL #12. 556 // 557 // Most call frames will be allocated at the start of a function so 558 // this is OK, but it is a limitation that needs dealing with. 559 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large"); 560 561 if (TLI->hasInlineStackProbe(MF) && 562 -Amount >= AArch64::StackProbeMaxUnprobedStack) { 563 // When stack probing is enabled, the decrement of SP may need to be 564 // probed. We only need to do this if the call site needs 1024 bytes of 565 // space or more, because a region smaller than that is allowed to be 566 // unprobed at an ABI boundary. We rely on the fact that SP has been 567 // probed exactly at this point, either by the prologue or most recent 568 // dynamic allocation. 569 assert(MFI.hasVarSizedObjects() && 570 "non-reserved call frame without var sized objects?"); 571 Register ScratchReg = 572 MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass); 573 inlineStackProbeFixed(I, ScratchReg, -Amount, StackOffset::get(0, 0)); 574 } else { 575 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, 576 StackOffset::getFixed(Amount), TII); 577 } 578 } 579 } else if (CalleePopAmount != 0) { 580 // If the calling convention demands that the callee pops arguments from the 581 // stack, we want to add it back if we have a reserved call frame. 582 assert(CalleePopAmount < 0xffffff && "call frame too large"); 583 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, 584 StackOffset::getFixed(-(int64_t)CalleePopAmount), TII); 585 } 586 return MBB.erase(I); 587 } 588 589 void AArch64FrameLowering::emitCalleeSavedGPRLocations( 590 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 591 MachineFunction &MF = *MBB.getParent(); 592 MachineFrameInfo &MFI = MF.getFrameInfo(); 593 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 594 SMEAttrs Attrs(MF.getFunction()); 595 bool LocallyStreaming = 596 Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface(); 597 598 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 599 if (CSI.empty()) 600 return; 601 602 const TargetSubtargetInfo &STI = MF.getSubtarget(); 603 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 604 const TargetInstrInfo &TII = *STI.getInstrInfo(); 605 DebugLoc DL = MBB.findDebugLoc(MBBI); 606 607 for (const auto &Info : CSI) { 608 unsigned FrameIdx = Info.getFrameIdx(); 609 if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector) 610 continue; 611 612 assert(!Info.isSpilledToReg() && "Spilling to registers not implemented"); 613 int64_t DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true); 614 int64_t Offset = MFI.getObjectOffset(FrameIdx) - getOffsetOfLocalArea(); 615 616 // The location of VG will be emitted before each streaming-mode change in 617 // the function. Only locally-streaming functions require emitting the 618 // non-streaming VG location here. 619 if ((LocallyStreaming && FrameIdx == AFI->getStreamingVGIdx()) || 620 (!LocallyStreaming && 621 DwarfReg == TRI.getDwarfRegNum(AArch64::VG, true))) 622 continue; 623 624 unsigned CFIIndex = MF.addFrameInst( 625 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 626 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 627 .addCFIIndex(CFIIndex) 628 .setMIFlags(MachineInstr::FrameSetup); 629 } 630 } 631 632 void AArch64FrameLowering::emitCalleeSavedSVELocations( 633 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 634 MachineFunction &MF = *MBB.getParent(); 635 MachineFrameInfo &MFI = MF.getFrameInfo(); 636 637 // Add callee saved registers to move list. 638 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 639 if (CSI.empty()) 640 return; 641 642 const TargetSubtargetInfo &STI = MF.getSubtarget(); 643 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 644 const TargetInstrInfo &TII = *STI.getInstrInfo(); 645 DebugLoc DL = MBB.findDebugLoc(MBBI); 646 AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>(); 647 648 for (const auto &Info : CSI) { 649 if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector)) 650 continue; 651 652 // Not all unwinders may know about SVE registers, so assume the lowest 653 // common demoninator. 654 assert(!Info.isSpilledToReg() && "Spilling to registers not implemented"); 655 unsigned Reg = Info.getReg(); 656 if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg)) 657 continue; 658 659 StackOffset Offset = 660 StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) - 661 StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI)); 662 663 unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset)); 664 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 665 .addCFIIndex(CFIIndex) 666 .setMIFlags(MachineInstr::FrameSetup); 667 } 668 } 669 670 static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF, 671 MachineBasicBlock &MBB, 672 MachineBasicBlock::iterator InsertPt, 673 unsigned DwarfReg) { 674 unsigned CFIIndex = 675 MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg)); 676 BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex); 677 } 678 679 void AArch64FrameLowering::resetCFIToInitialState( 680 MachineBasicBlock &MBB) const { 681 682 MachineFunction &MF = *MBB.getParent(); 683 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 684 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 685 const auto &TRI = 686 static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo()); 687 const auto &MFI = *MF.getInfo<AArch64FunctionInfo>(); 688 689 const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION); 690 DebugLoc DL; 691 692 // Reset the CFA to `SP + 0`. 693 MachineBasicBlock::iterator InsertPt = MBB.begin(); 694 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa( 695 nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0)); 696 BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex); 697 698 // Flip the RA sign state. 699 if (MFI.shouldSignReturnAddress(MF)) { 700 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr)); 701 BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex); 702 } 703 704 // Shadow call stack uses X18, reset it. 705 if (MFI.needsShadowCallStackPrologueEpilogue(MF)) 706 insertCFISameValue(CFIDesc, MF, MBB, InsertPt, 707 TRI.getDwarfRegNum(AArch64::X18, true)); 708 709 // Emit .cfi_same_value for callee-saved registers. 710 const std::vector<CalleeSavedInfo> &CSI = 711 MF.getFrameInfo().getCalleeSavedInfo(); 712 for (const auto &Info : CSI) { 713 unsigned Reg = Info.getReg(); 714 if (!TRI.regNeedsCFI(Reg, Reg)) 715 continue; 716 insertCFISameValue(CFIDesc, MF, MBB, InsertPt, 717 TRI.getDwarfRegNum(Reg, true)); 718 } 719 } 720 721 static void emitCalleeSavedRestores(MachineBasicBlock &MBB, 722 MachineBasicBlock::iterator MBBI, 723 bool SVE) { 724 MachineFunction &MF = *MBB.getParent(); 725 MachineFrameInfo &MFI = MF.getFrameInfo(); 726 727 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 728 if (CSI.empty()) 729 return; 730 731 const TargetSubtargetInfo &STI = MF.getSubtarget(); 732 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 733 const TargetInstrInfo &TII = *STI.getInstrInfo(); 734 DebugLoc DL = MBB.findDebugLoc(MBBI); 735 736 for (const auto &Info : CSI) { 737 if (SVE != 738 (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector)) 739 continue; 740 741 unsigned Reg = Info.getReg(); 742 if (SVE && 743 !static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg)) 744 continue; 745 746 if (!Info.isRestored()) 747 continue; 748 749 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore( 750 nullptr, TRI.getDwarfRegNum(Info.getReg(), true))); 751 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 752 .addCFIIndex(CFIIndex) 753 .setMIFlags(MachineInstr::FrameDestroy); 754 } 755 } 756 757 void AArch64FrameLowering::emitCalleeSavedGPRRestores( 758 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 759 emitCalleeSavedRestores(MBB, MBBI, false); 760 } 761 762 void AArch64FrameLowering::emitCalleeSavedSVERestores( 763 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 764 emitCalleeSavedRestores(MBB, MBBI, true); 765 } 766 767 // Return the maximum possible number of bytes for `Size` due to the 768 // architectural limit on the size of a SVE register. 769 static int64_t upperBound(StackOffset Size) { 770 static const int64_t MAX_BYTES_PER_SCALABLE_BYTE = 16; 771 return Size.getScalable() * MAX_BYTES_PER_SCALABLE_BYTE + Size.getFixed(); 772 } 773 774 void AArch64FrameLowering::allocateStackSpace( 775 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 776 int64_t RealignmentPadding, StackOffset AllocSize, bool NeedsWinCFI, 777 bool *HasWinCFI, bool EmitCFI, StackOffset InitialOffset, 778 bool FollowupAllocs) const { 779 780 if (!AllocSize) 781 return; 782 783 DebugLoc DL; 784 MachineFunction &MF = *MBB.getParent(); 785 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 786 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 787 AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>(); 788 const MachineFrameInfo &MFI = MF.getFrameInfo(); 789 790 const int64_t MaxAlign = MFI.getMaxAlign().value(); 791 const uint64_t AndMask = ~(MaxAlign - 1); 792 793 if (!Subtarget.getTargetLowering()->hasInlineStackProbe(MF)) { 794 Register TargetReg = RealignmentPadding 795 ? findScratchNonCalleeSaveRegister(&MBB) 796 : AArch64::SP; 797 // SUB Xd/SP, SP, AllocSize 798 emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII, 799 MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI, 800 EmitCFI, InitialOffset); 801 802 if (RealignmentPadding) { 803 // AND SP, X9, 0b11111...0000 804 BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP) 805 .addReg(TargetReg, RegState::Kill) 806 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64)) 807 .setMIFlags(MachineInstr::FrameSetup); 808 AFI.setStackRealigned(true); 809 810 // No need for SEH instructions here; if we're realigning the stack, 811 // we've set a frame pointer and already finished the SEH prologue. 812 assert(!NeedsWinCFI); 813 } 814 return; 815 } 816 817 // 818 // Stack probing allocation. 819 // 820 821 // Fixed length allocation. If we don't need to re-align the stack and don't 822 // have SVE objects, we can use a more efficient sequence for stack probing. 823 if (AllocSize.getScalable() == 0 && RealignmentPadding == 0) { 824 Register ScratchReg = findScratchNonCalleeSaveRegister(&MBB); 825 assert(ScratchReg != AArch64::NoRegister); 826 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC)) 827 .addDef(ScratchReg) 828 .addImm(AllocSize.getFixed()) 829 .addImm(InitialOffset.getFixed()) 830 .addImm(InitialOffset.getScalable()); 831 // The fixed allocation may leave unprobed bytes at the top of the 832 // stack. If we have subsequent alocation (e.g. if we have variable-sized 833 // objects), we need to issue an extra probe, so these allocations start in 834 // a known state. 835 if (FollowupAllocs) { 836 // STR XZR, [SP] 837 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui)) 838 .addReg(AArch64::XZR) 839 .addReg(AArch64::SP) 840 .addImm(0) 841 .setMIFlags(MachineInstr::FrameSetup); 842 } 843 844 return; 845 } 846 847 // Variable length allocation. 848 849 // If the (unknown) allocation size cannot exceed the probe size, decrement 850 // the stack pointer right away. 851 int64_t ProbeSize = AFI.getStackProbeSize(); 852 if (upperBound(AllocSize) + RealignmentPadding <= ProbeSize) { 853 Register ScratchReg = RealignmentPadding 854 ? findScratchNonCalleeSaveRegister(&MBB) 855 : AArch64::SP; 856 assert(ScratchReg != AArch64::NoRegister); 857 // SUB Xd, SP, AllocSize 858 emitFrameOffset(MBB, MBBI, DL, ScratchReg, AArch64::SP, -AllocSize, &TII, 859 MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI, 860 EmitCFI, InitialOffset); 861 if (RealignmentPadding) { 862 // AND SP, Xn, 0b11111...0000 863 BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP) 864 .addReg(ScratchReg, RegState::Kill) 865 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64)) 866 .setMIFlags(MachineInstr::FrameSetup); 867 AFI.setStackRealigned(true); 868 } 869 if (FollowupAllocs || upperBound(AllocSize) + RealignmentPadding > 870 AArch64::StackProbeMaxUnprobedStack) { 871 // STR XZR, [SP] 872 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui)) 873 .addReg(AArch64::XZR) 874 .addReg(AArch64::SP) 875 .addImm(0) 876 .setMIFlags(MachineInstr::FrameSetup); 877 } 878 return; 879 } 880 881 // Emit a variable-length allocation probing loop. 882 // TODO: As an optimisation, the loop can be "unrolled" into a few parts, 883 // each of them guaranteed to adjust the stack by less than the probe size. 884 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB); 885 assert(TargetReg != AArch64::NoRegister); 886 // SUB Xd, SP, AllocSize 887 emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII, 888 MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI, 889 EmitCFI, InitialOffset); 890 if (RealignmentPadding) { 891 // AND Xn, Xn, 0b11111...0000 892 BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), TargetReg) 893 .addReg(TargetReg, RegState::Kill) 894 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64)) 895 .setMIFlags(MachineInstr::FrameSetup); 896 } 897 898 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC_VAR)) 899 .addReg(TargetReg); 900 if (EmitCFI) { 901 // Set the CFA register back to SP. 902 unsigned Reg = 903 Subtarget.getRegisterInfo()->getDwarfRegNum(AArch64::SP, true); 904 unsigned CFIIndex = 905 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg)); 906 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 907 .addCFIIndex(CFIIndex) 908 .setMIFlags(MachineInstr::FrameSetup); 909 } 910 if (RealignmentPadding) 911 AFI.setStackRealigned(true); 912 } 913 914 static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) { 915 switch (Reg.id()) { 916 default: 917 // The called routine is expected to preserve r19-r28 918 // r29 and r30 are used as frame pointer and link register resp. 919 return 0; 920 921 // GPRs 922 #define CASE(n) \ 923 case AArch64::W##n: \ 924 case AArch64::X##n: \ 925 return AArch64::X##n 926 CASE(0); 927 CASE(1); 928 CASE(2); 929 CASE(3); 930 CASE(4); 931 CASE(5); 932 CASE(6); 933 CASE(7); 934 CASE(8); 935 CASE(9); 936 CASE(10); 937 CASE(11); 938 CASE(12); 939 CASE(13); 940 CASE(14); 941 CASE(15); 942 CASE(16); 943 CASE(17); 944 CASE(18); 945 #undef CASE 946 947 // FPRs 948 #define CASE(n) \ 949 case AArch64::B##n: \ 950 case AArch64::H##n: \ 951 case AArch64::S##n: \ 952 case AArch64::D##n: \ 953 case AArch64::Q##n: \ 954 return HasSVE ? AArch64::Z##n : AArch64::Q##n 955 CASE(0); 956 CASE(1); 957 CASE(2); 958 CASE(3); 959 CASE(4); 960 CASE(5); 961 CASE(6); 962 CASE(7); 963 CASE(8); 964 CASE(9); 965 CASE(10); 966 CASE(11); 967 CASE(12); 968 CASE(13); 969 CASE(14); 970 CASE(15); 971 CASE(16); 972 CASE(17); 973 CASE(18); 974 CASE(19); 975 CASE(20); 976 CASE(21); 977 CASE(22); 978 CASE(23); 979 CASE(24); 980 CASE(25); 981 CASE(26); 982 CASE(27); 983 CASE(28); 984 CASE(29); 985 CASE(30); 986 CASE(31); 987 #undef CASE 988 } 989 } 990 991 void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero, 992 MachineBasicBlock &MBB) const { 993 // Insertion point. 994 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); 995 996 // Fake a debug loc. 997 DebugLoc DL; 998 if (MBBI != MBB.end()) 999 DL = MBBI->getDebugLoc(); 1000 1001 const MachineFunction &MF = *MBB.getParent(); 1002 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>(); 1003 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo(); 1004 1005 BitVector GPRsToZero(TRI.getNumRegs()); 1006 BitVector FPRsToZero(TRI.getNumRegs()); 1007 bool HasSVE = STI.hasSVE(); 1008 for (MCRegister Reg : RegsToZero.set_bits()) { 1009 if (TRI.isGeneralPurposeRegister(MF, Reg)) { 1010 // For GPRs, we only care to clear out the 64-bit register. 1011 if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE)) 1012 GPRsToZero.set(XReg); 1013 } else if (AArch64InstrInfo::isFpOrNEON(Reg)) { 1014 // For FPRs, 1015 if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE)) 1016 FPRsToZero.set(XReg); 1017 } 1018 } 1019 1020 const AArch64InstrInfo &TII = *STI.getInstrInfo(); 1021 1022 // Zero out GPRs. 1023 for (MCRegister Reg : GPRsToZero.set_bits()) 1024 TII.buildClearRegister(Reg, MBB, MBBI, DL); 1025 1026 // Zero out FP/vector registers. 1027 for (MCRegister Reg : FPRsToZero.set_bits()) 1028 TII.buildClearRegister(Reg, MBB, MBBI, DL); 1029 1030 if (HasSVE) { 1031 for (MCRegister PReg : 1032 {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4, 1033 AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9, 1034 AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14, 1035 AArch64::P15}) { 1036 if (RegsToZero[PReg]) 1037 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg); 1038 } 1039 } 1040 } 1041 1042 static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs, 1043 const MachineBasicBlock &MBB) { 1044 const MachineFunction *MF = MBB.getParent(); 1045 LiveRegs.addLiveIns(MBB); 1046 // Mark callee saved registers as used so we will not choose them. 1047 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs(); 1048 for (unsigned i = 0; CSRegs[i]; ++i) 1049 LiveRegs.addReg(CSRegs[i]); 1050 } 1051 1052 // Find a scratch register that we can use at the start of the prologue to 1053 // re-align the stack pointer. We avoid using callee-save registers since they 1054 // may appear to be free when this is called from canUseAsPrologue (during 1055 // shrink wrapping), but then no longer be free when this is called from 1056 // emitPrologue. 1057 // 1058 // FIXME: This is a bit conservative, since in the above case we could use one 1059 // of the callee-save registers as a scratch temp to re-align the stack pointer, 1060 // but we would then have to make sure that we were in fact saving at least one 1061 // callee-save register in the prologue, which is additional complexity that 1062 // doesn't seem worth the benefit. 1063 static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) { 1064 MachineFunction *MF = MBB->getParent(); 1065 1066 // If MBB is an entry block, use X9 as the scratch register 1067 // preserve_none functions may be using X9 to pass arguments, 1068 // so prefer to pick an available register below. 1069 if (&MF->front() == MBB && 1070 MF->getFunction().getCallingConv() != CallingConv::PreserveNone) 1071 return AArch64::X9; 1072 1073 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 1074 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo(); 1075 LivePhysRegs LiveRegs(TRI); 1076 getLiveRegsForEntryMBB(LiveRegs, *MBB); 1077 1078 // Prefer X9 since it was historically used for the prologue scratch reg. 1079 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1080 if (LiveRegs.available(MRI, AArch64::X9)) 1081 return AArch64::X9; 1082 1083 for (unsigned Reg : AArch64::GPR64RegClass) { 1084 if (LiveRegs.available(MRI, Reg)) 1085 return Reg; 1086 } 1087 return AArch64::NoRegister; 1088 } 1089 1090 bool AArch64FrameLowering::canUseAsPrologue( 1091 const MachineBasicBlock &MBB) const { 1092 const MachineFunction *MF = MBB.getParent(); 1093 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB); 1094 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 1095 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 1096 const AArch64TargetLowering *TLI = Subtarget.getTargetLowering(); 1097 const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>(); 1098 1099 if (AFI->hasSwiftAsyncContext()) { 1100 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo(); 1101 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1102 LivePhysRegs LiveRegs(TRI); 1103 getLiveRegsForEntryMBB(LiveRegs, MBB); 1104 // The StoreSwiftAsyncContext clobbers X16 and X17. Make sure they are 1105 // available. 1106 if (!LiveRegs.available(MRI, AArch64::X16) || 1107 !LiveRegs.available(MRI, AArch64::X17)) 1108 return false; 1109 } 1110 1111 // Certain stack probing sequences might clobber flags, then we can't use 1112 // the block as a prologue if the flags register is a live-in. 1113 if (MF->getInfo<AArch64FunctionInfo>()->hasStackProbing() && 1114 MBB.isLiveIn(AArch64::NZCV)) 1115 return false; 1116 1117 // Don't need a scratch register if we're not going to re-align the stack or 1118 // emit stack probes. 1119 if (!RegInfo->hasStackRealignment(*MF) && !TLI->hasInlineStackProbe(*MF)) 1120 return true; 1121 // Otherwise, we can use any block as long as it has a scratch register 1122 // available. 1123 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister; 1124 } 1125 1126 static bool windowsRequiresStackProbe(MachineFunction &MF, 1127 uint64_t StackSizeInBytes) { 1128 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1129 const AArch64FunctionInfo &MFI = *MF.getInfo<AArch64FunctionInfo>(); 1130 // TODO: When implementing stack protectors, take that into account 1131 // for the probe threshold. 1132 return Subtarget.isTargetWindows() && MFI.hasStackProbing() && 1133 StackSizeInBytes >= uint64_t(MFI.getStackProbeSize()); 1134 } 1135 1136 static bool needsWinCFI(const MachineFunction &MF) { 1137 const Function &F = MF.getFunction(); 1138 return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() && 1139 F.needsUnwindTableEntry(); 1140 } 1141 1142 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump( 1143 MachineFunction &MF, uint64_t StackBumpBytes) const { 1144 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1145 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1146 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1147 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 1148 if (homogeneousPrologEpilog(MF)) 1149 return false; 1150 1151 if (AFI->getLocalStackSize() == 0) 1152 return false; 1153 1154 // For WinCFI, if optimizing for size, prefer to not combine the stack bump 1155 // (to force a stp with predecrement) to match the packed unwind format, 1156 // provided that there actually are any callee saved registers to merge the 1157 // decrement with. 1158 // This is potentially marginally slower, but allows using the packed 1159 // unwind format for functions that both have a local area and callee saved 1160 // registers. Using the packed unwind format notably reduces the size of 1161 // the unwind info. 1162 if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 && 1163 MF.getFunction().hasOptSize()) 1164 return false; 1165 1166 // 512 is the maximum immediate for stp/ldp that will be used for 1167 // callee-save save/restores 1168 if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes)) 1169 return false; 1170 1171 if (MFI.hasVarSizedObjects()) 1172 return false; 1173 1174 if (RegInfo->hasStackRealignment(MF)) 1175 return false; 1176 1177 // This isn't strictly necessary, but it simplifies things a bit since the 1178 // current RedZone handling code assumes the SP is adjusted by the 1179 // callee-save save/restore code. 1180 if (canUseRedZone(MF)) 1181 return false; 1182 1183 // When there is an SVE area on the stack, always allocate the 1184 // callee-saves and spills/locals separately. 1185 if (getSVEStackSize(MF)) 1186 return false; 1187 1188 return true; 1189 } 1190 1191 bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue( 1192 MachineBasicBlock &MBB, unsigned StackBumpBytes) const { 1193 if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes)) 1194 return false; 1195 1196 if (MBB.empty()) 1197 return true; 1198 1199 // Disable combined SP bump if the last instruction is an MTE tag store. It 1200 // is almost always better to merge SP adjustment into those instructions. 1201 MachineBasicBlock::iterator LastI = MBB.getFirstTerminator(); 1202 MachineBasicBlock::iterator Begin = MBB.begin(); 1203 while (LastI != Begin) { 1204 --LastI; 1205 if (LastI->isTransient()) 1206 continue; 1207 if (!LastI->getFlag(MachineInstr::FrameDestroy)) 1208 break; 1209 } 1210 switch (LastI->getOpcode()) { 1211 case AArch64::STGloop: 1212 case AArch64::STZGloop: 1213 case AArch64::STGi: 1214 case AArch64::STZGi: 1215 case AArch64::ST2Gi: 1216 case AArch64::STZ2Gi: 1217 return false; 1218 default: 1219 return true; 1220 } 1221 llvm_unreachable("unreachable"); 1222 } 1223 1224 // Given a load or a store instruction, generate an appropriate unwinding SEH 1225 // code on Windows. 1226 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI, 1227 const TargetInstrInfo &TII, 1228 MachineInstr::MIFlag Flag) { 1229 unsigned Opc = MBBI->getOpcode(); 1230 MachineBasicBlock *MBB = MBBI->getParent(); 1231 MachineFunction &MF = *MBB->getParent(); 1232 DebugLoc DL = MBBI->getDebugLoc(); 1233 unsigned ImmIdx = MBBI->getNumOperands() - 1; 1234 int Imm = MBBI->getOperand(ImmIdx).getImm(); 1235 MachineInstrBuilder MIB; 1236 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1237 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 1238 1239 switch (Opc) { 1240 default: 1241 llvm_unreachable("No SEH Opcode for this instruction"); 1242 case AArch64::LDPDpost: 1243 Imm = -Imm; 1244 [[fallthrough]]; 1245 case AArch64::STPDpre: { 1246 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1247 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg()); 1248 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X)) 1249 .addImm(Reg0) 1250 .addImm(Reg1) 1251 .addImm(Imm * 8) 1252 .setMIFlag(Flag); 1253 break; 1254 } 1255 case AArch64::LDPXpost: 1256 Imm = -Imm; 1257 [[fallthrough]]; 1258 case AArch64::STPXpre: { 1259 Register Reg0 = MBBI->getOperand(1).getReg(); 1260 Register Reg1 = MBBI->getOperand(2).getReg(); 1261 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR) 1262 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X)) 1263 .addImm(Imm * 8) 1264 .setMIFlag(Flag); 1265 else 1266 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X)) 1267 .addImm(RegInfo->getSEHRegNum(Reg0)) 1268 .addImm(RegInfo->getSEHRegNum(Reg1)) 1269 .addImm(Imm * 8) 1270 .setMIFlag(Flag); 1271 break; 1272 } 1273 case AArch64::LDRDpost: 1274 Imm = -Imm; 1275 [[fallthrough]]; 1276 case AArch64::STRDpre: { 1277 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1278 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X)) 1279 .addImm(Reg) 1280 .addImm(Imm) 1281 .setMIFlag(Flag); 1282 break; 1283 } 1284 case AArch64::LDRXpost: 1285 Imm = -Imm; 1286 [[fallthrough]]; 1287 case AArch64::STRXpre: { 1288 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1289 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X)) 1290 .addImm(Reg) 1291 .addImm(Imm) 1292 .setMIFlag(Flag); 1293 break; 1294 } 1295 case AArch64::STPDi: 1296 case AArch64::LDPDi: { 1297 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 1298 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1299 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP)) 1300 .addImm(Reg0) 1301 .addImm(Reg1) 1302 .addImm(Imm * 8) 1303 .setMIFlag(Flag); 1304 break; 1305 } 1306 case AArch64::STPXi: 1307 case AArch64::LDPXi: { 1308 Register Reg0 = MBBI->getOperand(0).getReg(); 1309 Register Reg1 = MBBI->getOperand(1).getReg(); 1310 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR) 1311 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR)) 1312 .addImm(Imm * 8) 1313 .setMIFlag(Flag); 1314 else 1315 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP)) 1316 .addImm(RegInfo->getSEHRegNum(Reg0)) 1317 .addImm(RegInfo->getSEHRegNum(Reg1)) 1318 .addImm(Imm * 8) 1319 .setMIFlag(Flag); 1320 break; 1321 } 1322 case AArch64::STRXui: 1323 case AArch64::LDRXui: { 1324 int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 1325 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg)) 1326 .addImm(Reg) 1327 .addImm(Imm * 8) 1328 .setMIFlag(Flag); 1329 break; 1330 } 1331 case AArch64::STRDui: 1332 case AArch64::LDRDui: { 1333 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 1334 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg)) 1335 .addImm(Reg) 1336 .addImm(Imm * 8) 1337 .setMIFlag(Flag); 1338 break; 1339 } 1340 case AArch64::STPQi: 1341 case AArch64::LDPQi: { 1342 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 1343 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1344 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQP)) 1345 .addImm(Reg0) 1346 .addImm(Reg1) 1347 .addImm(Imm * 16) 1348 .setMIFlag(Flag); 1349 break; 1350 } 1351 case AArch64::LDPQpost: 1352 Imm = -Imm; 1353 [[fallthrough]]; 1354 case AArch64::STPQpre: { 1355 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 1356 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg()); 1357 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQPX)) 1358 .addImm(Reg0) 1359 .addImm(Reg1) 1360 .addImm(Imm * 16) 1361 .setMIFlag(Flag); 1362 break; 1363 } 1364 } 1365 auto I = MBB->insertAfter(MBBI, MIB); 1366 return I; 1367 } 1368 1369 // Fix up the SEH opcode associated with the save/restore instruction. 1370 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI, 1371 unsigned LocalStackSize) { 1372 MachineOperand *ImmOpnd = nullptr; 1373 unsigned ImmIdx = MBBI->getNumOperands() - 1; 1374 switch (MBBI->getOpcode()) { 1375 default: 1376 llvm_unreachable("Fix the offset in the SEH instruction"); 1377 case AArch64::SEH_SaveFPLR: 1378 case AArch64::SEH_SaveRegP: 1379 case AArch64::SEH_SaveReg: 1380 case AArch64::SEH_SaveFRegP: 1381 case AArch64::SEH_SaveFReg: 1382 case AArch64::SEH_SaveAnyRegQP: 1383 case AArch64::SEH_SaveAnyRegQPX: 1384 ImmOpnd = &MBBI->getOperand(ImmIdx); 1385 break; 1386 } 1387 if (ImmOpnd) 1388 ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize); 1389 } 1390 1391 bool requiresGetVGCall(MachineFunction &MF) { 1392 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1393 return AFI->hasStreamingModeChanges() && 1394 !MF.getSubtarget<AArch64Subtarget>().hasSVE(); 1395 } 1396 1397 bool isVGInstruction(MachineBasicBlock::iterator MBBI) { 1398 unsigned Opc = MBBI->getOpcode(); 1399 if (Opc == AArch64::CNTD_XPiI || Opc == AArch64::RDSVLI_XI || 1400 Opc == AArch64::UBFMXri) 1401 return true; 1402 1403 if (requiresGetVGCall(*MBBI->getMF())) { 1404 if (Opc == AArch64::ORRXrr) 1405 return true; 1406 1407 if (Opc == AArch64::BL) { 1408 auto Op1 = MBBI->getOperand(0); 1409 return Op1.isSymbol() && 1410 (StringRef(Op1.getSymbolName()) == "__arm_get_current_vg"); 1411 } 1412 } 1413 1414 return false; 1415 } 1416 1417 // Convert callee-save register save/restore instruction to do stack pointer 1418 // decrement/increment to allocate/deallocate the callee-save stack area by 1419 // converting store/load to use pre/post increment version. 1420 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec( 1421 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 1422 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc, 1423 bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI, 1424 MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup, 1425 int CFAOffset = 0) { 1426 unsigned NewOpc; 1427 1428 // If the function contains streaming mode changes, we expect instructions 1429 // to calculate the value of VG before spilling. For locally-streaming 1430 // functions, we need to do this for both the streaming and non-streaming 1431 // vector length. Move past these instructions if necessary. 1432 MachineFunction &MF = *MBB.getParent(); 1433 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1434 if (AFI->hasStreamingModeChanges()) 1435 while (isVGInstruction(MBBI)) 1436 ++MBBI; 1437 1438 switch (MBBI->getOpcode()) { 1439 default: 1440 llvm_unreachable("Unexpected callee-save save/restore opcode!"); 1441 case AArch64::STPXi: 1442 NewOpc = AArch64::STPXpre; 1443 break; 1444 case AArch64::STPDi: 1445 NewOpc = AArch64::STPDpre; 1446 break; 1447 case AArch64::STPQi: 1448 NewOpc = AArch64::STPQpre; 1449 break; 1450 case AArch64::STRXui: 1451 NewOpc = AArch64::STRXpre; 1452 break; 1453 case AArch64::STRDui: 1454 NewOpc = AArch64::STRDpre; 1455 break; 1456 case AArch64::STRQui: 1457 NewOpc = AArch64::STRQpre; 1458 break; 1459 case AArch64::LDPXi: 1460 NewOpc = AArch64::LDPXpost; 1461 break; 1462 case AArch64::LDPDi: 1463 NewOpc = AArch64::LDPDpost; 1464 break; 1465 case AArch64::LDPQi: 1466 NewOpc = AArch64::LDPQpost; 1467 break; 1468 case AArch64::LDRXui: 1469 NewOpc = AArch64::LDRXpost; 1470 break; 1471 case AArch64::LDRDui: 1472 NewOpc = AArch64::LDRDpost; 1473 break; 1474 case AArch64::LDRQui: 1475 NewOpc = AArch64::LDRQpost; 1476 break; 1477 } 1478 // Get rid of the SEH code associated with the old instruction. 1479 if (NeedsWinCFI) { 1480 auto SEH = std::next(MBBI); 1481 if (AArch64InstrInfo::isSEHInstruction(*SEH)) 1482 SEH->eraseFromParent(); 1483 } 1484 1485 TypeSize Scale = TypeSize::getFixed(1), Width = TypeSize::getFixed(0); 1486 int64_t MinOffset, MaxOffset; 1487 bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo( 1488 NewOpc, Scale, Width, MinOffset, MaxOffset); 1489 (void)Success; 1490 assert(Success && "unknown load/store opcode"); 1491 1492 // If the first store isn't right where we want SP then we can't fold the 1493 // update in so create a normal arithmetic instruction instead. 1494 if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 || 1495 CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) { 1496 // If we are destroying the frame, make sure we add the increment after the 1497 // last frame operation. 1498 if (FrameFlag == MachineInstr::FrameDestroy) 1499 ++MBBI; 1500 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, 1501 StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag, 1502 false, false, nullptr, EmitCFI, 1503 StackOffset::getFixed(CFAOffset)); 1504 1505 return std::prev(MBBI); 1506 } 1507 1508 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc)); 1509 MIB.addReg(AArch64::SP, RegState::Define); 1510 1511 // Copy all operands other than the immediate offset. 1512 unsigned OpndIdx = 0; 1513 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd; 1514 ++OpndIdx) 1515 MIB.add(MBBI->getOperand(OpndIdx)); 1516 1517 assert(MBBI->getOperand(OpndIdx).getImm() == 0 && 1518 "Unexpected immediate offset in first/last callee-save save/restore " 1519 "instruction!"); 1520 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP && 1521 "Unexpected base register in callee-save save/restore instruction!"); 1522 assert(CSStackSizeInc % Scale == 0); 1523 MIB.addImm(CSStackSizeInc / (int)Scale); 1524 1525 MIB.setMIFlags(MBBI->getFlags()); 1526 MIB.setMemRefs(MBBI->memoperands()); 1527 1528 // Generate a new SEH code that corresponds to the new instruction. 1529 if (NeedsWinCFI) { 1530 *HasWinCFI = true; 1531 InsertSEH(*MIB, *TII, FrameFlag); 1532 } 1533 1534 if (EmitCFI) { 1535 unsigned CFIIndex = MF.addFrameInst( 1536 MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc)); 1537 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 1538 .addCFIIndex(CFIIndex) 1539 .setMIFlags(FrameFlag); 1540 } 1541 1542 return std::prev(MBB.erase(MBBI)); 1543 } 1544 1545 // Fixup callee-save register save/restore instructions to take into account 1546 // combined SP bump by adding the local stack size to the stack offsets. 1547 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI, 1548 uint64_t LocalStackSize, 1549 bool NeedsWinCFI, 1550 bool *HasWinCFI) { 1551 if (AArch64InstrInfo::isSEHInstruction(MI)) 1552 return; 1553 1554 unsigned Opc = MI.getOpcode(); 1555 unsigned Scale; 1556 switch (Opc) { 1557 case AArch64::STPXi: 1558 case AArch64::STRXui: 1559 case AArch64::STPDi: 1560 case AArch64::STRDui: 1561 case AArch64::LDPXi: 1562 case AArch64::LDRXui: 1563 case AArch64::LDPDi: 1564 case AArch64::LDRDui: 1565 Scale = 8; 1566 break; 1567 case AArch64::STPQi: 1568 case AArch64::STRQui: 1569 case AArch64::LDPQi: 1570 case AArch64::LDRQui: 1571 Scale = 16; 1572 break; 1573 default: 1574 llvm_unreachable("Unexpected callee-save save/restore opcode!"); 1575 } 1576 1577 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1; 1578 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP && 1579 "Unexpected base register in callee-save save/restore instruction!"); 1580 // Last operand is immediate offset that needs fixing. 1581 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx); 1582 // All generated opcodes have scaled offsets. 1583 assert(LocalStackSize % Scale == 0); 1584 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale); 1585 1586 if (NeedsWinCFI) { 1587 *HasWinCFI = true; 1588 auto MBBI = std::next(MachineBasicBlock::iterator(MI)); 1589 assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction"); 1590 assert(AArch64InstrInfo::isSEHInstruction(*MBBI) && 1591 "Expecting a SEH instruction"); 1592 fixupSEHOpcode(MBBI, LocalStackSize); 1593 } 1594 } 1595 1596 static bool isTargetWindows(const MachineFunction &MF) { 1597 return MF.getSubtarget<AArch64Subtarget>().isTargetWindows(); 1598 } 1599 1600 // Convenience function to determine whether I is an SVE callee save. 1601 static bool IsSVECalleeSave(MachineBasicBlock::iterator I) { 1602 switch (I->getOpcode()) { 1603 default: 1604 return false; 1605 case AArch64::PTRUE_C_B: 1606 case AArch64::LD1B_2Z_IMM: 1607 case AArch64::ST1B_2Z_IMM: 1608 case AArch64::STR_ZXI: 1609 case AArch64::STR_PXI: 1610 case AArch64::LDR_ZXI: 1611 case AArch64::LDR_PXI: 1612 return I->getFlag(MachineInstr::FrameSetup) || 1613 I->getFlag(MachineInstr::FrameDestroy); 1614 } 1615 } 1616 1617 static void emitShadowCallStackPrologue(const TargetInstrInfo &TII, 1618 MachineFunction &MF, 1619 MachineBasicBlock &MBB, 1620 MachineBasicBlock::iterator MBBI, 1621 const DebugLoc &DL, bool NeedsWinCFI, 1622 bool NeedsUnwindInfo) { 1623 // Shadow call stack prolog: str x30, [x18], #8 1624 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost)) 1625 .addReg(AArch64::X18, RegState::Define) 1626 .addReg(AArch64::LR) 1627 .addReg(AArch64::X18) 1628 .addImm(8) 1629 .setMIFlag(MachineInstr::FrameSetup); 1630 1631 // This instruction also makes x18 live-in to the entry block. 1632 MBB.addLiveIn(AArch64::X18); 1633 1634 if (NeedsWinCFI) 1635 BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop)) 1636 .setMIFlag(MachineInstr::FrameSetup); 1637 1638 if (NeedsUnwindInfo) { 1639 // Emit a CFI instruction that causes 8 to be subtracted from the value of 1640 // x18 when unwinding past this frame. 1641 static const char CFIInst[] = { 1642 dwarf::DW_CFA_val_expression, 1643 18, // register 1644 2, // length 1645 static_cast<char>(unsigned(dwarf::DW_OP_breg18)), 1646 static_cast<char>(-8) & 0x7f, // addend (sleb128) 1647 }; 1648 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape( 1649 nullptr, StringRef(CFIInst, sizeof(CFIInst)))); 1650 BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION)) 1651 .addCFIIndex(CFIIndex) 1652 .setMIFlag(MachineInstr::FrameSetup); 1653 } 1654 } 1655 1656 static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII, 1657 MachineFunction &MF, 1658 MachineBasicBlock &MBB, 1659 MachineBasicBlock::iterator MBBI, 1660 const DebugLoc &DL) { 1661 // Shadow call stack epilog: ldr x30, [x18, #-8]! 1662 BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre)) 1663 .addReg(AArch64::X18, RegState::Define) 1664 .addReg(AArch64::LR, RegState::Define) 1665 .addReg(AArch64::X18) 1666 .addImm(-8) 1667 .setMIFlag(MachineInstr::FrameDestroy); 1668 1669 if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF)) { 1670 unsigned CFIIndex = 1671 MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18)); 1672 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1673 .addCFIIndex(CFIIndex) 1674 .setMIFlags(MachineInstr::FrameDestroy); 1675 } 1676 } 1677 1678 // Define the current CFA rule to use the provided FP. 1679 static void emitDefineCFAWithFP(MachineFunction &MF, MachineBasicBlock &MBB, 1680 MachineBasicBlock::iterator MBBI, 1681 const DebugLoc &DL, unsigned FixedObject) { 1682 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>(); 1683 const AArch64RegisterInfo *TRI = STI.getRegisterInfo(); 1684 const TargetInstrInfo *TII = STI.getInstrInfo(); 1685 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1686 1687 const int OffsetToFirstCalleeSaveFromFP = 1688 AFI->getCalleeSaveBaseToFrameRecordOffset() - 1689 AFI->getCalleeSavedStackSize(); 1690 Register FramePtr = TRI->getFrameRegister(MF); 1691 unsigned Reg = TRI->getDwarfRegNum(FramePtr, true); 1692 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa( 1693 nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP)); 1694 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 1695 .addCFIIndex(CFIIndex) 1696 .setMIFlags(MachineInstr::FrameSetup); 1697 } 1698 1699 #ifndef NDEBUG 1700 /// Collect live registers from the end of \p MI's parent up to (including) \p 1701 /// MI in \p LiveRegs. 1702 static void getLivePhysRegsUpTo(MachineInstr &MI, const TargetRegisterInfo &TRI, 1703 LivePhysRegs &LiveRegs) { 1704 1705 MachineBasicBlock &MBB = *MI.getParent(); 1706 LiveRegs.addLiveOuts(MBB); 1707 for (const MachineInstr &MI : 1708 reverse(make_range(MI.getIterator(), MBB.instr_end()))) 1709 LiveRegs.stepBackward(MI); 1710 } 1711 #endif 1712 1713 void AArch64FrameLowering::emitPrologue(MachineFunction &MF, 1714 MachineBasicBlock &MBB) const { 1715 MachineBasicBlock::iterator MBBI = MBB.begin(); 1716 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1717 const Function &F = MF.getFunction(); 1718 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1719 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 1720 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1721 1722 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1723 bool EmitCFI = AFI->needsDwarfUnwindInfo(MF); 1724 bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF); 1725 bool HasFP = hasFP(MF); 1726 bool NeedsWinCFI = needsWinCFI(MF); 1727 bool HasWinCFI = false; 1728 auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); }); 1729 1730 MachineBasicBlock::iterator End = MBB.end(); 1731 #ifndef NDEBUG 1732 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1733 // Collect live register from the end of MBB up to the start of the existing 1734 // frame setup instructions. 1735 MachineBasicBlock::iterator NonFrameStart = MBB.begin(); 1736 while (NonFrameStart != End && 1737 NonFrameStart->getFlag(MachineInstr::FrameSetup)) 1738 ++NonFrameStart; 1739 1740 LivePhysRegs LiveRegs(*TRI); 1741 if (NonFrameStart != MBB.end()) { 1742 getLivePhysRegsUpTo(*NonFrameStart, *TRI, LiveRegs); 1743 // Ignore registers used for stack management for now. 1744 LiveRegs.removeReg(AArch64::SP); 1745 LiveRegs.removeReg(AArch64::X19); 1746 LiveRegs.removeReg(AArch64::FP); 1747 LiveRegs.removeReg(AArch64::LR); 1748 1749 // X0 will be clobbered by a call to __arm_get_current_vg in the prologue. 1750 // This is necessary to spill VG if required where SVE is unavailable, but 1751 // X0 is preserved around this call. 1752 if (requiresGetVGCall(MF)) 1753 LiveRegs.removeReg(AArch64::X0); 1754 } 1755 1756 auto VerifyClobberOnExit = make_scope_exit([&]() { 1757 if (NonFrameStart == MBB.end()) 1758 return; 1759 // Check if any of the newly instructions clobber any of the live registers. 1760 for (MachineInstr &MI : 1761 make_range(MBB.instr_begin(), NonFrameStart->getIterator())) { 1762 for (auto &Op : MI.operands()) 1763 if (Op.isReg() && Op.isDef()) 1764 assert(!LiveRegs.contains(Op.getReg()) && 1765 "live register clobbered by inserted prologue instructions"); 1766 } 1767 }); 1768 #endif 1769 1770 bool IsFunclet = MBB.isEHFuncletEntry(); 1771 1772 // At this point, we're going to decide whether or not the function uses a 1773 // redzone. In most cases, the function doesn't have a redzone so let's 1774 // assume that's false and set it to true in the case that there's a redzone. 1775 AFI->setHasRedZone(false); 1776 1777 // Debug location must be unknown since the first debug location is used 1778 // to determine the end of the prologue. 1779 DebugLoc DL; 1780 1781 const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>(); 1782 if (MFnI.needsShadowCallStackPrologueEpilogue(MF)) 1783 emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI, 1784 MFnI.needsDwarfUnwindInfo(MF)); 1785 1786 if (MFnI.shouldSignReturnAddress(MF)) { 1787 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PAUTH_PROLOGUE)) 1788 .setMIFlag(MachineInstr::FrameSetup); 1789 if (NeedsWinCFI) 1790 HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR 1791 } 1792 1793 if (EmitCFI && MFnI.isMTETagged()) { 1794 BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITMTETAGGED)) 1795 .setMIFlag(MachineInstr::FrameSetup); 1796 } 1797 1798 // We signal the presence of a Swift extended frame to external tools by 1799 // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple 1800 // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI 1801 // bits so that is still true. 1802 if (HasFP && AFI->hasSwiftAsyncContext()) { 1803 switch (MF.getTarget().Options.SwiftAsyncFramePointer) { 1804 case SwiftAsyncFramePointerMode::DeploymentBased: 1805 if (Subtarget.swiftAsyncContextIsDynamicallySet()) { 1806 // The special symbol below is absolute and has a *value* that can be 1807 // combined with the frame pointer to signal an extended frame. 1808 BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16) 1809 .addExternalSymbol("swift_async_extendedFramePointerFlags", 1810 AArch64II::MO_GOT); 1811 if (NeedsWinCFI) { 1812 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1813 .setMIFlags(MachineInstr::FrameSetup); 1814 HasWinCFI = true; 1815 } 1816 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP) 1817 .addUse(AArch64::FP) 1818 .addUse(AArch64::X16) 1819 .addImm(Subtarget.isTargetILP32() ? 32 : 0); 1820 if (NeedsWinCFI) { 1821 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1822 .setMIFlags(MachineInstr::FrameSetup); 1823 HasWinCFI = true; 1824 } 1825 break; 1826 } 1827 [[fallthrough]]; 1828 1829 case SwiftAsyncFramePointerMode::Always: 1830 // ORR x29, x29, #0x1000_0000_0000_0000 1831 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP) 1832 .addUse(AArch64::FP) 1833 .addImm(0x1100) 1834 .setMIFlag(MachineInstr::FrameSetup); 1835 if (NeedsWinCFI) { 1836 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1837 .setMIFlags(MachineInstr::FrameSetup); 1838 HasWinCFI = true; 1839 } 1840 break; 1841 1842 case SwiftAsyncFramePointerMode::Never: 1843 break; 1844 } 1845 } 1846 1847 // All calls are tail calls in GHC calling conv, and functions have no 1848 // prologue/epilogue. 1849 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 1850 return; 1851 1852 // Set tagged base pointer to the requested stack slot. 1853 // Ideally it should match SP value after prologue. 1854 std::optional<int> TBPI = AFI->getTaggedBasePointerIndex(); 1855 if (TBPI) 1856 AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI)); 1857 else 1858 AFI->setTaggedBasePointerOffset(MFI.getStackSize()); 1859 1860 const StackOffset &SVEStackSize = getSVEStackSize(MF); 1861 1862 // getStackSize() includes all the locals in its size calculation. We don't 1863 // include these locals when computing the stack size of a funclet, as they 1864 // are allocated in the parent's stack frame and accessed via the frame 1865 // pointer from the funclet. We only save the callee saved registers in the 1866 // funclet, which are really the callee saved registers of the parent 1867 // function, including the funclet. 1868 int64_t NumBytes = 1869 IsFunclet ? getWinEHFuncletFrameSize(MF) : MFI.getStackSize(); 1870 if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) { 1871 assert(!HasFP && "unexpected function without stack frame but with FP"); 1872 assert(!SVEStackSize && 1873 "unexpected function without stack frame but with SVE objects"); 1874 // All of the stack allocation is for locals. 1875 AFI->setLocalStackSize(NumBytes); 1876 if (!NumBytes) 1877 return; 1878 // REDZONE: If the stack size is less than 128 bytes, we don't need 1879 // to actually allocate. 1880 if (canUseRedZone(MF)) { 1881 AFI->setHasRedZone(true); 1882 ++NumRedZoneFunctions; 1883 } else { 1884 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, 1885 StackOffset::getFixed(-NumBytes), TII, 1886 MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI); 1887 if (EmitCFI) { 1888 // Label used to tie together the PROLOG_LABEL and the MachineMoves. 1889 MCSymbol *FrameLabel = MF.getContext().createTempSymbol(); 1890 // Encode the stack size of the leaf function. 1891 unsigned CFIIndex = MF.addFrameInst( 1892 MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes)); 1893 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 1894 .addCFIIndex(CFIIndex) 1895 .setMIFlags(MachineInstr::FrameSetup); 1896 } 1897 } 1898 1899 if (NeedsWinCFI) { 1900 HasWinCFI = true; 1901 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 1902 .setMIFlag(MachineInstr::FrameSetup); 1903 } 1904 1905 return; 1906 } 1907 1908 bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg()); 1909 unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet); 1910 1911 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject; 1912 // All of the remaining stack allocations are for locals. 1913 AFI->setLocalStackSize(NumBytes - PrologueSaveSize); 1914 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes); 1915 bool HomPrologEpilog = homogeneousPrologEpilog(MF); 1916 if (CombineSPBump) { 1917 assert(!SVEStackSize && "Cannot combine SP bump with SVE"); 1918 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, 1919 StackOffset::getFixed(-NumBytes), TII, 1920 MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI, 1921 EmitAsyncCFI); 1922 NumBytes = 0; 1923 } else if (HomPrologEpilog) { 1924 // Stack has been already adjusted. 1925 NumBytes -= PrologueSaveSize; 1926 } else if (PrologueSaveSize != 0) { 1927 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec( 1928 MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI, 1929 EmitAsyncCFI); 1930 NumBytes -= PrologueSaveSize; 1931 } 1932 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 1933 1934 // Move past the saves of the callee-saved registers, fixing up the offsets 1935 // and pre-inc if we decided to combine the callee-save and local stack 1936 // pointer bump above. 1937 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) && 1938 !IsSVECalleeSave(MBBI)) { 1939 // Move past instructions generated to calculate VG 1940 if (AFI->hasStreamingModeChanges()) 1941 while (isVGInstruction(MBBI)) 1942 ++MBBI; 1943 1944 if (CombineSPBump) 1945 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(), 1946 NeedsWinCFI, &HasWinCFI); 1947 ++MBBI; 1948 } 1949 1950 // For funclets the FP belongs to the containing function. 1951 if (!IsFunclet && HasFP) { 1952 // Only set up FP if we actually need to. 1953 int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset(); 1954 1955 if (CombineSPBump) 1956 FPOffset += AFI->getLocalStackSize(); 1957 1958 if (AFI->hasSwiftAsyncContext()) { 1959 // Before we update the live FP we have to ensure there's a valid (or 1960 // null) asynchronous context in its slot just before FP in the frame 1961 // record, so store it now. 1962 const auto &Attrs = MF.getFunction().getAttributes(); 1963 bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync); 1964 if (HaveInitialContext) 1965 MBB.addLiveIn(AArch64::X22); 1966 Register Reg = HaveInitialContext ? AArch64::X22 : AArch64::XZR; 1967 BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext)) 1968 .addUse(Reg) 1969 .addUse(AArch64::SP) 1970 .addImm(FPOffset - 8) 1971 .setMIFlags(MachineInstr::FrameSetup); 1972 if (NeedsWinCFI) { 1973 // WinCFI and arm64e, where StoreSwiftAsyncContext is expanded 1974 // to multiple instructions, should be mutually-exclusive. 1975 assert(Subtarget.getTargetTriple().getArchName() != "arm64e"); 1976 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1977 .setMIFlags(MachineInstr::FrameSetup); 1978 HasWinCFI = true; 1979 } 1980 } 1981 1982 if (HomPrologEpilog) { 1983 auto Prolog = MBBI; 1984 --Prolog; 1985 assert(Prolog->getOpcode() == AArch64::HOM_Prolog); 1986 Prolog->addOperand(MachineOperand::CreateImm(FPOffset)); 1987 } else { 1988 // Issue sub fp, sp, FPOffset or 1989 // mov fp,sp when FPOffset is zero. 1990 // Note: All stores of callee-saved registers are marked as "FrameSetup". 1991 // This code marks the instruction(s) that set the FP also. 1992 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, 1993 StackOffset::getFixed(FPOffset), TII, 1994 MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI); 1995 if (NeedsWinCFI && HasWinCFI) { 1996 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 1997 .setMIFlag(MachineInstr::FrameSetup); 1998 // After setting up the FP, the rest of the prolog doesn't need to be 1999 // included in the SEH unwind info. 2000 NeedsWinCFI = false; 2001 } 2002 } 2003 if (EmitAsyncCFI) 2004 emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject); 2005 } 2006 2007 // Now emit the moves for whatever callee saved regs we have (including FP, 2008 // LR if those are saved). Frame instructions for SVE register are emitted 2009 // later, after the instruction which actually save SVE regs. 2010 if (EmitAsyncCFI) 2011 emitCalleeSavedGPRLocations(MBB, MBBI); 2012 2013 // Alignment is required for the parent frame, not the funclet 2014 const bool NeedsRealignment = 2015 NumBytes && !IsFunclet && RegInfo->hasStackRealignment(MF); 2016 const int64_t RealignmentPadding = 2017 (NeedsRealignment && MFI.getMaxAlign() > Align(16)) 2018 ? MFI.getMaxAlign().value() - 16 2019 : 0; 2020 2021 if (windowsRequiresStackProbe(MF, NumBytes + RealignmentPadding)) { 2022 uint64_t NumWords = (NumBytes + RealignmentPadding) >> 4; 2023 if (NeedsWinCFI) { 2024 HasWinCFI = true; 2025 // alloc_l can hold at most 256MB, so assume that NumBytes doesn't 2026 // exceed this amount. We need to move at most 2^24 - 1 into x15. 2027 // This is at most two instructions, MOVZ follwed by MOVK. 2028 // TODO: Fix to use multiple stack alloc unwind codes for stacks 2029 // exceeding 256MB in size. 2030 if (NumBytes >= (1 << 28)) 2031 report_fatal_error("Stack size cannot exceed 256MB for stack " 2032 "unwinding purposes"); 2033 2034 uint32_t LowNumWords = NumWords & 0xFFFF; 2035 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15) 2036 .addImm(LowNumWords) 2037 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)) 2038 .setMIFlag(MachineInstr::FrameSetup); 2039 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2040 .setMIFlag(MachineInstr::FrameSetup); 2041 if ((NumWords & 0xFFFF0000) != 0) { 2042 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15) 2043 .addReg(AArch64::X15) 2044 .addImm((NumWords & 0xFFFF0000) >> 16) // High half 2045 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16)) 2046 .setMIFlag(MachineInstr::FrameSetup); 2047 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2048 .setMIFlag(MachineInstr::FrameSetup); 2049 } 2050 } else { 2051 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15) 2052 .addImm(NumWords) 2053 .setMIFlags(MachineInstr::FrameSetup); 2054 } 2055 2056 const char *ChkStk = Subtarget.getChkStkName(); 2057 switch (MF.getTarget().getCodeModel()) { 2058 case CodeModel::Tiny: 2059 case CodeModel::Small: 2060 case CodeModel::Medium: 2061 case CodeModel::Kernel: 2062 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL)) 2063 .addExternalSymbol(ChkStk) 2064 .addReg(AArch64::X15, RegState::Implicit) 2065 .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead) 2066 .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead) 2067 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead) 2068 .setMIFlags(MachineInstr::FrameSetup); 2069 if (NeedsWinCFI) { 2070 HasWinCFI = true; 2071 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2072 .setMIFlag(MachineInstr::FrameSetup); 2073 } 2074 break; 2075 case CodeModel::Large: 2076 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT)) 2077 .addReg(AArch64::X16, RegState::Define) 2078 .addExternalSymbol(ChkStk) 2079 .addExternalSymbol(ChkStk) 2080 .setMIFlags(MachineInstr::FrameSetup); 2081 if (NeedsWinCFI) { 2082 HasWinCFI = true; 2083 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2084 .setMIFlag(MachineInstr::FrameSetup); 2085 } 2086 2087 BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF))) 2088 .addReg(AArch64::X16, RegState::Kill) 2089 .addReg(AArch64::X15, RegState::Implicit | RegState::Define) 2090 .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead) 2091 .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead) 2092 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead) 2093 .setMIFlags(MachineInstr::FrameSetup); 2094 if (NeedsWinCFI) { 2095 HasWinCFI = true; 2096 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2097 .setMIFlag(MachineInstr::FrameSetup); 2098 } 2099 break; 2100 } 2101 2102 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP) 2103 .addReg(AArch64::SP, RegState::Kill) 2104 .addReg(AArch64::X15, RegState::Kill) 2105 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4)) 2106 .setMIFlags(MachineInstr::FrameSetup); 2107 if (NeedsWinCFI) { 2108 HasWinCFI = true; 2109 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc)) 2110 .addImm(NumBytes) 2111 .setMIFlag(MachineInstr::FrameSetup); 2112 } 2113 NumBytes = 0; 2114 2115 if (RealignmentPadding > 0) { 2116 if (RealignmentPadding >= 4096) { 2117 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm)) 2118 .addReg(AArch64::X16, RegState::Define) 2119 .addImm(RealignmentPadding) 2120 .setMIFlags(MachineInstr::FrameSetup); 2121 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXrx64), AArch64::X15) 2122 .addReg(AArch64::SP) 2123 .addReg(AArch64::X16, RegState::Kill) 2124 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0)) 2125 .setMIFlag(MachineInstr::FrameSetup); 2126 } else { 2127 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXri), AArch64::X15) 2128 .addReg(AArch64::SP) 2129 .addImm(RealignmentPadding) 2130 .addImm(0) 2131 .setMIFlag(MachineInstr::FrameSetup); 2132 } 2133 2134 uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1); 2135 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP) 2136 .addReg(AArch64::X15, RegState::Kill) 2137 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64)); 2138 AFI->setStackRealigned(true); 2139 2140 // No need for SEH instructions here; if we're realigning the stack, 2141 // we've set a frame pointer and already finished the SEH prologue. 2142 assert(!NeedsWinCFI); 2143 } 2144 } 2145 2146 StackOffset SVECalleeSavesSize = {}, SVELocalsSize = SVEStackSize; 2147 MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI; 2148 2149 // Process the SVE callee-saves to determine what space needs to be 2150 // allocated. 2151 if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) { 2152 LLVM_DEBUG(dbgs() << "SVECalleeSavedStackSize = " << CalleeSavedSize 2153 << "\n"); 2154 // Find callee save instructions in frame. 2155 CalleeSavesBegin = MBBI; 2156 assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction"); 2157 while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator()) 2158 ++MBBI; 2159 CalleeSavesEnd = MBBI; 2160 2161 SVECalleeSavesSize = StackOffset::getScalable(CalleeSavedSize); 2162 SVELocalsSize = SVEStackSize - SVECalleeSavesSize; 2163 } 2164 2165 // Allocate space for the callee saves (if any). 2166 StackOffset CFAOffset = 2167 StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes); 2168 StackOffset LocalsSize = SVELocalsSize + StackOffset::getFixed(NumBytes); 2169 allocateStackSpace(MBB, CalleeSavesBegin, 0, SVECalleeSavesSize, false, 2170 nullptr, EmitAsyncCFI && !HasFP, CFAOffset, 2171 MFI.hasVarSizedObjects() || LocalsSize); 2172 CFAOffset += SVECalleeSavesSize; 2173 2174 if (EmitAsyncCFI) 2175 emitCalleeSavedSVELocations(MBB, CalleeSavesEnd); 2176 2177 // Allocate space for the rest of the frame including SVE locals. Align the 2178 // stack as necessary. 2179 assert(!(canUseRedZone(MF) && NeedsRealignment) && 2180 "Cannot use redzone with stack realignment"); 2181 if (!canUseRedZone(MF)) { 2182 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have 2183 // the correct value here, as NumBytes also includes padding bytes, 2184 // which shouldn't be counted here. 2185 allocateStackSpace(MBB, CalleeSavesEnd, RealignmentPadding, 2186 SVELocalsSize + StackOffset::getFixed(NumBytes), 2187 NeedsWinCFI, &HasWinCFI, EmitAsyncCFI && !HasFP, 2188 CFAOffset, MFI.hasVarSizedObjects()); 2189 } 2190 2191 // If we need a base pointer, set it up here. It's whatever the value of the 2192 // stack pointer is at this point. Any variable size objects will be allocated 2193 // after this, so we can still use the base pointer to reference locals. 2194 // 2195 // FIXME: Clarify FrameSetup flags here. 2196 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is 2197 // needed. 2198 // For funclets the BP belongs to the containing function. 2199 if (!IsFunclet && RegInfo->hasBasePointer(MF)) { 2200 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP, 2201 false); 2202 if (NeedsWinCFI) { 2203 HasWinCFI = true; 2204 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2205 .setMIFlag(MachineInstr::FrameSetup); 2206 } 2207 } 2208 2209 // The very last FrameSetup instruction indicates the end of prologue. Emit a 2210 // SEH opcode indicating the prologue end. 2211 if (NeedsWinCFI && HasWinCFI) { 2212 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 2213 .setMIFlag(MachineInstr::FrameSetup); 2214 } 2215 2216 // SEH funclets are passed the frame pointer in X1. If the parent 2217 // function uses the base register, then the base register is used 2218 // directly, and is not retrieved from X1. 2219 if (IsFunclet && F.hasPersonalityFn()) { 2220 EHPersonality Per = classifyEHPersonality(F.getPersonalityFn()); 2221 if (isAsynchronousEHPersonality(Per)) { 2222 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP) 2223 .addReg(AArch64::X1) 2224 .setMIFlag(MachineInstr::FrameSetup); 2225 MBB.addLiveIn(AArch64::X1); 2226 } 2227 } 2228 2229 if (EmitCFI && !EmitAsyncCFI) { 2230 if (HasFP) { 2231 emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject); 2232 } else { 2233 StackOffset TotalSize = 2234 SVEStackSize + StackOffset::getFixed((int64_t)MFI.getStackSize()); 2235 unsigned CFIIndex = MF.addFrameInst(createDefCFA( 2236 *RegInfo, /*FrameReg=*/AArch64::SP, /*Reg=*/AArch64::SP, TotalSize, 2237 /*LastAdjustmentWasScalable=*/false)); 2238 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 2239 .addCFIIndex(CFIIndex) 2240 .setMIFlags(MachineInstr::FrameSetup); 2241 } 2242 emitCalleeSavedGPRLocations(MBB, MBBI); 2243 emitCalleeSavedSVELocations(MBB, MBBI); 2244 } 2245 } 2246 2247 static bool isFuncletReturnInstr(const MachineInstr &MI) { 2248 switch (MI.getOpcode()) { 2249 default: 2250 return false; 2251 case AArch64::CATCHRET: 2252 case AArch64::CLEANUPRET: 2253 return true; 2254 } 2255 } 2256 2257 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF, 2258 MachineBasicBlock &MBB) const { 2259 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 2260 MachineFrameInfo &MFI = MF.getFrameInfo(); 2261 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 2262 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 2263 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 2264 DebugLoc DL; 2265 bool NeedsWinCFI = needsWinCFI(MF); 2266 bool EmitCFI = AFI->needsAsyncDwarfUnwindInfo(MF); 2267 bool HasWinCFI = false; 2268 bool IsFunclet = false; 2269 2270 if (MBB.end() != MBBI) { 2271 DL = MBBI->getDebugLoc(); 2272 IsFunclet = isFuncletReturnInstr(*MBBI); 2273 } 2274 2275 MachineBasicBlock::iterator EpilogStartI = MBB.end(); 2276 2277 auto FinishingTouches = make_scope_exit([&]() { 2278 if (AFI->shouldSignReturnAddress(MF)) { 2279 BuildMI(MBB, MBB.getFirstTerminator(), DL, 2280 TII->get(AArch64::PAUTH_EPILOGUE)) 2281 .setMIFlag(MachineInstr::FrameDestroy); 2282 if (NeedsWinCFI) 2283 HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR 2284 } 2285 if (AFI->needsShadowCallStackPrologueEpilogue(MF)) 2286 emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL); 2287 if (EmitCFI) 2288 emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator()); 2289 if (HasWinCFI) { 2290 BuildMI(MBB, MBB.getFirstTerminator(), DL, 2291 TII->get(AArch64::SEH_EpilogEnd)) 2292 .setMIFlag(MachineInstr::FrameDestroy); 2293 if (!MF.hasWinCFI()) 2294 MF.setHasWinCFI(true); 2295 } 2296 if (NeedsWinCFI) { 2297 assert(EpilogStartI != MBB.end()); 2298 if (!HasWinCFI) 2299 MBB.erase(EpilogStartI); 2300 } 2301 }); 2302 2303 int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF) 2304 : MFI.getStackSize(); 2305 2306 // All calls are tail calls in GHC calling conv, and functions have no 2307 // prologue/epilogue. 2308 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 2309 return; 2310 2311 // How much of the stack used by incoming arguments this function is expected 2312 // to restore in this particular epilogue. 2313 int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB); 2314 bool IsWin64 = Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(), 2315 MF.getFunction().isVarArg()); 2316 unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet); 2317 2318 int64_t AfterCSRPopSize = ArgumentStackToRestore; 2319 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject; 2320 // We cannot rely on the local stack size set in emitPrologue if the function 2321 // has funclets, as funclets have different local stack size requirements, and 2322 // the current value set in emitPrologue may be that of the containing 2323 // function. 2324 if (MF.hasEHFunclets()) 2325 AFI->setLocalStackSize(NumBytes - PrologueSaveSize); 2326 if (homogeneousPrologEpilog(MF, &MBB)) { 2327 assert(!NeedsWinCFI); 2328 auto LastPopI = MBB.getFirstTerminator(); 2329 if (LastPopI != MBB.begin()) { 2330 auto HomogeneousEpilog = std::prev(LastPopI); 2331 if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog) 2332 LastPopI = HomogeneousEpilog; 2333 } 2334 2335 // Adjust local stack 2336 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, 2337 StackOffset::getFixed(AFI->getLocalStackSize()), TII, 2338 MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI); 2339 2340 // SP has been already adjusted while restoring callee save regs. 2341 // We've bailed-out the case with adjusting SP for arguments. 2342 assert(AfterCSRPopSize == 0); 2343 return; 2344 } 2345 bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes); 2346 // Assume we can't combine the last pop with the sp restore. 2347 2348 bool CombineAfterCSRBump = false; 2349 if (!CombineSPBump && PrologueSaveSize != 0) { 2350 MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator()); 2351 while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION || 2352 AArch64InstrInfo::isSEHInstruction(*Pop)) 2353 Pop = std::prev(Pop); 2354 // Converting the last ldp to a post-index ldp is valid only if the last 2355 // ldp's offset is 0. 2356 const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1); 2357 // If the offset is 0 and the AfterCSR pop is not actually trying to 2358 // allocate more stack for arguments (in space that an untimely interrupt 2359 // may clobber), convert it to a post-index ldp. 2360 if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) { 2361 convertCalleeSaveRestoreToSPPrePostIncDec( 2362 MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI, 2363 MachineInstr::FrameDestroy, PrologueSaveSize); 2364 } else { 2365 // If not, make sure to emit an add after the last ldp. 2366 // We're doing this by transfering the size to be restored from the 2367 // adjustment *before* the CSR pops to the adjustment *after* the CSR 2368 // pops. 2369 AfterCSRPopSize += PrologueSaveSize; 2370 CombineAfterCSRBump = true; 2371 } 2372 } 2373 2374 // Move past the restores of the callee-saved registers. 2375 // If we plan on combining the sp bump of the local stack size and the callee 2376 // save stack size, we might need to adjust the CSR save and restore offsets. 2377 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator(); 2378 MachineBasicBlock::iterator Begin = MBB.begin(); 2379 while (LastPopI != Begin) { 2380 --LastPopI; 2381 if (!LastPopI->getFlag(MachineInstr::FrameDestroy) || 2382 IsSVECalleeSave(LastPopI)) { 2383 ++LastPopI; 2384 break; 2385 } else if (CombineSPBump) 2386 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(), 2387 NeedsWinCFI, &HasWinCFI); 2388 } 2389 2390 if (NeedsWinCFI) { 2391 // Note that there are cases where we insert SEH opcodes in the 2392 // epilogue when we had no SEH opcodes in the prologue. For 2393 // example, when there is no stack frame but there are stack 2394 // arguments. Insert the SEH_EpilogStart and remove it later if it 2395 // we didn't emit any SEH opcodes to avoid generating WinCFI for 2396 // functions that don't need it. 2397 BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart)) 2398 .setMIFlag(MachineInstr::FrameDestroy); 2399 EpilogStartI = LastPopI; 2400 --EpilogStartI; 2401 } 2402 2403 if (hasFP(MF) && AFI->hasSwiftAsyncContext()) { 2404 switch (MF.getTarget().Options.SwiftAsyncFramePointer) { 2405 case SwiftAsyncFramePointerMode::DeploymentBased: 2406 // Avoid the reload as it is GOT relative, and instead fall back to the 2407 // hardcoded value below. This allows a mismatch between the OS and 2408 // application without immediately terminating on the difference. 2409 [[fallthrough]]; 2410 case SwiftAsyncFramePointerMode::Always: 2411 // We need to reset FP to its untagged state on return. Bit 60 is 2412 // currently used to show the presence of an extended frame. 2413 2414 // BIC x29, x29, #0x1000_0000_0000_0000 2415 BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri), 2416 AArch64::FP) 2417 .addUse(AArch64::FP) 2418 .addImm(0x10fe) 2419 .setMIFlag(MachineInstr::FrameDestroy); 2420 if (NeedsWinCFI) { 2421 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 2422 .setMIFlags(MachineInstr::FrameDestroy); 2423 HasWinCFI = true; 2424 } 2425 break; 2426 2427 case SwiftAsyncFramePointerMode::Never: 2428 break; 2429 } 2430 } 2431 2432 const StackOffset &SVEStackSize = getSVEStackSize(MF); 2433 2434 // If there is a single SP update, insert it before the ret and we're done. 2435 if (CombineSPBump) { 2436 assert(!SVEStackSize && "Cannot combine SP bump with SVE"); 2437 2438 // When we are about to restore the CSRs, the CFA register is SP again. 2439 if (EmitCFI && hasFP(MF)) { 2440 const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo(); 2441 unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true); 2442 unsigned CFIIndex = 2443 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes)); 2444 BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 2445 .addCFIIndex(CFIIndex) 2446 .setMIFlags(MachineInstr::FrameDestroy); 2447 } 2448 2449 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP, 2450 StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize), 2451 TII, MachineInstr::FrameDestroy, false, NeedsWinCFI, 2452 &HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes)); 2453 return; 2454 } 2455 2456 NumBytes -= PrologueSaveSize; 2457 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 2458 2459 // Process the SVE callee-saves to determine what space needs to be 2460 // deallocated. 2461 StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize; 2462 MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI; 2463 if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) { 2464 RestoreBegin = std::prev(RestoreEnd); 2465 while (RestoreBegin != MBB.begin() && 2466 IsSVECalleeSave(std::prev(RestoreBegin))) 2467 --RestoreBegin; 2468 2469 assert(IsSVECalleeSave(RestoreBegin) && 2470 IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction"); 2471 2472 StackOffset CalleeSavedSizeAsOffset = 2473 StackOffset::getScalable(CalleeSavedSize); 2474 DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset; 2475 DeallocateAfter = CalleeSavedSizeAsOffset; 2476 } 2477 2478 // Deallocate the SVE area. 2479 if (SVEStackSize) { 2480 // If we have stack realignment or variable sized objects on the stack, 2481 // restore the stack pointer from the frame pointer prior to SVE CSR 2482 // restoration. 2483 if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) { 2484 if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) { 2485 // Set SP to start of SVE callee-save area from which they can 2486 // be reloaded. The code below will deallocate the stack space 2487 // space by moving FP -> SP. 2488 emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP, 2489 StackOffset::getScalable(-CalleeSavedSize), TII, 2490 MachineInstr::FrameDestroy); 2491 } 2492 } else { 2493 if (AFI->getSVECalleeSavedStackSize()) { 2494 // Deallocate the non-SVE locals first before we can deallocate (and 2495 // restore callee saves) from the SVE area. 2496 emitFrameOffset( 2497 MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP, 2498 StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy, 2499 false, false, nullptr, EmitCFI && !hasFP(MF), 2500 SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize)); 2501 NumBytes = 0; 2502 } 2503 2504 emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP, 2505 DeallocateBefore, TII, MachineInstr::FrameDestroy, false, 2506 false, nullptr, EmitCFI && !hasFP(MF), 2507 SVEStackSize + 2508 StackOffset::getFixed(NumBytes + PrologueSaveSize)); 2509 2510 emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP, 2511 DeallocateAfter, TII, MachineInstr::FrameDestroy, false, 2512 false, nullptr, EmitCFI && !hasFP(MF), 2513 DeallocateAfter + 2514 StackOffset::getFixed(NumBytes + PrologueSaveSize)); 2515 } 2516 if (EmitCFI) 2517 emitCalleeSavedSVERestores(MBB, RestoreEnd); 2518 } 2519 2520 if (!hasFP(MF)) { 2521 bool RedZone = canUseRedZone(MF); 2522 // If this was a redzone leaf function, we don't need to restore the 2523 // stack pointer (but we may need to pop stack args for fastcc). 2524 if (RedZone && AfterCSRPopSize == 0) 2525 return; 2526 2527 // Pop the local variables off the stack. If there are no callee-saved 2528 // registers, it means we are actually positioned at the terminator and can 2529 // combine stack increment for the locals and the stack increment for 2530 // callee-popped arguments into (possibly) a single instruction and be done. 2531 bool NoCalleeSaveRestore = PrologueSaveSize == 0; 2532 int64_t StackRestoreBytes = RedZone ? 0 : NumBytes; 2533 if (NoCalleeSaveRestore) 2534 StackRestoreBytes += AfterCSRPopSize; 2535 2536 emitFrameOffset( 2537 MBB, LastPopI, DL, AArch64::SP, AArch64::SP, 2538 StackOffset::getFixed(StackRestoreBytes), TII, 2539 MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI, 2540 StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize)); 2541 2542 // If we were able to combine the local stack pop with the argument pop, 2543 // then we're done. 2544 if (NoCalleeSaveRestore || AfterCSRPopSize == 0) { 2545 return; 2546 } 2547 2548 NumBytes = 0; 2549 } 2550 2551 // Restore the original stack pointer. 2552 // FIXME: Rather than doing the math here, we should instead just use 2553 // non-post-indexed loads for the restores if we aren't actually going to 2554 // be able to save any instructions. 2555 if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) { 2556 emitFrameOffset( 2557 MBB, LastPopI, DL, AArch64::SP, AArch64::FP, 2558 StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()), 2559 TII, MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI); 2560 } else if (NumBytes) 2561 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, 2562 StackOffset::getFixed(NumBytes), TII, 2563 MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI); 2564 2565 // When we are about to restore the CSRs, the CFA register is SP again. 2566 if (EmitCFI && hasFP(MF)) { 2567 const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo(); 2568 unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true); 2569 unsigned CFIIndex = MF.addFrameInst( 2570 MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize)); 2571 BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 2572 .addCFIIndex(CFIIndex) 2573 .setMIFlags(MachineInstr::FrameDestroy); 2574 } 2575 2576 // This must be placed after the callee-save restore code because that code 2577 // assumes the SP is at the same location as it was after the callee-save save 2578 // code in the prologue. 2579 if (AfterCSRPopSize) { 2580 assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an " 2581 "interrupt may have clobbered"); 2582 2583 emitFrameOffset( 2584 MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP, 2585 StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy, 2586 false, NeedsWinCFI, &HasWinCFI, EmitCFI, 2587 StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0)); 2588 } 2589 } 2590 2591 bool AArch64FrameLowering::enableCFIFixup(MachineFunction &MF) const { 2592 return TargetFrameLowering::enableCFIFixup(MF) && 2593 MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF); 2594 } 2595 2596 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 2597 /// debug info. It's the same as what we use for resolving the code-gen 2598 /// references for now. FIXME: This can go wrong when references are 2599 /// SP-relative and simple call frames aren't used. 2600 StackOffset 2601 AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 2602 Register &FrameReg) const { 2603 return resolveFrameIndexReference( 2604 MF, FI, FrameReg, 2605 /*PreferFP=*/ 2606 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress) || 2607 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemTag), 2608 /*ForSimm=*/false); 2609 } 2610 2611 StackOffset 2612 AArch64FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, 2613 int FI) const { 2614 // This function serves to provide a comparable offset from a single reference 2615 // point (the value of SP at function entry) that can be used for analysis, 2616 // e.g. the stack-frame-layout analysis pass. It is not guaranteed to be 2617 // correct for all objects in the presence of VLA-area objects or dynamic 2618 // stack re-alignment. 2619 2620 const auto &MFI = MF.getFrameInfo(); 2621 2622 int64_t ObjectOffset = MFI.getObjectOffset(FI); 2623 StackOffset SVEStackSize = getSVEStackSize(MF); 2624 2625 // For VLA-area objects, just emit an offset at the end of the stack frame. 2626 // Whilst not quite correct, these objects do live at the end of the frame and 2627 // so it is more useful for analysis for the offset to reflect this. 2628 if (MFI.isVariableSizedObjectIndex(FI)) { 2629 return StackOffset::getFixed(-((int64_t)MFI.getStackSize())) - SVEStackSize; 2630 } 2631 2632 // This is correct in the absence of any SVE stack objects. 2633 if (!SVEStackSize) 2634 return StackOffset::getFixed(ObjectOffset - getOffsetOfLocalArea()); 2635 2636 const auto *AFI = MF.getInfo<AArch64FunctionInfo>(); 2637 if (MFI.getStackID(FI) == TargetStackID::ScalableVector) { 2638 return StackOffset::get(-((int64_t)AFI->getCalleeSavedStackSize()), 2639 ObjectOffset); 2640 } 2641 2642 bool IsFixed = MFI.isFixedObjectIndex(FI); 2643 bool IsCSR = 2644 !IsFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI)); 2645 2646 StackOffset ScalableOffset = {}; 2647 if (!IsFixed && !IsCSR) 2648 ScalableOffset = -SVEStackSize; 2649 2650 return StackOffset::getFixed(ObjectOffset) + ScalableOffset; 2651 } 2652 2653 StackOffset 2654 AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF, 2655 int FI) const { 2656 return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI)); 2657 } 2658 2659 static StackOffset getFPOffset(const MachineFunction &MF, 2660 int64_t ObjectOffset) { 2661 const auto *AFI = MF.getInfo<AArch64FunctionInfo>(); 2662 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 2663 const Function &F = MF.getFunction(); 2664 bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg()); 2665 unsigned FixedObject = 2666 getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false); 2667 int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo()); 2668 int64_t FPAdjust = 2669 CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset(); 2670 return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust); 2671 } 2672 2673 static StackOffset getStackOffset(const MachineFunction &MF, 2674 int64_t ObjectOffset) { 2675 const auto &MFI = MF.getFrameInfo(); 2676 return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize()); 2677 } 2678 2679 // TODO: This function currently does not work for scalable vectors. 2680 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF, 2681 int FI) const { 2682 const auto *RegInfo = static_cast<const AArch64RegisterInfo *>( 2683 MF.getSubtarget().getRegisterInfo()); 2684 int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI); 2685 return RegInfo->getLocalAddressRegister(MF) == AArch64::FP 2686 ? getFPOffset(MF, ObjectOffset).getFixed() 2687 : getStackOffset(MF, ObjectOffset).getFixed(); 2688 } 2689 2690 StackOffset AArch64FrameLowering::resolveFrameIndexReference( 2691 const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP, 2692 bool ForSimm) const { 2693 const auto &MFI = MF.getFrameInfo(); 2694 int64_t ObjectOffset = MFI.getObjectOffset(FI); 2695 bool isFixed = MFI.isFixedObjectIndex(FI); 2696 bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector; 2697 return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg, 2698 PreferFP, ForSimm); 2699 } 2700 2701 StackOffset AArch64FrameLowering::resolveFrameOffsetReference( 2702 const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE, 2703 Register &FrameReg, bool PreferFP, bool ForSimm) const { 2704 const auto &MFI = MF.getFrameInfo(); 2705 const auto *RegInfo = static_cast<const AArch64RegisterInfo *>( 2706 MF.getSubtarget().getRegisterInfo()); 2707 const auto *AFI = MF.getInfo<AArch64FunctionInfo>(); 2708 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 2709 2710 int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed(); 2711 int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed(); 2712 bool isCSR = 2713 !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI)); 2714 2715 const StackOffset &SVEStackSize = getSVEStackSize(MF); 2716 2717 // Use frame pointer to reference fixed objects. Use it for locals if 2718 // there are VLAs or a dynamically realigned SP (and thus the SP isn't 2719 // reliable as a base). Make sure useFPForScavengingIndex() does the 2720 // right thing for the emergency spill slot. 2721 bool UseFP = false; 2722 if (AFI->hasStackFrame() && !isSVE) { 2723 // We shouldn't prefer using the FP to access fixed-sized stack objects when 2724 // there are scalable (SVE) objects in between the FP and the fixed-sized 2725 // objects. 2726 PreferFP &= !SVEStackSize; 2727 2728 // Note: Keeping the following as multiple 'if' statements rather than 2729 // merging to a single expression for readability. 2730 // 2731 // Argument access should always use the FP. 2732 if (isFixed) { 2733 UseFP = hasFP(MF); 2734 } else if (isCSR && RegInfo->hasStackRealignment(MF)) { 2735 // References to the CSR area must use FP if we're re-aligning the stack 2736 // since the dynamically-sized alignment padding is between the SP/BP and 2737 // the CSR area. 2738 assert(hasFP(MF) && "Re-aligned stack must have frame pointer"); 2739 UseFP = true; 2740 } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) { 2741 // If the FPOffset is negative and we're producing a signed immediate, we 2742 // have to keep in mind that the available offset range for negative 2743 // offsets is smaller than for positive ones. If an offset is available 2744 // via the FP and the SP, use whichever is closest. 2745 bool FPOffsetFits = !ForSimm || FPOffset >= -256; 2746 PreferFP |= Offset > -FPOffset && !SVEStackSize; 2747 2748 if (MFI.hasVarSizedObjects()) { 2749 // If we have variable sized objects, we can use either FP or BP, as the 2750 // SP offset is unknown. We can use the base pointer if we have one and 2751 // FP is not preferred. If not, we're stuck with using FP. 2752 bool CanUseBP = RegInfo->hasBasePointer(MF); 2753 if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best. 2754 UseFP = PreferFP; 2755 else if (!CanUseBP) // Can't use BP. Forced to use FP. 2756 UseFP = true; 2757 // else we can use BP and FP, but the offset from FP won't fit. 2758 // That will make us scavenge registers which we can probably avoid by 2759 // using BP. If it won't fit for BP either, we'll scavenge anyway. 2760 } else if (FPOffset >= 0) { 2761 // Use SP or FP, whichever gives us the best chance of the offset 2762 // being in range for direct access. If the FPOffset is positive, 2763 // that'll always be best, as the SP will be even further away. 2764 UseFP = true; 2765 } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) { 2766 // Funclets access the locals contained in the parent's stack frame 2767 // via the frame pointer, so we have to use the FP in the parent 2768 // function. 2769 (void) Subtarget; 2770 assert(Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(), 2771 MF.getFunction().isVarArg()) && 2772 "Funclets should only be present on Win64"); 2773 UseFP = true; 2774 } else { 2775 // We have the choice between FP and (SP or BP). 2776 if (FPOffsetFits && PreferFP) // If FP is the best fit, use it. 2777 UseFP = true; 2778 } 2779 } 2780 } 2781 2782 assert( 2783 ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) && 2784 "In the presence of dynamic stack pointer realignment, " 2785 "non-argument/CSR objects cannot be accessed through the frame pointer"); 2786 2787 if (isSVE) { 2788 StackOffset FPOffset = 2789 StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset); 2790 StackOffset SPOffset = 2791 SVEStackSize + 2792 StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(), 2793 ObjectOffset); 2794 // Always use the FP for SVE spills if available and beneficial. 2795 if (hasFP(MF) && (SPOffset.getFixed() || 2796 FPOffset.getScalable() < SPOffset.getScalable() || 2797 RegInfo->hasStackRealignment(MF))) { 2798 FrameReg = RegInfo->getFrameRegister(MF); 2799 return FPOffset; 2800 } 2801 2802 FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister() 2803 : (unsigned)AArch64::SP; 2804 return SPOffset; 2805 } 2806 2807 StackOffset ScalableOffset = {}; 2808 if (UseFP && !(isFixed || isCSR)) 2809 ScalableOffset = -SVEStackSize; 2810 if (!UseFP && (isFixed || isCSR)) 2811 ScalableOffset = SVEStackSize; 2812 2813 if (UseFP) { 2814 FrameReg = RegInfo->getFrameRegister(MF); 2815 return StackOffset::getFixed(FPOffset) + ScalableOffset; 2816 } 2817 2818 // Use the base pointer if we have one. 2819 if (RegInfo->hasBasePointer(MF)) 2820 FrameReg = RegInfo->getBaseRegister(); 2821 else { 2822 assert(!MFI.hasVarSizedObjects() && 2823 "Can't use SP when we have var sized objects."); 2824 FrameReg = AArch64::SP; 2825 // If we're using the red zone for this function, the SP won't actually 2826 // be adjusted, so the offsets will be negative. They're also all 2827 // within range of the signed 9-bit immediate instructions. 2828 if (canUseRedZone(MF)) 2829 Offset -= AFI->getLocalStackSize(); 2830 } 2831 2832 return StackOffset::getFixed(Offset) + ScalableOffset; 2833 } 2834 2835 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) { 2836 // Do not set a kill flag on values that are also marked as live-in. This 2837 // happens with the @llvm-returnaddress intrinsic and with arguments passed in 2838 // callee saved registers. 2839 // Omitting the kill flags is conservatively correct even if the live-in 2840 // is not used after all. 2841 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg); 2842 return getKillRegState(!IsLiveIn); 2843 } 2844 2845 static bool produceCompactUnwindFrame(MachineFunction &MF) { 2846 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 2847 AttributeList Attrs = MF.getFunction().getAttributes(); 2848 return Subtarget.isTargetMachO() && 2849 !(Subtarget.getTargetLowering()->supportSwiftError() && 2850 Attrs.hasAttrSomewhere(Attribute::SwiftError)) && 2851 MF.getFunction().getCallingConv() != CallingConv::SwiftTail; 2852 } 2853 2854 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2, 2855 bool NeedsWinCFI, bool IsFirst, 2856 const TargetRegisterInfo *TRI) { 2857 // If we are generating register pairs for a Windows function that requires 2858 // EH support, then pair consecutive registers only. There are no unwind 2859 // opcodes for saves/restores of non-consectuve register pairs. 2860 // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x, 2861 // save_lrpair. 2862 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling 2863 2864 if (Reg2 == AArch64::FP) 2865 return true; 2866 if (!NeedsWinCFI) 2867 return false; 2868 if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1) 2869 return false; 2870 // If pairing a GPR with LR, the pair can be described by the save_lrpair 2871 // opcode. If this is the first register pair, it would end up with a 2872 // predecrement, but there's no save_lrpair_x opcode, so we can only do this 2873 // if LR is paired with something else than the first register. 2874 // The save_lrpair opcode requires the first register to be an odd one. 2875 if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 && 2876 (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst) 2877 return false; 2878 return true; 2879 } 2880 2881 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction. 2882 /// WindowsCFI requires that only consecutive registers can be paired. 2883 /// LR and FP need to be allocated together when the frame needs to save 2884 /// the frame-record. This means any other register pairing with LR is invalid. 2885 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2, 2886 bool UsesWinAAPCS, bool NeedsWinCFI, 2887 bool NeedsFrameRecord, bool IsFirst, 2888 const TargetRegisterInfo *TRI) { 2889 if (UsesWinAAPCS) 2890 return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst, 2891 TRI); 2892 2893 // If we need to store the frame record, don't pair any register 2894 // with LR other than FP. 2895 if (NeedsFrameRecord) 2896 return Reg2 == AArch64::LR; 2897 2898 return false; 2899 } 2900 2901 namespace { 2902 2903 struct RegPairInfo { 2904 unsigned Reg1 = AArch64::NoRegister; 2905 unsigned Reg2 = AArch64::NoRegister; 2906 int FrameIdx; 2907 int Offset; 2908 enum RegType { GPR, FPR64, FPR128, PPR, ZPR, VG } Type; 2909 2910 RegPairInfo() = default; 2911 2912 bool isPaired() const { return Reg2 != AArch64::NoRegister; } 2913 2914 unsigned getScale() const { 2915 switch (Type) { 2916 case PPR: 2917 return 2; 2918 case GPR: 2919 case FPR64: 2920 case VG: 2921 return 8; 2922 case ZPR: 2923 case FPR128: 2924 return 16; 2925 } 2926 llvm_unreachable("Unsupported type"); 2927 } 2928 2929 bool isScalable() const { return Type == PPR || Type == ZPR; } 2930 }; 2931 2932 } // end anonymous namespace 2933 2934 unsigned findFreePredicateReg(BitVector &SavedRegs) { 2935 for (unsigned PReg = AArch64::P8; PReg <= AArch64::P15; ++PReg) { 2936 if (SavedRegs.test(PReg)) { 2937 unsigned PNReg = PReg - AArch64::P0 + AArch64::PN0; 2938 return PNReg; 2939 } 2940 } 2941 return AArch64::NoRegister; 2942 } 2943 2944 static void computeCalleeSaveRegisterPairs( 2945 MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI, 2946 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs, 2947 bool NeedsFrameRecord) { 2948 2949 if (CSI.empty()) 2950 return; 2951 2952 bool IsWindows = isTargetWindows(MF); 2953 bool NeedsWinCFI = needsWinCFI(MF); 2954 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 2955 MachineFrameInfo &MFI = MF.getFrameInfo(); 2956 CallingConv::ID CC = MF.getFunction().getCallingConv(); 2957 unsigned Count = CSI.size(); 2958 (void)CC; 2959 // MachO's compact unwind format relies on all registers being stored in 2960 // pairs. 2961 assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost || 2962 CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS || 2963 CC == CallingConv::Win64 || (Count & 1) == 0) && 2964 "Odd number of callee-saved regs to spill!"); 2965 int ByteOffset = AFI->getCalleeSavedStackSize(); 2966 int StackFillDir = -1; 2967 int RegInc = 1; 2968 unsigned FirstReg = 0; 2969 if (NeedsWinCFI) { 2970 // For WinCFI, fill the stack from the bottom up. 2971 ByteOffset = 0; 2972 StackFillDir = 1; 2973 // As the CSI array is reversed to match PrologEpilogInserter, iterate 2974 // backwards, to pair up registers starting from lower numbered registers. 2975 RegInc = -1; 2976 FirstReg = Count - 1; 2977 } 2978 int ScalableByteOffset = AFI->getSVECalleeSavedStackSize(); 2979 bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace(); 2980 Register LastReg = 0; 2981 2982 // When iterating backwards, the loop condition relies on unsigned wraparound. 2983 for (unsigned i = FirstReg; i < Count; i += RegInc) { 2984 RegPairInfo RPI; 2985 RPI.Reg1 = CSI[i].getReg(); 2986 2987 if (AArch64::GPR64RegClass.contains(RPI.Reg1)) 2988 RPI.Type = RegPairInfo::GPR; 2989 else if (AArch64::FPR64RegClass.contains(RPI.Reg1)) 2990 RPI.Type = RegPairInfo::FPR64; 2991 else if (AArch64::FPR128RegClass.contains(RPI.Reg1)) 2992 RPI.Type = RegPairInfo::FPR128; 2993 else if (AArch64::ZPRRegClass.contains(RPI.Reg1)) 2994 RPI.Type = RegPairInfo::ZPR; 2995 else if (AArch64::PPRRegClass.contains(RPI.Reg1)) 2996 RPI.Type = RegPairInfo::PPR; 2997 else if (RPI.Reg1 == AArch64::VG) 2998 RPI.Type = RegPairInfo::VG; 2999 else 3000 llvm_unreachable("Unsupported register class."); 3001 3002 // Add the stack hazard size as we transition from GPR->FPR CSRs. 3003 if (AFI->hasStackHazardSlotIndex() && 3004 (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) && 3005 AArch64InstrInfo::isFpOrNEON(RPI.Reg1)) 3006 ByteOffset += StackFillDir * StackHazardSize; 3007 LastReg = RPI.Reg1; 3008 3009 // Add the next reg to the pair if it is in the same register class. 3010 if (unsigned(i + RegInc) < Count && !AFI->hasStackHazardSlotIndex()) { 3011 Register NextReg = CSI[i + RegInc].getReg(); 3012 bool IsFirst = i == FirstReg; 3013 switch (RPI.Type) { 3014 case RegPairInfo::GPR: 3015 if (AArch64::GPR64RegClass.contains(NextReg) && 3016 !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows, 3017 NeedsWinCFI, NeedsFrameRecord, IsFirst, 3018 TRI)) 3019 RPI.Reg2 = NextReg; 3020 break; 3021 case RegPairInfo::FPR64: 3022 if (AArch64::FPR64RegClass.contains(NextReg) && 3023 !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI, 3024 IsFirst, TRI)) 3025 RPI.Reg2 = NextReg; 3026 break; 3027 case RegPairInfo::FPR128: 3028 if (AArch64::FPR128RegClass.contains(NextReg)) 3029 RPI.Reg2 = NextReg; 3030 break; 3031 case RegPairInfo::PPR: 3032 break; 3033 case RegPairInfo::ZPR: 3034 if (AFI->getPredicateRegForFillSpill() != 0) 3035 if (((RPI.Reg1 - AArch64::Z0) & 1) == 0 && (NextReg == RPI.Reg1 + 1)) 3036 RPI.Reg2 = NextReg; 3037 break; 3038 case RegPairInfo::VG: 3039 break; 3040 } 3041 } 3042 3043 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI 3044 // list to come in sorted by frame index so that we can issue the store 3045 // pair instructions directly. Assert if we see anything otherwise. 3046 // 3047 // The order of the registers in the list is controlled by 3048 // getCalleeSavedRegs(), so they will always be in-order, as well. 3049 assert((!RPI.isPaired() || 3050 (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) && 3051 "Out of order callee saved regs!"); 3052 3053 assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP || 3054 RPI.Reg1 == AArch64::LR) && 3055 "FrameRecord must be allocated together with LR"); 3056 3057 // Windows AAPCS has FP and LR reversed. 3058 assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP || 3059 RPI.Reg2 == AArch64::LR) && 3060 "FrameRecord must be allocated together with LR"); 3061 3062 // MachO's compact unwind format relies on all registers being stored in 3063 // adjacent register pairs. 3064 assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost || 3065 CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS || 3066 CC == CallingConv::Win64 || 3067 (RPI.isPaired() && 3068 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) || 3069 RPI.Reg1 + 1 == RPI.Reg2))) && 3070 "Callee-save registers not saved as adjacent register pair!"); 3071 3072 RPI.FrameIdx = CSI[i].getFrameIdx(); 3073 if (NeedsWinCFI && 3074 RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair 3075 RPI.FrameIdx = CSI[i + RegInc].getFrameIdx(); 3076 int Scale = RPI.getScale(); 3077 3078 int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset; 3079 assert(OffsetPre % Scale == 0); 3080 3081 if (RPI.isScalable()) 3082 ScalableByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale); 3083 else 3084 ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale); 3085 3086 // Swift's async context is directly before FP, so allocate an extra 3087 // 8 bytes for it. 3088 if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() && 3089 ((!IsWindows && RPI.Reg2 == AArch64::FP) || 3090 (IsWindows && RPI.Reg2 == AArch64::LR))) 3091 ByteOffset += StackFillDir * 8; 3092 3093 // Round up size of non-pair to pair size if we need to pad the 3094 // callee-save area to ensure 16-byte alignment. 3095 if (NeedGapToAlignStack && !NeedsWinCFI && !RPI.isScalable() && 3096 RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired() && 3097 ByteOffset % 16 != 0) { 3098 ByteOffset += 8 * StackFillDir; 3099 assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16)); 3100 // A stack frame with a gap looks like this, bottom up: 3101 // d9, d8. x21, gap, x20, x19. 3102 // Set extra alignment on the x21 object to create the gap above it. 3103 MFI.setObjectAlignment(RPI.FrameIdx, Align(16)); 3104 NeedGapToAlignStack = false; 3105 } 3106 3107 int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset; 3108 assert(OffsetPost % Scale == 0); 3109 // If filling top down (default), we want the offset after incrementing it. 3110 // If filling bottom up (WinCFI) we need the original offset. 3111 int Offset = NeedsWinCFI ? OffsetPre : OffsetPost; 3112 3113 // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the 3114 // Swift context can directly precede FP. 3115 if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() && 3116 ((!IsWindows && RPI.Reg2 == AArch64::FP) || 3117 (IsWindows && RPI.Reg2 == AArch64::LR))) 3118 Offset += 8; 3119 RPI.Offset = Offset / Scale; 3120 3121 assert((!RPI.isPaired() || 3122 (!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) || 3123 (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) && 3124 "Offset out of bounds for LDP/STP immediate"); 3125 3126 // Save the offset to frame record so that the FP register can point to the 3127 // innermost frame record (spilled FP and LR registers). 3128 if (NeedsFrameRecord && 3129 ((!IsWindows && RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) || 3130 (IsWindows && RPI.Reg1 == AArch64::FP && RPI.Reg2 == AArch64::LR))) 3131 AFI->setCalleeSaveBaseToFrameRecordOffset(Offset); 3132 3133 RegPairs.push_back(RPI); 3134 if (RPI.isPaired()) 3135 i += RegInc; 3136 } 3137 if (NeedsWinCFI) { 3138 // If we need an alignment gap in the stack, align the topmost stack 3139 // object. A stack frame with a gap looks like this, bottom up: 3140 // x19, d8. d9, gap. 3141 // Set extra alignment on the topmost stack object (the first element in 3142 // CSI, which goes top down), to create the gap above it. 3143 if (AFI->hasCalleeSaveStackFreeSpace()) 3144 MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16)); 3145 // We iterated bottom up over the registers; flip RegPairs back to top 3146 // down order. 3147 std::reverse(RegPairs.begin(), RegPairs.end()); 3148 } 3149 } 3150 3151 bool AArch64FrameLowering::spillCalleeSavedRegisters( 3152 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 3153 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 3154 MachineFunction &MF = *MBB.getParent(); 3155 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 3156 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3157 bool NeedsWinCFI = needsWinCFI(MF); 3158 DebugLoc DL; 3159 SmallVector<RegPairInfo, 8> RegPairs; 3160 3161 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF)); 3162 3163 MachineRegisterInfo &MRI = MF.getRegInfo(); 3164 // Refresh the reserved regs in case there are any potential changes since the 3165 // last freeze. 3166 MRI.freezeReservedRegs(); 3167 3168 if (homogeneousPrologEpilog(MF)) { 3169 auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog)) 3170 .setMIFlag(MachineInstr::FrameSetup); 3171 3172 for (auto &RPI : RegPairs) { 3173 MIB.addReg(RPI.Reg1); 3174 MIB.addReg(RPI.Reg2); 3175 3176 // Update register live in. 3177 if (!MRI.isReserved(RPI.Reg1)) 3178 MBB.addLiveIn(RPI.Reg1); 3179 if (RPI.isPaired() && !MRI.isReserved(RPI.Reg2)) 3180 MBB.addLiveIn(RPI.Reg2); 3181 } 3182 return true; 3183 } 3184 bool PTrueCreated = false; 3185 for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) { 3186 unsigned Reg1 = RPI.Reg1; 3187 unsigned Reg2 = RPI.Reg2; 3188 unsigned StrOpc; 3189 3190 // Issue sequence of spills for cs regs. The first spill may be converted 3191 // to a pre-decrement store later by emitPrologue if the callee-save stack 3192 // area allocation can't be combined with the local stack area allocation. 3193 // For example: 3194 // stp x22, x21, [sp, #0] // addImm(+0) 3195 // stp x20, x19, [sp, #16] // addImm(+2) 3196 // stp fp, lr, [sp, #32] // addImm(+4) 3197 // Rationale: This sequence saves uop updates compared to a sequence of 3198 // pre-increment spills like stp xi,xj,[sp,#-16]! 3199 // Note: Similar rationale and sequence for restores in epilog. 3200 unsigned Size; 3201 Align Alignment; 3202 switch (RPI.Type) { 3203 case RegPairInfo::GPR: 3204 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui; 3205 Size = 8; 3206 Alignment = Align(8); 3207 break; 3208 case RegPairInfo::FPR64: 3209 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui; 3210 Size = 8; 3211 Alignment = Align(8); 3212 break; 3213 case RegPairInfo::FPR128: 3214 StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui; 3215 Size = 16; 3216 Alignment = Align(16); 3217 break; 3218 case RegPairInfo::ZPR: 3219 StrOpc = RPI.isPaired() ? AArch64::ST1B_2Z_IMM : AArch64::STR_ZXI; 3220 Size = 16; 3221 Alignment = Align(16); 3222 break; 3223 case RegPairInfo::PPR: 3224 StrOpc = AArch64::STR_PXI; 3225 Size = 2; 3226 Alignment = Align(2); 3227 break; 3228 case RegPairInfo::VG: 3229 StrOpc = AArch64::STRXui; 3230 Size = 8; 3231 Alignment = Align(8); 3232 break; 3233 } 3234 3235 unsigned X0Scratch = AArch64::NoRegister; 3236 if (Reg1 == AArch64::VG) { 3237 // Find an available register to store value of VG to. 3238 Reg1 = findScratchNonCalleeSaveRegister(&MBB); 3239 assert(Reg1 != AArch64::NoRegister); 3240 SMEAttrs Attrs(MF.getFunction()); 3241 3242 if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface() && 3243 AFI->getStreamingVGIdx() == std::numeric_limits<int>::max()) { 3244 // For locally-streaming functions, we need to store both the streaming 3245 // & non-streaming VG. Spill the streaming value first. 3246 BuildMI(MBB, MI, DL, TII.get(AArch64::RDSVLI_XI), Reg1) 3247 .addImm(1) 3248 .setMIFlag(MachineInstr::FrameSetup); 3249 BuildMI(MBB, MI, DL, TII.get(AArch64::UBFMXri), Reg1) 3250 .addReg(Reg1) 3251 .addImm(3) 3252 .addImm(63) 3253 .setMIFlag(MachineInstr::FrameSetup); 3254 3255 AFI->setStreamingVGIdx(RPI.FrameIdx); 3256 } else if (MF.getSubtarget<AArch64Subtarget>().hasSVE()) { 3257 BuildMI(MBB, MI, DL, TII.get(AArch64::CNTD_XPiI), Reg1) 3258 .addImm(31) 3259 .addImm(1) 3260 .setMIFlag(MachineInstr::FrameSetup); 3261 AFI->setVGIdx(RPI.FrameIdx); 3262 } else { 3263 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>(); 3264 if (llvm::any_of( 3265 MBB.liveins(), 3266 [&STI](const MachineBasicBlock::RegisterMaskPair &LiveIn) { 3267 return STI.getRegisterInfo()->isSuperOrSubRegisterEq( 3268 AArch64::X0, LiveIn.PhysReg); 3269 })) 3270 X0Scratch = Reg1; 3271 3272 if (X0Scratch != AArch64::NoRegister) 3273 BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), Reg1) 3274 .addReg(AArch64::XZR) 3275 .addReg(AArch64::X0, RegState::Undef) 3276 .addReg(AArch64::X0, RegState::Implicit) 3277 .setMIFlag(MachineInstr::FrameSetup); 3278 3279 const uint32_t *RegMask = TRI->getCallPreservedMask( 3280 MF, 3281 CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1); 3282 BuildMI(MBB, MI, DL, TII.get(AArch64::BL)) 3283 .addExternalSymbol("__arm_get_current_vg") 3284 .addRegMask(RegMask) 3285 .addReg(AArch64::X0, RegState::ImplicitDefine) 3286 .setMIFlag(MachineInstr::FrameSetup); 3287 Reg1 = AArch64::X0; 3288 AFI->setVGIdx(RPI.FrameIdx); 3289 } 3290 } 3291 3292 LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI); 3293 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI); 3294 dbgs() << ") -> fi#(" << RPI.FrameIdx; 3295 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1; 3296 dbgs() << ")\n"); 3297 3298 assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) && 3299 "Windows unwdinding requires a consecutive (FP,LR) pair"); 3300 // Windows unwind codes require consecutive registers if registers are 3301 // paired. Make the switch here, so that the code below will save (x,x+1) 3302 // and not (x+1,x). 3303 unsigned FrameIdxReg1 = RPI.FrameIdx; 3304 unsigned FrameIdxReg2 = RPI.FrameIdx + 1; 3305 if (NeedsWinCFI && RPI.isPaired()) { 3306 std::swap(Reg1, Reg2); 3307 std::swap(FrameIdxReg1, FrameIdxReg2); 3308 } 3309 3310 if (RPI.isPaired() && RPI.isScalable()) { 3311 [[maybe_unused]] const AArch64Subtarget &Subtarget = 3312 MF.getSubtarget<AArch64Subtarget>(); 3313 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3314 unsigned PnReg = AFI->getPredicateRegForFillSpill(); 3315 assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) && 3316 "Expects SVE2.1 or SME2 target and a predicate register"); 3317 #ifdef EXPENSIVE_CHECKS 3318 auto IsPPR = [](const RegPairInfo &c) { 3319 return c.Reg1 == RegPairInfo::PPR; 3320 }; 3321 auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR); 3322 auto IsZPR = [](const RegPairInfo &c) { 3323 return c.Type == RegPairInfo::ZPR; 3324 }; 3325 auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR); 3326 assert(!(PPRBegin < ZPRBegin) && 3327 "Expected callee save predicate to be handled first"); 3328 #endif 3329 if (!PTrueCreated) { 3330 PTrueCreated = true; 3331 BuildMI(MBB, MI, DL, TII.get(AArch64::PTRUE_C_B), PnReg) 3332 .setMIFlags(MachineInstr::FrameSetup); 3333 } 3334 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc)); 3335 if (!MRI.isReserved(Reg1)) 3336 MBB.addLiveIn(Reg1); 3337 if (!MRI.isReserved(Reg2)) 3338 MBB.addLiveIn(Reg2); 3339 MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0)); 3340 MIB.addMemOperand(MF.getMachineMemOperand( 3341 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 3342 MachineMemOperand::MOStore, Size, Alignment)); 3343 MIB.addReg(PnReg); 3344 MIB.addReg(AArch64::SP) 3345 .addImm(RPI.Offset) // [sp, #offset*scale], 3346 // where factor*scale is implicit 3347 .setMIFlag(MachineInstr::FrameSetup); 3348 MIB.addMemOperand(MF.getMachineMemOperand( 3349 MachinePointerInfo::getFixedStack(MF, FrameIdxReg1), 3350 MachineMemOperand::MOStore, Size, Alignment)); 3351 if (NeedsWinCFI) 3352 InsertSEH(MIB, TII, MachineInstr::FrameSetup); 3353 } else { // The code when the pair of ZReg is not present 3354 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc)); 3355 if (!MRI.isReserved(Reg1)) 3356 MBB.addLiveIn(Reg1); 3357 if (RPI.isPaired()) { 3358 if (!MRI.isReserved(Reg2)) 3359 MBB.addLiveIn(Reg2); 3360 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2)); 3361 MIB.addMemOperand(MF.getMachineMemOperand( 3362 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 3363 MachineMemOperand::MOStore, Size, Alignment)); 3364 } 3365 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1)) 3366 .addReg(AArch64::SP) 3367 .addImm(RPI.Offset) // [sp, #offset*scale], 3368 // where factor*scale is implicit 3369 .setMIFlag(MachineInstr::FrameSetup); 3370 MIB.addMemOperand(MF.getMachineMemOperand( 3371 MachinePointerInfo::getFixedStack(MF, FrameIdxReg1), 3372 MachineMemOperand::MOStore, Size, Alignment)); 3373 if (NeedsWinCFI) 3374 InsertSEH(MIB, TII, MachineInstr::FrameSetup); 3375 } 3376 // Update the StackIDs of the SVE stack slots. 3377 MachineFrameInfo &MFI = MF.getFrameInfo(); 3378 if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR) { 3379 MFI.setStackID(FrameIdxReg1, TargetStackID::ScalableVector); 3380 if (RPI.isPaired()) 3381 MFI.setStackID(FrameIdxReg2, TargetStackID::ScalableVector); 3382 } 3383 3384 if (X0Scratch != AArch64::NoRegister) 3385 BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), AArch64::X0) 3386 .addReg(AArch64::XZR) 3387 .addReg(X0Scratch, RegState::Undef) 3388 .addReg(X0Scratch, RegState::Implicit) 3389 .setMIFlag(MachineInstr::FrameSetup); 3390 } 3391 return true; 3392 } 3393 3394 bool AArch64FrameLowering::restoreCalleeSavedRegisters( 3395 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 3396 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 3397 MachineFunction &MF = *MBB.getParent(); 3398 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 3399 DebugLoc DL; 3400 SmallVector<RegPairInfo, 8> RegPairs; 3401 bool NeedsWinCFI = needsWinCFI(MF); 3402 3403 if (MBBI != MBB.end()) 3404 DL = MBBI->getDebugLoc(); 3405 3406 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF)); 3407 if (homogeneousPrologEpilog(MF, &MBB)) { 3408 auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog)) 3409 .setMIFlag(MachineInstr::FrameDestroy); 3410 for (auto &RPI : RegPairs) { 3411 MIB.addReg(RPI.Reg1, RegState::Define); 3412 MIB.addReg(RPI.Reg2, RegState::Define); 3413 } 3414 return true; 3415 } 3416 3417 // For performance reasons restore SVE register in increasing order 3418 auto IsPPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::PPR; }; 3419 auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR); 3420 auto PPREnd = std::find_if_not(PPRBegin, RegPairs.end(), IsPPR); 3421 std::reverse(PPRBegin, PPREnd); 3422 auto IsZPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::ZPR; }; 3423 auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR); 3424 auto ZPREnd = std::find_if_not(ZPRBegin, RegPairs.end(), IsZPR); 3425 std::reverse(ZPRBegin, ZPREnd); 3426 3427 bool PTrueCreated = false; 3428 for (const RegPairInfo &RPI : RegPairs) { 3429 unsigned Reg1 = RPI.Reg1; 3430 unsigned Reg2 = RPI.Reg2; 3431 3432 // Issue sequence of restores for cs regs. The last restore may be converted 3433 // to a post-increment load later by emitEpilogue if the callee-save stack 3434 // area allocation can't be combined with the local stack area allocation. 3435 // For example: 3436 // ldp fp, lr, [sp, #32] // addImm(+4) 3437 // ldp x20, x19, [sp, #16] // addImm(+2) 3438 // ldp x22, x21, [sp, #0] // addImm(+0) 3439 // Note: see comment in spillCalleeSavedRegisters() 3440 unsigned LdrOpc; 3441 unsigned Size; 3442 Align Alignment; 3443 switch (RPI.Type) { 3444 case RegPairInfo::GPR: 3445 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui; 3446 Size = 8; 3447 Alignment = Align(8); 3448 break; 3449 case RegPairInfo::FPR64: 3450 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui; 3451 Size = 8; 3452 Alignment = Align(8); 3453 break; 3454 case RegPairInfo::FPR128: 3455 LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui; 3456 Size = 16; 3457 Alignment = Align(16); 3458 break; 3459 case RegPairInfo::ZPR: 3460 LdrOpc = RPI.isPaired() ? AArch64::LD1B_2Z_IMM : AArch64::LDR_ZXI; 3461 Size = 16; 3462 Alignment = Align(16); 3463 break; 3464 case RegPairInfo::PPR: 3465 LdrOpc = AArch64::LDR_PXI; 3466 Size = 2; 3467 Alignment = Align(2); 3468 break; 3469 case RegPairInfo::VG: 3470 continue; 3471 } 3472 LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI); 3473 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI); 3474 dbgs() << ") -> fi#(" << RPI.FrameIdx; 3475 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1; 3476 dbgs() << ")\n"); 3477 3478 // Windows unwind codes require consecutive registers if registers are 3479 // paired. Make the switch here, so that the code below will save (x,x+1) 3480 // and not (x+1,x). 3481 unsigned FrameIdxReg1 = RPI.FrameIdx; 3482 unsigned FrameIdxReg2 = RPI.FrameIdx + 1; 3483 if (NeedsWinCFI && RPI.isPaired()) { 3484 std::swap(Reg1, Reg2); 3485 std::swap(FrameIdxReg1, FrameIdxReg2); 3486 } 3487 3488 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3489 if (RPI.isPaired() && RPI.isScalable()) { 3490 [[maybe_unused]] const AArch64Subtarget &Subtarget = 3491 MF.getSubtarget<AArch64Subtarget>(); 3492 unsigned PnReg = AFI->getPredicateRegForFillSpill(); 3493 assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) && 3494 "Expects SVE2.1 or SME2 target and a predicate register"); 3495 #ifdef EXPENSIVE_CHECKS 3496 assert(!(PPRBegin < ZPRBegin) && 3497 "Expected callee save predicate to be handled first"); 3498 #endif 3499 if (!PTrueCreated) { 3500 PTrueCreated = true; 3501 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PTRUE_C_B), PnReg) 3502 .setMIFlags(MachineInstr::FrameDestroy); 3503 } 3504 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc)); 3505 MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0), 3506 getDefRegState(true)); 3507 MIB.addMemOperand(MF.getMachineMemOperand( 3508 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 3509 MachineMemOperand::MOLoad, Size, Alignment)); 3510 MIB.addReg(PnReg); 3511 MIB.addReg(AArch64::SP) 3512 .addImm(RPI.Offset) // [sp, #offset*scale] 3513 // where factor*scale is implicit 3514 .setMIFlag(MachineInstr::FrameDestroy); 3515 MIB.addMemOperand(MF.getMachineMemOperand( 3516 MachinePointerInfo::getFixedStack(MF, FrameIdxReg1), 3517 MachineMemOperand::MOLoad, Size, Alignment)); 3518 if (NeedsWinCFI) 3519 InsertSEH(MIB, TII, MachineInstr::FrameDestroy); 3520 } else { 3521 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc)); 3522 if (RPI.isPaired()) { 3523 MIB.addReg(Reg2, getDefRegState(true)); 3524 MIB.addMemOperand(MF.getMachineMemOperand( 3525 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 3526 MachineMemOperand::MOLoad, Size, Alignment)); 3527 } 3528 MIB.addReg(Reg1, getDefRegState(true)); 3529 MIB.addReg(AArch64::SP) 3530 .addImm(RPI.Offset) // [sp, #offset*scale] 3531 // where factor*scale is implicit 3532 .setMIFlag(MachineInstr::FrameDestroy); 3533 MIB.addMemOperand(MF.getMachineMemOperand( 3534 MachinePointerInfo::getFixedStack(MF, FrameIdxReg1), 3535 MachineMemOperand::MOLoad, Size, Alignment)); 3536 if (NeedsWinCFI) 3537 InsertSEH(MIB, TII, MachineInstr::FrameDestroy); 3538 } 3539 } 3540 return true; 3541 } 3542 3543 // Return the FrameID for a MMO. 3544 static std::optional<int> getMMOFrameID(MachineMemOperand *MMO, 3545 const MachineFrameInfo &MFI) { 3546 auto *PSV = 3547 dyn_cast_or_null<FixedStackPseudoSourceValue>(MMO->getPseudoValue()); 3548 if (PSV) 3549 return std::optional<int>(PSV->getFrameIndex()); 3550 3551 if (MMO->getValue()) { 3552 if (auto *Al = dyn_cast<AllocaInst>(getUnderlyingObject(MMO->getValue()))) { 3553 for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd(); 3554 FI++) 3555 if (MFI.getObjectAllocation(FI) == Al) 3556 return FI; 3557 } 3558 } 3559 3560 return std::nullopt; 3561 } 3562 3563 // Return the FrameID for a Load/Store instruction by looking at the first MMO. 3564 static std::optional<int> getLdStFrameID(const MachineInstr &MI, 3565 const MachineFrameInfo &MFI) { 3566 if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1) 3567 return std::nullopt; 3568 3569 return getMMOFrameID(*MI.memoperands_begin(), MFI); 3570 } 3571 3572 // Check if a Hazard slot is needed for the current function, and if so create 3573 // one for it. The index is stored in AArch64FunctionInfo->StackHazardSlotIndex, 3574 // which can be used to determine if any hazard padding is needed. 3575 void AArch64FrameLowering::determineStackHazardSlot( 3576 MachineFunction &MF, BitVector &SavedRegs) const { 3577 if (StackHazardSize == 0 || StackHazardSize % 16 != 0 || 3578 MF.getInfo<AArch64FunctionInfo>()->hasStackHazardSlotIndex()) 3579 return; 3580 3581 // Stack hazards are only needed in streaming functions. 3582 SMEAttrs Attrs(MF.getFunction()); 3583 if (!StackHazardInNonStreaming && Attrs.hasNonStreamingInterfaceAndBody()) 3584 return; 3585 3586 MachineFrameInfo &MFI = MF.getFrameInfo(); 3587 3588 // Add a hazard slot if there are any CSR FPR registers, or are any fp-only 3589 // stack objects. 3590 bool HasFPRCSRs = any_of(SavedRegs.set_bits(), [](unsigned Reg) { 3591 return AArch64::FPR64RegClass.contains(Reg) || 3592 AArch64::FPR128RegClass.contains(Reg) || 3593 AArch64::ZPRRegClass.contains(Reg) || 3594 AArch64::PPRRegClass.contains(Reg); 3595 }); 3596 bool HasFPRStackObjects = false; 3597 if (!HasFPRCSRs) { 3598 std::vector<unsigned> FrameObjects(MFI.getObjectIndexEnd()); 3599 for (auto &MBB : MF) { 3600 for (auto &MI : MBB) { 3601 std::optional<int> FI = getLdStFrameID(MI, MFI); 3602 if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) { 3603 if (MFI.getStackID(*FI) == TargetStackID::ScalableVector || 3604 AArch64InstrInfo::isFpOrNEON(MI)) 3605 FrameObjects[*FI] |= 2; 3606 else 3607 FrameObjects[*FI] |= 1; 3608 } 3609 } 3610 } 3611 HasFPRStackObjects = 3612 any_of(FrameObjects, [](unsigned B) { return (B & 3) == 2; }); 3613 } 3614 3615 if (HasFPRCSRs || HasFPRStackObjects) { 3616 int ID = MFI.CreateStackObject(StackHazardSize, Align(16), false); 3617 LLVM_DEBUG(dbgs() << "Created Hazard slot at " << ID << " size " 3618 << StackHazardSize << "\n"); 3619 MF.getInfo<AArch64FunctionInfo>()->setStackHazardSlotIndex(ID); 3620 } 3621 } 3622 3623 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF, 3624 BitVector &SavedRegs, 3625 RegScavenger *RS) const { 3626 // All calls are tail calls in GHC calling conv, and functions have no 3627 // prologue/epilogue. 3628 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 3629 return; 3630 3631 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 3632 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>( 3633 MF.getSubtarget().getRegisterInfo()); 3634 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 3635 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3636 unsigned UnspilledCSGPR = AArch64::NoRegister; 3637 unsigned UnspilledCSGPRPaired = AArch64::NoRegister; 3638 3639 MachineFrameInfo &MFI = MF.getFrameInfo(); 3640 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs(); 3641 3642 unsigned BasePointerReg = RegInfo->hasBasePointer(MF) 3643 ? RegInfo->getBaseRegister() 3644 : (unsigned)AArch64::NoRegister; 3645 3646 unsigned ExtraCSSpill = 0; 3647 bool HasUnpairedGPR64 = false; 3648 bool HasPairZReg = false; 3649 // Figure out which callee-saved registers to save/restore. 3650 for (unsigned i = 0; CSRegs[i]; ++i) { 3651 const unsigned Reg = CSRegs[i]; 3652 3653 // Add the base pointer register to SavedRegs if it is callee-save. 3654 if (Reg == BasePointerReg) 3655 SavedRegs.set(Reg); 3656 3657 bool RegUsed = SavedRegs.test(Reg); 3658 unsigned PairedReg = AArch64::NoRegister; 3659 const bool RegIsGPR64 = AArch64::GPR64RegClass.contains(Reg); 3660 if (RegIsGPR64 || AArch64::FPR64RegClass.contains(Reg) || 3661 AArch64::FPR128RegClass.contains(Reg)) { 3662 // Compensate for odd numbers of GP CSRs. 3663 // For now, all the known cases of odd number of CSRs are of GPRs. 3664 if (HasUnpairedGPR64) 3665 PairedReg = CSRegs[i % 2 == 0 ? i - 1 : i + 1]; 3666 else 3667 PairedReg = CSRegs[i ^ 1]; 3668 } 3669 3670 // If the function requires all the GP registers to save (SavedRegs), 3671 // and there are an odd number of GP CSRs at the same time (CSRegs), 3672 // PairedReg could be in a different register class from Reg, which would 3673 // lead to a FPR (usually D8) accidentally being marked saved. 3674 if (RegIsGPR64 && !AArch64::GPR64RegClass.contains(PairedReg)) { 3675 PairedReg = AArch64::NoRegister; 3676 HasUnpairedGPR64 = true; 3677 } 3678 assert(PairedReg == AArch64::NoRegister || 3679 AArch64::GPR64RegClass.contains(Reg, PairedReg) || 3680 AArch64::FPR64RegClass.contains(Reg, PairedReg) || 3681 AArch64::FPR128RegClass.contains(Reg, PairedReg)); 3682 3683 if (!RegUsed) { 3684 if (AArch64::GPR64RegClass.contains(Reg) && 3685 !RegInfo->isReservedReg(MF, Reg)) { 3686 UnspilledCSGPR = Reg; 3687 UnspilledCSGPRPaired = PairedReg; 3688 } 3689 continue; 3690 } 3691 3692 // MachO's compact unwind format relies on all registers being stored in 3693 // pairs. 3694 // FIXME: the usual format is actually better if unwinding isn't needed. 3695 if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister && 3696 !SavedRegs.test(PairedReg)) { 3697 SavedRegs.set(PairedReg); 3698 if (AArch64::GPR64RegClass.contains(PairedReg) && 3699 !RegInfo->isReservedReg(MF, PairedReg)) 3700 ExtraCSSpill = PairedReg; 3701 } 3702 // Check if there is a pair of ZRegs, so it can select PReg for spill/fill 3703 HasPairZReg |= (AArch64::ZPRRegClass.contains(Reg, CSRegs[i ^ 1]) && 3704 SavedRegs.test(CSRegs[i ^ 1])); 3705 } 3706 3707 if (HasPairZReg && (Subtarget.hasSVE2p1() || Subtarget.hasSME2())) { 3708 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3709 // Find a suitable predicate register for the multi-vector spill/fill 3710 // instructions. 3711 unsigned PnReg = findFreePredicateReg(SavedRegs); 3712 if (PnReg != AArch64::NoRegister) 3713 AFI->setPredicateRegForFillSpill(PnReg); 3714 // If no free callee-save has been found assign one. 3715 if (!AFI->getPredicateRegForFillSpill() && 3716 MF.getFunction().getCallingConv() == 3717 CallingConv::AArch64_SVE_VectorCall) { 3718 SavedRegs.set(AArch64::P8); 3719 AFI->setPredicateRegForFillSpill(AArch64::PN8); 3720 } 3721 3722 assert(!RegInfo->isReservedReg(MF, AFI->getPredicateRegForFillSpill()) && 3723 "Predicate cannot be a reserved register"); 3724 } 3725 3726 if (MF.getFunction().getCallingConv() == CallingConv::Win64 && 3727 !Subtarget.isTargetWindows()) { 3728 // For Windows calling convention on a non-windows OS, where X18 is treated 3729 // as reserved, back up X18 when entering non-windows code (marked with the 3730 // Windows calling convention) and restore when returning regardless of 3731 // whether the individual function uses it - it might call other functions 3732 // that clobber it. 3733 SavedRegs.set(AArch64::X18); 3734 } 3735 3736 // Calculates the callee saved stack size. 3737 unsigned CSStackSize = 0; 3738 unsigned SVECSStackSize = 0; 3739 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 3740 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3741 for (unsigned Reg : SavedRegs.set_bits()) { 3742 auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8; 3743 if (AArch64::PPRRegClass.contains(Reg) || 3744 AArch64::ZPRRegClass.contains(Reg)) 3745 SVECSStackSize += RegSize; 3746 else 3747 CSStackSize += RegSize; 3748 } 3749 3750 // Increase the callee-saved stack size if the function has streaming mode 3751 // changes, as we will need to spill the value of the VG register. 3752 // For locally streaming functions, we spill both the streaming and 3753 // non-streaming VG value. 3754 const Function &F = MF.getFunction(); 3755 SMEAttrs Attrs(F); 3756 if (AFI->hasStreamingModeChanges()) { 3757 if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface()) 3758 CSStackSize += 16; 3759 else 3760 CSStackSize += 8; 3761 } 3762 3763 // Determine if a Hazard slot should be used, and increase the CSStackSize by 3764 // StackHazardSize if so. 3765 determineStackHazardSlot(MF, SavedRegs); 3766 if (AFI->hasStackHazardSlotIndex()) 3767 CSStackSize += StackHazardSize; 3768 3769 // Save number of saved regs, so we can easily update CSStackSize later. 3770 unsigned NumSavedRegs = SavedRegs.count(); 3771 3772 // The frame record needs to be created by saving the appropriate registers 3773 uint64_t EstimatedStackSize = MFI.estimateStackSize(MF); 3774 if (hasFP(MF) || 3775 windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) { 3776 SavedRegs.set(AArch64::FP); 3777 SavedRegs.set(AArch64::LR); 3778 } 3779 3780 LLVM_DEBUG({ 3781 dbgs() << "*** determineCalleeSaves\nSaved CSRs:"; 3782 for (unsigned Reg : SavedRegs.set_bits()) 3783 dbgs() << ' ' << printReg(Reg, RegInfo); 3784 dbgs() << "\n"; 3785 }); 3786 3787 // If any callee-saved registers are used, the frame cannot be eliminated. 3788 int64_t SVEStackSize = 3789 alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16); 3790 bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize; 3791 3792 // The CSR spill slots have not been allocated yet, so estimateStackSize 3793 // won't include them. 3794 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF); 3795 3796 // We may address some of the stack above the canonical frame address, either 3797 // for our own arguments or during a call. Include that in calculating whether 3798 // we have complicated addressing concerns. 3799 int64_t CalleeStackUsed = 0; 3800 for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) { 3801 int64_t FixedOff = MFI.getObjectOffset(I); 3802 if (FixedOff > CalleeStackUsed) 3803 CalleeStackUsed = FixedOff; 3804 } 3805 3806 // Conservatively always assume BigStack when there are SVE spills. 3807 bool BigStack = SVEStackSize || (EstimatedStackSize + CSStackSize + 3808 CalleeStackUsed) > EstimatedStackSizeLimit; 3809 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) 3810 AFI->setHasStackFrame(true); 3811 3812 // Estimate if we might need to scavenge a register at some point in order 3813 // to materialize a stack offset. If so, either spill one additional 3814 // callee-saved register or reserve a special spill slot to facilitate 3815 // register scavenging. If we already spilled an extra callee-saved register 3816 // above to keep the number of spills even, we don't need to do anything else 3817 // here. 3818 if (BigStack) { 3819 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) { 3820 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo) 3821 << " to get a scratch register.\n"); 3822 SavedRegs.set(UnspilledCSGPR); 3823 ExtraCSSpill = UnspilledCSGPR; 3824 3825 // MachO's compact unwind format relies on all registers being stored in 3826 // pairs, so if we need to spill one extra for BigStack, then we need to 3827 // store the pair. 3828 if (producePairRegisters(MF)) { 3829 if (UnspilledCSGPRPaired == AArch64::NoRegister) { 3830 // Failed to make a pair for compact unwind format, revert spilling. 3831 if (produceCompactUnwindFrame(MF)) { 3832 SavedRegs.reset(UnspilledCSGPR); 3833 ExtraCSSpill = AArch64::NoRegister; 3834 } 3835 } else 3836 SavedRegs.set(UnspilledCSGPRPaired); 3837 } 3838 } 3839 3840 // If we didn't find an extra callee-saved register to spill, create 3841 // an emergency spill slot. 3842 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) { 3843 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 3844 const TargetRegisterClass &RC = AArch64::GPR64RegClass; 3845 unsigned Size = TRI->getSpillSize(RC); 3846 Align Alignment = TRI->getSpillAlign(RC); 3847 int FI = MFI.CreateStackObject(Size, Alignment, false); 3848 RS->addScavengingFrameIndex(FI); 3849 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI 3850 << " as the emergency spill slot.\n"); 3851 } 3852 } 3853 3854 // Adding the size of additional 64bit GPR saves. 3855 CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs); 3856 3857 // A Swift asynchronous context extends the frame record with a pointer 3858 // directly before FP. 3859 if (hasFP(MF) && AFI->hasSwiftAsyncContext()) 3860 CSStackSize += 8; 3861 3862 uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16); 3863 LLVM_DEBUG(dbgs() << "Estimated stack frame size: " 3864 << EstimatedStackSize + AlignedCSStackSize << " bytes.\n"); 3865 3866 assert((!MFI.isCalleeSavedInfoValid() || 3867 AFI->getCalleeSavedStackSize() == AlignedCSStackSize) && 3868 "Should not invalidate callee saved info"); 3869 3870 // Round up to register pair alignment to avoid additional SP adjustment 3871 // instructions. 3872 AFI->setCalleeSavedStackSize(AlignedCSStackSize); 3873 AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize); 3874 AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16)); 3875 } 3876 3877 bool AArch64FrameLowering::assignCalleeSavedSpillSlots( 3878 MachineFunction &MF, const TargetRegisterInfo *RegInfo, 3879 std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex, 3880 unsigned &MaxCSFrameIndex) const { 3881 bool NeedsWinCFI = needsWinCFI(MF); 3882 // To match the canonical windows frame layout, reverse the list of 3883 // callee saved registers to get them laid out by PrologEpilogInserter 3884 // in the right order. (PrologEpilogInserter allocates stack objects top 3885 // down. Windows canonical prologs store higher numbered registers at 3886 // the top, thus have the CSI array start from the highest registers.) 3887 if (NeedsWinCFI) 3888 std::reverse(CSI.begin(), CSI.end()); 3889 3890 if (CSI.empty()) 3891 return true; // Early exit if no callee saved registers are modified! 3892 3893 // Now that we know which registers need to be saved and restored, allocate 3894 // stack slots for them. 3895 MachineFrameInfo &MFI = MF.getFrameInfo(); 3896 auto *AFI = MF.getInfo<AArch64FunctionInfo>(); 3897 3898 bool UsesWinAAPCS = isTargetWindows(MF); 3899 if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) { 3900 int FrameIdx = MFI.CreateStackObject(8, Align(16), true); 3901 AFI->setSwiftAsyncContextFrameIdx(FrameIdx); 3902 if ((unsigned)FrameIdx < MinCSFrameIndex) 3903 MinCSFrameIndex = FrameIdx; 3904 if ((unsigned)FrameIdx > MaxCSFrameIndex) 3905 MaxCSFrameIndex = FrameIdx; 3906 } 3907 3908 // Insert VG into the list of CSRs, immediately before LR if saved. 3909 if (AFI->hasStreamingModeChanges()) { 3910 std::vector<CalleeSavedInfo> VGSaves; 3911 SMEAttrs Attrs(MF.getFunction()); 3912 3913 auto VGInfo = CalleeSavedInfo(AArch64::VG); 3914 VGInfo.setRestored(false); 3915 VGSaves.push_back(VGInfo); 3916 3917 // Add VG again if the function is locally-streaming, as we will spill two 3918 // values. 3919 if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface()) 3920 VGSaves.push_back(VGInfo); 3921 3922 bool InsertBeforeLR = false; 3923 3924 for (unsigned I = 0; I < CSI.size(); I++) 3925 if (CSI[I].getReg() == AArch64::LR) { 3926 InsertBeforeLR = true; 3927 CSI.insert(CSI.begin() + I, VGSaves.begin(), VGSaves.end()); 3928 break; 3929 } 3930 3931 if (!InsertBeforeLR) 3932 CSI.insert(CSI.end(), VGSaves.begin(), VGSaves.end()); 3933 } 3934 3935 Register LastReg = 0; 3936 int HazardSlotIndex = std::numeric_limits<int>::max(); 3937 for (auto &CS : CSI) { 3938 Register Reg = CS.getReg(); 3939 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 3940 3941 // Create a hazard slot as we switch between GPR and FPR CSRs. 3942 if (AFI->hasStackHazardSlotIndex() && 3943 (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) && 3944 AArch64InstrInfo::isFpOrNEON(Reg)) { 3945 assert(HazardSlotIndex == std::numeric_limits<int>::max() && 3946 "Unexpected register order for hazard slot"); 3947 HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true); 3948 LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex 3949 << "\n"); 3950 AFI->setStackHazardCSRSlotIndex(HazardSlotIndex); 3951 if ((unsigned)HazardSlotIndex < MinCSFrameIndex) 3952 MinCSFrameIndex = HazardSlotIndex; 3953 if ((unsigned)HazardSlotIndex > MaxCSFrameIndex) 3954 MaxCSFrameIndex = HazardSlotIndex; 3955 } 3956 3957 unsigned Size = RegInfo->getSpillSize(*RC); 3958 Align Alignment(RegInfo->getSpillAlign(*RC)); 3959 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true); 3960 CS.setFrameIdx(FrameIdx); 3961 3962 if ((unsigned)FrameIdx < MinCSFrameIndex) 3963 MinCSFrameIndex = FrameIdx; 3964 if ((unsigned)FrameIdx > MaxCSFrameIndex) 3965 MaxCSFrameIndex = FrameIdx; 3966 3967 // Grab 8 bytes below FP for the extended asynchronous frame info. 3968 if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS && 3969 Reg == AArch64::FP) { 3970 FrameIdx = MFI.CreateStackObject(8, Alignment, true); 3971 AFI->setSwiftAsyncContextFrameIdx(FrameIdx); 3972 if ((unsigned)FrameIdx < MinCSFrameIndex) 3973 MinCSFrameIndex = FrameIdx; 3974 if ((unsigned)FrameIdx > MaxCSFrameIndex) 3975 MaxCSFrameIndex = FrameIdx; 3976 } 3977 LastReg = Reg; 3978 } 3979 3980 // Add hazard slot in the case where no FPR CSRs are present. 3981 if (AFI->hasStackHazardSlotIndex() && 3982 HazardSlotIndex == std::numeric_limits<int>::max()) { 3983 HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true); 3984 LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex 3985 << "\n"); 3986 AFI->setStackHazardCSRSlotIndex(HazardSlotIndex); 3987 if ((unsigned)HazardSlotIndex < MinCSFrameIndex) 3988 MinCSFrameIndex = HazardSlotIndex; 3989 if ((unsigned)HazardSlotIndex > MaxCSFrameIndex) 3990 MaxCSFrameIndex = HazardSlotIndex; 3991 } 3992 3993 return true; 3994 } 3995 3996 bool AArch64FrameLowering::enableStackSlotScavenging( 3997 const MachineFunction &MF) const { 3998 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 3999 // If the function has streaming-mode changes, don't scavenge a 4000 // spillslot in the callee-save area, as that might require an 4001 // 'addvl' in the streaming-mode-changing call-sequence when the 4002 // function doesn't use a FP. 4003 if (AFI->hasStreamingModeChanges() && !hasFP(MF)) 4004 return false; 4005 // Don't allow register salvaging with hazard slots, in case it moves objects 4006 // into the wrong place. 4007 if (AFI->hasStackHazardSlotIndex()) 4008 return false; 4009 return AFI->hasCalleeSaveStackFreeSpace(); 4010 } 4011 4012 /// returns true if there are any SVE callee saves. 4013 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI, 4014 int &Min, int &Max) { 4015 Min = std::numeric_limits<int>::max(); 4016 Max = std::numeric_limits<int>::min(); 4017 4018 if (!MFI.isCalleeSavedInfoValid()) 4019 return false; 4020 4021 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 4022 for (auto &CS : CSI) { 4023 if (AArch64::ZPRRegClass.contains(CS.getReg()) || 4024 AArch64::PPRRegClass.contains(CS.getReg())) { 4025 assert((Max == std::numeric_limits<int>::min() || 4026 Max + 1 == CS.getFrameIdx()) && 4027 "SVE CalleeSaves are not consecutive"); 4028 4029 Min = std::min(Min, CS.getFrameIdx()); 4030 Max = std::max(Max, CS.getFrameIdx()); 4031 } 4032 } 4033 return Min != std::numeric_limits<int>::max(); 4034 } 4035 4036 // Process all the SVE stack objects and determine offsets for each 4037 // object. If AssignOffsets is true, the offsets get assigned. 4038 // Fills in the first and last callee-saved frame indices into 4039 // Min/MaxCSFrameIndex, respectively. 4040 // Returns the size of the stack. 4041 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI, 4042 int &MinCSFrameIndex, 4043 int &MaxCSFrameIndex, 4044 bool AssignOffsets) { 4045 #ifndef NDEBUG 4046 // First process all fixed stack objects. 4047 for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) 4048 assert(MFI.getStackID(I) != TargetStackID::ScalableVector && 4049 "SVE vectors should never be passed on the stack by value, only by " 4050 "reference."); 4051 #endif 4052 4053 auto Assign = [&MFI](int FI, int64_t Offset) { 4054 LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n"); 4055 MFI.setObjectOffset(FI, Offset); 4056 }; 4057 4058 int64_t Offset = 0; 4059 4060 // Then process all callee saved slots. 4061 if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) { 4062 // Assign offsets to the callee save slots. 4063 for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) { 4064 Offset += MFI.getObjectSize(I); 4065 Offset = alignTo(Offset, MFI.getObjectAlign(I)); 4066 if (AssignOffsets) 4067 Assign(I, -Offset); 4068 } 4069 } 4070 4071 // Ensure that the Callee-save area is aligned to 16bytes. 4072 Offset = alignTo(Offset, Align(16U)); 4073 4074 // Create a buffer of SVE objects to allocate and sort it. 4075 SmallVector<int, 8> ObjectsToAllocate; 4076 // If we have a stack protector, and we've previously decided that we have SVE 4077 // objects on the stack and thus need it to go in the SVE stack area, then it 4078 // needs to go first. 4079 int StackProtectorFI = -1; 4080 if (MFI.hasStackProtectorIndex()) { 4081 StackProtectorFI = MFI.getStackProtectorIndex(); 4082 if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector) 4083 ObjectsToAllocate.push_back(StackProtectorFI); 4084 } 4085 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) { 4086 unsigned StackID = MFI.getStackID(I); 4087 if (StackID != TargetStackID::ScalableVector) 4088 continue; 4089 if (I == StackProtectorFI) 4090 continue; 4091 if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex) 4092 continue; 4093 if (MFI.isDeadObjectIndex(I)) 4094 continue; 4095 4096 ObjectsToAllocate.push_back(I); 4097 } 4098 4099 // Allocate all SVE locals and spills 4100 for (unsigned FI : ObjectsToAllocate) { 4101 Align Alignment = MFI.getObjectAlign(FI); 4102 // FIXME: Given that the length of SVE vectors is not necessarily a power of 4103 // two, we'd need to align every object dynamically at runtime if the 4104 // alignment is larger than 16. This is not yet supported. 4105 if (Alignment > Align(16)) 4106 report_fatal_error( 4107 "Alignment of scalable vectors > 16 bytes is not yet supported"); 4108 4109 Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment); 4110 if (AssignOffsets) 4111 Assign(FI, -Offset); 4112 } 4113 4114 return Offset; 4115 } 4116 4117 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets( 4118 MachineFrameInfo &MFI) const { 4119 int MinCSFrameIndex, MaxCSFrameIndex; 4120 return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false); 4121 } 4122 4123 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets( 4124 MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const { 4125 return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, 4126 true); 4127 } 4128 4129 void AArch64FrameLowering::processFunctionBeforeFrameFinalized( 4130 MachineFunction &MF, RegScavenger *RS) const { 4131 MachineFrameInfo &MFI = MF.getFrameInfo(); 4132 4133 assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown && 4134 "Upwards growing stack unsupported"); 4135 4136 int MinCSFrameIndex, MaxCSFrameIndex; 4137 int64_t SVEStackSize = 4138 assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex); 4139 4140 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 4141 AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U)); 4142 AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex); 4143 4144 // If this function isn't doing Win64-style C++ EH, we don't need to do 4145 // anything. 4146 if (!MF.hasEHFunclets()) 4147 return; 4148 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 4149 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo(); 4150 4151 MachineBasicBlock &MBB = MF.front(); 4152 auto MBBI = MBB.begin(); 4153 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) 4154 ++MBBI; 4155 4156 // Create an UnwindHelp object. 4157 // The UnwindHelp object is allocated at the start of the fixed object area 4158 int64_t FixedObject = 4159 getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false); 4160 int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8, 4161 /*SPOffset*/ -FixedObject, 4162 /*IsImmutable=*/false); 4163 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI; 4164 4165 // We need to store -2 into the UnwindHelp object at the start of the 4166 // function. 4167 DebugLoc DL; 4168 RS->enterBasicBlockEnd(MBB); 4169 RS->backward(MBBI); 4170 Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass); 4171 assert(DstReg && "There must be a free register after frame setup"); 4172 BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2); 4173 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi)) 4174 .addReg(DstReg, getKillRegState(true)) 4175 .addFrameIndex(UnwindHelpFI) 4176 .addImm(0); 4177 } 4178 4179 namespace { 4180 struct TagStoreInstr { 4181 MachineInstr *MI; 4182 int64_t Offset, Size; 4183 explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size) 4184 : MI(MI), Offset(Offset), Size(Size) {} 4185 }; 4186 4187 class TagStoreEdit { 4188 MachineFunction *MF; 4189 MachineBasicBlock *MBB; 4190 MachineRegisterInfo *MRI; 4191 // Tag store instructions that are being replaced. 4192 SmallVector<TagStoreInstr, 8> TagStores; 4193 // Combined memref arguments of the above instructions. 4194 SmallVector<MachineMemOperand *, 8> CombinedMemRefs; 4195 4196 // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg + 4197 // FrameRegOffset + Size) with the address tag of SP. 4198 Register FrameReg; 4199 StackOffset FrameRegOffset; 4200 int64_t Size; 4201 // If not std::nullopt, move FrameReg to (FrameReg + FrameRegUpdate) at the 4202 // end. 4203 std::optional<int64_t> FrameRegUpdate; 4204 // MIFlags for any FrameReg updating instructions. 4205 unsigned FrameRegUpdateFlags; 4206 4207 // Use zeroing instruction variants. 4208 bool ZeroData; 4209 DebugLoc DL; 4210 4211 void emitUnrolled(MachineBasicBlock::iterator InsertI); 4212 void emitLoop(MachineBasicBlock::iterator InsertI); 4213 4214 public: 4215 TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData) 4216 : MBB(MBB), ZeroData(ZeroData) { 4217 MF = MBB->getParent(); 4218 MRI = &MF->getRegInfo(); 4219 } 4220 // Add an instruction to be replaced. Instructions must be added in the 4221 // ascending order of Offset, and have to be adjacent. 4222 void addInstruction(TagStoreInstr I) { 4223 assert((TagStores.empty() || 4224 TagStores.back().Offset + TagStores.back().Size == I.Offset) && 4225 "Non-adjacent tag store instructions."); 4226 TagStores.push_back(I); 4227 } 4228 void clear() { TagStores.clear(); } 4229 // Emit equivalent code at the given location, and erase the current set of 4230 // instructions. May skip if the replacement is not profitable. May invalidate 4231 // the input iterator and replace it with a valid one. 4232 void emitCode(MachineBasicBlock::iterator &InsertI, 4233 const AArch64FrameLowering *TFI, bool TryMergeSPUpdate); 4234 }; 4235 4236 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) { 4237 const AArch64InstrInfo *TII = 4238 MF->getSubtarget<AArch64Subtarget>().getInstrInfo(); 4239 4240 const int64_t kMinOffset = -256 * 16; 4241 const int64_t kMaxOffset = 255 * 16; 4242 4243 Register BaseReg = FrameReg; 4244 int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed(); 4245 if (BaseRegOffsetBytes < kMinOffset || 4246 BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset || 4247 // BaseReg can be FP, which is not necessarily aligned to 16-bytes. In 4248 // that case, BaseRegOffsetBytes will not be aligned to 16 bytes, which 4249 // is required for the offset of ST2G. 4250 BaseRegOffsetBytes % 16 != 0) { 4251 Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass); 4252 emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg, 4253 StackOffset::getFixed(BaseRegOffsetBytes), TII); 4254 BaseReg = ScratchReg; 4255 BaseRegOffsetBytes = 0; 4256 } 4257 4258 MachineInstr *LastI = nullptr; 4259 while (Size) { 4260 int64_t InstrSize = (Size > 16) ? 32 : 16; 4261 unsigned Opcode = 4262 InstrSize == 16 4263 ? (ZeroData ? AArch64::STZGi : AArch64::STGi) 4264 : (ZeroData ? AArch64::STZ2Gi : AArch64::ST2Gi); 4265 assert(BaseRegOffsetBytes % 16 == 0); 4266 MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode)) 4267 .addReg(AArch64::SP) 4268 .addReg(BaseReg) 4269 .addImm(BaseRegOffsetBytes / 16) 4270 .setMemRefs(CombinedMemRefs); 4271 // A store to [BaseReg, #0] should go last for an opportunity to fold the 4272 // final SP adjustment in the epilogue. 4273 if (BaseRegOffsetBytes == 0) 4274 LastI = I; 4275 BaseRegOffsetBytes += InstrSize; 4276 Size -= InstrSize; 4277 } 4278 4279 if (LastI) 4280 MBB->splice(InsertI, MBB, LastI); 4281 } 4282 4283 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) { 4284 const AArch64InstrInfo *TII = 4285 MF->getSubtarget<AArch64Subtarget>().getInstrInfo(); 4286 4287 Register BaseReg = FrameRegUpdate 4288 ? FrameReg 4289 : MRI->createVirtualRegister(&AArch64::GPR64RegClass); 4290 Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass); 4291 4292 emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII); 4293 4294 int64_t LoopSize = Size; 4295 // If the loop size is not a multiple of 32, split off one 16-byte store at 4296 // the end to fold BaseReg update into. 4297 if (FrameRegUpdate && *FrameRegUpdate) 4298 LoopSize -= LoopSize % 32; 4299 MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL, 4300 TII->get(ZeroData ? AArch64::STZGloop_wback 4301 : AArch64::STGloop_wback)) 4302 .addDef(SizeReg) 4303 .addDef(BaseReg) 4304 .addImm(LoopSize) 4305 .addReg(BaseReg) 4306 .setMemRefs(CombinedMemRefs); 4307 if (FrameRegUpdate) 4308 LoopI->setFlags(FrameRegUpdateFlags); 4309 4310 int64_t ExtraBaseRegUpdate = 4311 FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0; 4312 if (LoopSize < Size) { 4313 assert(FrameRegUpdate); 4314 assert(Size - LoopSize == 16); 4315 // Tag 16 more bytes at BaseReg and update BaseReg. 4316 BuildMI(*MBB, InsertI, DL, 4317 TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex)) 4318 .addDef(BaseReg) 4319 .addReg(BaseReg) 4320 .addReg(BaseReg) 4321 .addImm(1 + ExtraBaseRegUpdate / 16) 4322 .setMemRefs(CombinedMemRefs) 4323 .setMIFlags(FrameRegUpdateFlags); 4324 } else if (ExtraBaseRegUpdate) { 4325 // Update BaseReg. 4326 BuildMI( 4327 *MBB, InsertI, DL, 4328 TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri)) 4329 .addDef(BaseReg) 4330 .addReg(BaseReg) 4331 .addImm(std::abs(ExtraBaseRegUpdate)) 4332 .addImm(0) 4333 .setMIFlags(FrameRegUpdateFlags); 4334 } 4335 } 4336 4337 // Check if *II is a register update that can be merged into STGloop that ends 4338 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the 4339 // end of the loop. 4340 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg, 4341 int64_t Size, int64_t *TotalOffset) { 4342 MachineInstr &MI = *II; 4343 if ((MI.getOpcode() == AArch64::ADDXri || 4344 MI.getOpcode() == AArch64::SUBXri) && 4345 MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) { 4346 unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm()); 4347 int64_t Offset = MI.getOperand(2).getImm() << Shift; 4348 if (MI.getOpcode() == AArch64::SUBXri) 4349 Offset = -Offset; 4350 int64_t AbsPostOffset = std::abs(Offset - Size); 4351 const int64_t kMaxOffset = 4352 0xFFF; // Max encoding for unshifted ADDXri / SUBXri 4353 if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) { 4354 *TotalOffset = Offset; 4355 return true; 4356 } 4357 } 4358 return false; 4359 } 4360 4361 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE, 4362 SmallVectorImpl<MachineMemOperand *> &MemRefs) { 4363 MemRefs.clear(); 4364 for (auto &TS : TSE) { 4365 MachineInstr *MI = TS.MI; 4366 // An instruction without memory operands may access anything. Be 4367 // conservative and return an empty list. 4368 if (MI->memoperands_empty()) { 4369 MemRefs.clear(); 4370 return; 4371 } 4372 MemRefs.append(MI->memoperands_begin(), MI->memoperands_end()); 4373 } 4374 } 4375 4376 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI, 4377 const AArch64FrameLowering *TFI, 4378 bool TryMergeSPUpdate) { 4379 if (TagStores.empty()) 4380 return; 4381 TagStoreInstr &FirstTagStore = TagStores[0]; 4382 TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1]; 4383 Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size; 4384 DL = TagStores[0].MI->getDebugLoc(); 4385 4386 Register Reg; 4387 FrameRegOffset = TFI->resolveFrameOffsetReference( 4388 *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg, 4389 /*PreferFP=*/false, /*ForSimm=*/true); 4390 FrameReg = Reg; 4391 FrameRegUpdate = std::nullopt; 4392 4393 mergeMemRefs(TagStores, CombinedMemRefs); 4394 4395 LLVM_DEBUG({ 4396 dbgs() << "Replacing adjacent STG instructions:\n"; 4397 for (const auto &Instr : TagStores) { 4398 dbgs() << " " << *Instr.MI; 4399 } 4400 }); 4401 4402 // Size threshold where a loop becomes shorter than a linear sequence of 4403 // tagging instructions. 4404 const int kSetTagLoopThreshold = 176; 4405 if (Size < kSetTagLoopThreshold) { 4406 if (TagStores.size() < 2) 4407 return; 4408 emitUnrolled(InsertI); 4409 } else { 4410 MachineInstr *UpdateInstr = nullptr; 4411 int64_t TotalOffset = 0; 4412 if (TryMergeSPUpdate) { 4413 // See if we can merge base register update into the STGloop. 4414 // This is done in AArch64LoadStoreOptimizer for "normal" stores, 4415 // but STGloop is way too unusual for that, and also it only 4416 // realistically happens in function epilogue. Also, STGloop is expanded 4417 // before that pass. 4418 if (InsertI != MBB->end() && 4419 canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size, 4420 &TotalOffset)) { 4421 UpdateInstr = &*InsertI++; 4422 LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n " 4423 << *UpdateInstr); 4424 } 4425 } 4426 4427 if (!UpdateInstr && TagStores.size() < 2) 4428 return; 4429 4430 if (UpdateInstr) { 4431 FrameRegUpdate = TotalOffset; 4432 FrameRegUpdateFlags = UpdateInstr->getFlags(); 4433 } 4434 emitLoop(InsertI); 4435 if (UpdateInstr) 4436 UpdateInstr->eraseFromParent(); 4437 } 4438 4439 for (auto &TS : TagStores) 4440 TS.MI->eraseFromParent(); 4441 } 4442 4443 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset, 4444 int64_t &Size, bool &ZeroData) { 4445 MachineFunction &MF = *MI.getParent()->getParent(); 4446 const MachineFrameInfo &MFI = MF.getFrameInfo(); 4447 4448 unsigned Opcode = MI.getOpcode(); 4449 ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGi || 4450 Opcode == AArch64::STZ2Gi); 4451 4452 if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) { 4453 if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead()) 4454 return false; 4455 if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI()) 4456 return false; 4457 Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex()); 4458 Size = MI.getOperand(2).getImm(); 4459 return true; 4460 } 4461 4462 if (Opcode == AArch64::STGi || Opcode == AArch64::STZGi) 4463 Size = 16; 4464 else if (Opcode == AArch64::ST2Gi || Opcode == AArch64::STZ2Gi) 4465 Size = 32; 4466 else 4467 return false; 4468 4469 if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI()) 4470 return false; 4471 4472 Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) + 4473 16 * MI.getOperand(2).getImm(); 4474 return true; 4475 } 4476 4477 // Detect a run of memory tagging instructions for adjacent stack frame slots, 4478 // and replace them with a shorter instruction sequence: 4479 // * replace STG + STG with ST2G 4480 // * replace STGloop + STGloop with STGloop 4481 // This code needs to run when stack slot offsets are already known, but before 4482 // FrameIndex operands in STG instructions are eliminated. 4483 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II, 4484 const AArch64FrameLowering *TFI, 4485 RegScavenger *RS) { 4486 bool FirstZeroData; 4487 int64_t Size, Offset; 4488 MachineInstr &MI = *II; 4489 MachineBasicBlock *MBB = MI.getParent(); 4490 MachineBasicBlock::iterator NextI = ++II; 4491 if (&MI == &MBB->instr_back()) 4492 return II; 4493 if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData)) 4494 return II; 4495 4496 SmallVector<TagStoreInstr, 4> Instrs; 4497 Instrs.emplace_back(&MI, Offset, Size); 4498 4499 constexpr int kScanLimit = 10; 4500 int Count = 0; 4501 for (MachineBasicBlock::iterator E = MBB->end(); 4502 NextI != E && Count < kScanLimit; ++NextI) { 4503 MachineInstr &MI = *NextI; 4504 bool ZeroData; 4505 int64_t Size, Offset; 4506 // Collect instructions that update memory tags with a FrameIndex operand 4507 // and (when applicable) constant size, and whose output registers are dead 4508 // (the latter is almost always the case in practice). Since these 4509 // instructions effectively have no inputs or outputs, we are free to skip 4510 // any non-aliasing instructions in between without tracking used registers. 4511 if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) { 4512 if (ZeroData != FirstZeroData) 4513 break; 4514 Instrs.emplace_back(&MI, Offset, Size); 4515 continue; 4516 } 4517 4518 // Only count non-transient, non-tagging instructions toward the scan 4519 // limit. 4520 if (!MI.isTransient()) 4521 ++Count; 4522 4523 // Just in case, stop before the epilogue code starts. 4524 if (MI.getFlag(MachineInstr::FrameSetup) || 4525 MI.getFlag(MachineInstr::FrameDestroy)) 4526 break; 4527 4528 // Reject anything that may alias the collected instructions. 4529 if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects()) 4530 break; 4531 } 4532 4533 // New code will be inserted after the last tagging instruction we've found. 4534 MachineBasicBlock::iterator InsertI = Instrs.back().MI; 4535 4536 // All the gathered stack tag instructions are merged and placed after 4537 // last tag store in the list. The check should be made if the nzcv 4538 // flag is live at the point where we are trying to insert. Otherwise 4539 // the nzcv flag might get clobbered if any stg loops are present. 4540 4541 // FIXME : This approach of bailing out from merge is conservative in 4542 // some ways like even if stg loops are not present after merge the 4543 // insert list, this liveness check is done (which is not needed). 4544 LivePhysRegs LiveRegs(*(MBB->getParent()->getSubtarget().getRegisterInfo())); 4545 LiveRegs.addLiveOuts(*MBB); 4546 for (auto I = MBB->rbegin();; ++I) { 4547 MachineInstr &MI = *I; 4548 if (MI == InsertI) 4549 break; 4550 LiveRegs.stepBackward(*I); 4551 } 4552 InsertI++; 4553 if (LiveRegs.contains(AArch64::NZCV)) 4554 return InsertI; 4555 4556 llvm::stable_sort(Instrs, 4557 [](const TagStoreInstr &Left, const TagStoreInstr &Right) { 4558 return Left.Offset < Right.Offset; 4559 }); 4560 4561 // Make sure that we don't have any overlapping stores. 4562 int64_t CurOffset = Instrs[0].Offset; 4563 for (auto &Instr : Instrs) { 4564 if (CurOffset > Instr.Offset) 4565 return NextI; 4566 CurOffset = Instr.Offset + Instr.Size; 4567 } 4568 4569 // Find contiguous runs of tagged memory and emit shorter instruction 4570 // sequencies for them when possible. 4571 TagStoreEdit TSE(MBB, FirstZeroData); 4572 std::optional<int64_t> EndOffset; 4573 for (auto &Instr : Instrs) { 4574 if (EndOffset && *EndOffset != Instr.Offset) { 4575 // Found a gap. 4576 TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false); 4577 TSE.clear(); 4578 } 4579 4580 TSE.addInstruction(Instr); 4581 EndOffset = Instr.Offset + Instr.Size; 4582 } 4583 4584 const MachineFunction *MF = MBB->getParent(); 4585 // Multiple FP/SP updates in a loop cannot be described by CFI instructions. 4586 TSE.emitCode( 4587 InsertI, TFI, /*TryMergeSPUpdate = */ 4588 !MF->getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(*MF)); 4589 4590 return InsertI; 4591 } 4592 } // namespace 4593 4594 MachineBasicBlock::iterator emitVGSaveRestore(MachineBasicBlock::iterator II, 4595 const AArch64FrameLowering *TFI) { 4596 MachineInstr &MI = *II; 4597 MachineBasicBlock *MBB = MI.getParent(); 4598 MachineFunction *MF = MBB->getParent(); 4599 4600 if (MI.getOpcode() != AArch64::VGSavePseudo && 4601 MI.getOpcode() != AArch64::VGRestorePseudo) 4602 return II; 4603 4604 SMEAttrs FuncAttrs(MF->getFunction()); 4605 bool LocallyStreaming = 4606 FuncAttrs.hasStreamingBody() && !FuncAttrs.hasStreamingInterface(); 4607 const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>(); 4608 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 4609 const AArch64InstrInfo *TII = 4610 MF->getSubtarget<AArch64Subtarget>().getInstrInfo(); 4611 4612 int64_t VGFrameIdx = 4613 LocallyStreaming ? AFI->getStreamingVGIdx() : AFI->getVGIdx(); 4614 assert(VGFrameIdx != std::numeric_limits<int>::max() && 4615 "Expected FrameIdx for VG"); 4616 4617 unsigned CFIIndex; 4618 if (MI.getOpcode() == AArch64::VGSavePseudo) { 4619 const MachineFrameInfo &MFI = MF->getFrameInfo(); 4620 int64_t Offset = 4621 MFI.getObjectOffset(VGFrameIdx) - TFI->getOffsetOfLocalArea(); 4622 CFIIndex = MF->addFrameInst(MCCFIInstruction::createOffset( 4623 nullptr, TRI->getDwarfRegNum(AArch64::VG, true), Offset)); 4624 } else 4625 CFIIndex = MF->addFrameInst(MCCFIInstruction::createRestore( 4626 nullptr, TRI->getDwarfRegNum(AArch64::VG, true))); 4627 4628 MachineInstr *UnwindInst = BuildMI(*MBB, II, II->getDebugLoc(), 4629 TII->get(TargetOpcode::CFI_INSTRUCTION)) 4630 .addCFIIndex(CFIIndex); 4631 4632 MI.eraseFromParent(); 4633 return UnwindInst->getIterator(); 4634 } 4635 4636 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced( 4637 MachineFunction &MF, RegScavenger *RS = nullptr) const { 4638 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 4639 for (auto &BB : MF) 4640 for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();) { 4641 if (AFI->hasStreamingModeChanges()) 4642 II = emitVGSaveRestore(II, this); 4643 if (StackTaggingMergeSetTag) 4644 II = tryMergeAdjacentSTG(II, this, RS); 4645 } 4646 } 4647 4648 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP 4649 /// before the update. This is easily retrieved as it is exactly the offset 4650 /// that is set in processFunctionBeforeFrameFinalized. 4651 StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP( 4652 const MachineFunction &MF, int FI, Register &FrameReg, 4653 bool IgnoreSPUpdates) const { 4654 const MachineFrameInfo &MFI = MF.getFrameInfo(); 4655 if (IgnoreSPUpdates) { 4656 LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is " 4657 << MFI.getObjectOffset(FI) << "\n"); 4658 FrameReg = AArch64::SP; 4659 return StackOffset::getFixed(MFI.getObjectOffset(FI)); 4660 } 4661 4662 // Go to common code if we cannot provide sp + offset. 4663 if (MFI.hasVarSizedObjects() || 4664 MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() || 4665 MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF)) 4666 return getFrameIndexReference(MF, FI, FrameReg); 4667 4668 FrameReg = AArch64::SP; 4669 return getStackOffset(MF, MFI.getObjectOffset(FI)); 4670 } 4671 4672 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve 4673 /// the parent's frame pointer 4674 unsigned AArch64FrameLowering::getWinEHParentFrameOffset( 4675 const MachineFunction &MF) const { 4676 return 0; 4677 } 4678 4679 /// Funclets only need to account for space for the callee saved registers, 4680 /// as the locals are accounted for in the parent's stack frame. 4681 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize( 4682 const MachineFunction &MF) const { 4683 // This is the size of the pushed CSRs. 4684 unsigned CSSize = 4685 MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize(); 4686 // This is the amount of stack a funclet needs to allocate. 4687 return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(), 4688 getStackAlign()); 4689 } 4690 4691 namespace { 4692 struct FrameObject { 4693 bool IsValid = false; 4694 // Index of the object in MFI. 4695 int ObjectIndex = 0; 4696 // Group ID this object belongs to. 4697 int GroupIndex = -1; 4698 // This object should be placed first (closest to SP). 4699 bool ObjectFirst = false; 4700 // This object's group (which always contains the object with 4701 // ObjectFirst==true) should be placed first. 4702 bool GroupFirst = false; 4703 4704 // Used to distinguish between FP and GPR accesses. The values are decided so 4705 // that they sort FPR < Hazard < GPR and they can be or'd together. 4706 unsigned Accesses = 0; 4707 enum { AccessFPR = 1, AccessHazard = 2, AccessGPR = 4 }; 4708 }; 4709 4710 class GroupBuilder { 4711 SmallVector<int, 8> CurrentMembers; 4712 int NextGroupIndex = 0; 4713 std::vector<FrameObject> &Objects; 4714 4715 public: 4716 GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {} 4717 void AddMember(int Index) { CurrentMembers.push_back(Index); } 4718 void EndCurrentGroup() { 4719 if (CurrentMembers.size() > 1) { 4720 // Create a new group with the current member list. This might remove them 4721 // from their pre-existing groups. That's OK, dealing with overlapping 4722 // groups is too hard and unlikely to make a difference. 4723 LLVM_DEBUG(dbgs() << "group:"); 4724 for (int Index : CurrentMembers) { 4725 Objects[Index].GroupIndex = NextGroupIndex; 4726 LLVM_DEBUG(dbgs() << " " << Index); 4727 } 4728 LLVM_DEBUG(dbgs() << "\n"); 4729 NextGroupIndex++; 4730 } 4731 CurrentMembers.clear(); 4732 } 4733 }; 4734 4735 bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) { 4736 // Objects at a lower index are closer to FP; objects at a higher index are 4737 // closer to SP. 4738 // 4739 // For consistency in our comparison, all invalid objects are placed 4740 // at the end. This also allows us to stop walking when we hit the 4741 // first invalid item after it's all sorted. 4742 // 4743 // If we want to include a stack hazard region, order FPR accesses < the 4744 // hazard object < GPRs accesses in order to create a separation between the 4745 // two. For the Accesses field 1 = FPR, 2 = Hazard Object, 4 = GPR. 4746 // 4747 // Otherwise the "first" object goes first (closest to SP), followed by the 4748 // members of the "first" group. 4749 // 4750 // The rest are sorted by the group index to keep the groups together. 4751 // Higher numbered groups are more likely to be around longer (i.e. untagged 4752 // in the function epilogue and not at some earlier point). Place them closer 4753 // to SP. 4754 // 4755 // If all else equal, sort by the object index to keep the objects in the 4756 // original order. 4757 return std::make_tuple(!A.IsValid, A.Accesses, A.ObjectFirst, A.GroupFirst, 4758 A.GroupIndex, A.ObjectIndex) < 4759 std::make_tuple(!B.IsValid, B.Accesses, B.ObjectFirst, B.GroupFirst, 4760 B.GroupIndex, B.ObjectIndex); 4761 } 4762 } // namespace 4763 4764 void AArch64FrameLowering::orderFrameObjects( 4765 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const { 4766 if (!OrderFrameObjects || ObjectsToAllocate.empty()) 4767 return; 4768 4769 const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>(); 4770 const MachineFrameInfo &MFI = MF.getFrameInfo(); 4771 std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd()); 4772 for (auto &Obj : ObjectsToAllocate) { 4773 FrameObjects[Obj].IsValid = true; 4774 FrameObjects[Obj].ObjectIndex = Obj; 4775 } 4776 4777 // Identify FPR vs GPR slots for hazards, and stack slots that are tagged at 4778 // the same time. 4779 GroupBuilder GB(FrameObjects); 4780 for (auto &MBB : MF) { 4781 for (auto &MI : MBB) { 4782 if (MI.isDebugInstr()) 4783 continue; 4784 4785 if (AFI.hasStackHazardSlotIndex()) { 4786 std::optional<int> FI = getLdStFrameID(MI, MFI); 4787 if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) { 4788 if (MFI.getStackID(*FI) == TargetStackID::ScalableVector || 4789 AArch64InstrInfo::isFpOrNEON(MI)) 4790 FrameObjects[*FI].Accesses |= FrameObject::AccessFPR; 4791 else 4792 FrameObjects[*FI].Accesses |= FrameObject::AccessGPR; 4793 } 4794 } 4795 4796 int OpIndex; 4797 switch (MI.getOpcode()) { 4798 case AArch64::STGloop: 4799 case AArch64::STZGloop: 4800 OpIndex = 3; 4801 break; 4802 case AArch64::STGi: 4803 case AArch64::STZGi: 4804 case AArch64::ST2Gi: 4805 case AArch64::STZ2Gi: 4806 OpIndex = 1; 4807 break; 4808 default: 4809 OpIndex = -1; 4810 } 4811 4812 int TaggedFI = -1; 4813 if (OpIndex >= 0) { 4814 const MachineOperand &MO = MI.getOperand(OpIndex); 4815 if (MO.isFI()) { 4816 int FI = MO.getIndex(); 4817 if (FI >= 0 && FI < MFI.getObjectIndexEnd() && 4818 FrameObjects[FI].IsValid) 4819 TaggedFI = FI; 4820 } 4821 } 4822 4823 // If this is a stack tagging instruction for a slot that is not part of a 4824 // group yet, either start a new group or add it to the current one. 4825 if (TaggedFI >= 0) 4826 GB.AddMember(TaggedFI); 4827 else 4828 GB.EndCurrentGroup(); 4829 } 4830 // Groups should never span multiple basic blocks. 4831 GB.EndCurrentGroup(); 4832 } 4833 4834 if (AFI.hasStackHazardSlotIndex()) { 4835 FrameObjects[AFI.getStackHazardSlotIndex()].Accesses = 4836 FrameObject::AccessHazard; 4837 // If a stack object is unknown or both GPR and FPR, sort it into GPR. 4838 for (auto &Obj : FrameObjects) 4839 if (!Obj.Accesses || 4840 Obj.Accesses == (FrameObject::AccessGPR | FrameObject::AccessFPR)) 4841 Obj.Accesses = FrameObject::AccessGPR; 4842 } 4843 4844 // If the function's tagged base pointer is pinned to a stack slot, we want to 4845 // put that slot first when possible. This will likely place it at SP + 0, 4846 // and save one instruction when generating the base pointer because IRG does 4847 // not allow an immediate offset. 4848 std::optional<int> TBPI = AFI.getTaggedBasePointerIndex(); 4849 if (TBPI) { 4850 FrameObjects[*TBPI].ObjectFirst = true; 4851 FrameObjects[*TBPI].GroupFirst = true; 4852 int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex; 4853 if (FirstGroupIndex >= 0) 4854 for (FrameObject &Object : FrameObjects) 4855 if (Object.GroupIndex == FirstGroupIndex) 4856 Object.GroupFirst = true; 4857 } 4858 4859 llvm::stable_sort(FrameObjects, FrameObjectCompare); 4860 4861 int i = 0; 4862 for (auto &Obj : FrameObjects) { 4863 // All invalid items are sorted at the end, so it's safe to stop. 4864 if (!Obj.IsValid) 4865 break; 4866 ObjectsToAllocate[i++] = Obj.ObjectIndex; 4867 } 4868 4869 LLVM_DEBUG({ 4870 dbgs() << "Final frame order:\n"; 4871 for (auto &Obj : FrameObjects) { 4872 if (!Obj.IsValid) 4873 break; 4874 dbgs() << " " << Obj.ObjectIndex << ": group " << Obj.GroupIndex; 4875 if (Obj.ObjectFirst) 4876 dbgs() << ", first"; 4877 if (Obj.GroupFirst) 4878 dbgs() << ", group-first"; 4879 dbgs() << "\n"; 4880 } 4881 }); 4882 } 4883 4884 /// Emit a loop to decrement SP until it is equal to TargetReg, with probes at 4885 /// least every ProbeSize bytes. Returns an iterator of the first instruction 4886 /// after the loop. The difference between SP and TargetReg must be an exact 4887 /// multiple of ProbeSize. 4888 MachineBasicBlock::iterator 4889 AArch64FrameLowering::inlineStackProbeLoopExactMultiple( 4890 MachineBasicBlock::iterator MBBI, int64_t ProbeSize, 4891 Register TargetReg) const { 4892 MachineBasicBlock &MBB = *MBBI->getParent(); 4893 MachineFunction &MF = *MBB.getParent(); 4894 const AArch64InstrInfo *TII = 4895 MF.getSubtarget<AArch64Subtarget>().getInstrInfo(); 4896 DebugLoc DL = MBB.findDebugLoc(MBBI); 4897 4898 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator()); 4899 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 4900 MF.insert(MBBInsertPoint, LoopMBB); 4901 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 4902 MF.insert(MBBInsertPoint, ExitMBB); 4903 4904 // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not encodable 4905 // in SUB). 4906 emitFrameOffset(*LoopMBB, LoopMBB->end(), DL, AArch64::SP, AArch64::SP, 4907 StackOffset::getFixed(-ProbeSize), TII, 4908 MachineInstr::FrameSetup); 4909 // STR XZR, [SP] 4910 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::STRXui)) 4911 .addReg(AArch64::XZR) 4912 .addReg(AArch64::SP) 4913 .addImm(0) 4914 .setMIFlags(MachineInstr::FrameSetup); 4915 // CMP SP, TargetReg 4916 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::SUBSXrx64), 4917 AArch64::XZR) 4918 .addReg(AArch64::SP) 4919 .addReg(TargetReg) 4920 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0)) 4921 .setMIFlags(MachineInstr::FrameSetup); 4922 // B.CC Loop 4923 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::Bcc)) 4924 .addImm(AArch64CC::NE) 4925 .addMBB(LoopMBB) 4926 .setMIFlags(MachineInstr::FrameSetup); 4927 4928 LoopMBB->addSuccessor(ExitMBB); 4929 LoopMBB->addSuccessor(LoopMBB); 4930 // Synthesize the exit MBB. 4931 ExitMBB->splice(ExitMBB->end(), &MBB, MBBI, MBB.end()); 4932 ExitMBB->transferSuccessorsAndUpdatePHIs(&MBB); 4933 MBB.addSuccessor(LoopMBB); 4934 // Update liveins. 4935 fullyRecomputeLiveIns({ExitMBB, LoopMBB}); 4936 4937 return ExitMBB->begin(); 4938 } 4939 4940 void AArch64FrameLowering::inlineStackProbeFixed( 4941 MachineBasicBlock::iterator MBBI, Register ScratchReg, int64_t FrameSize, 4942 StackOffset CFAOffset) const { 4943 MachineBasicBlock *MBB = MBBI->getParent(); 4944 MachineFunction &MF = *MBB->getParent(); 4945 const AArch64InstrInfo *TII = 4946 MF.getSubtarget<AArch64Subtarget>().getInstrInfo(); 4947 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 4948 bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF); 4949 bool HasFP = hasFP(MF); 4950 4951 DebugLoc DL; 4952 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize(); 4953 int64_t NumBlocks = FrameSize / ProbeSize; 4954 int64_t ResidualSize = FrameSize % ProbeSize; 4955 4956 LLVM_DEBUG(dbgs() << "Stack probing: total " << FrameSize << " bytes, " 4957 << NumBlocks << " blocks of " << ProbeSize 4958 << " bytes, plus " << ResidualSize << " bytes\n"); 4959 4960 // Decrement SP by NumBlock * ProbeSize bytes, with either unrolled or 4961 // ordinary loop. 4962 if (NumBlocks <= AArch64::StackProbeMaxLoopUnroll) { 4963 for (int i = 0; i < NumBlocks; ++i) { 4964 // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not 4965 // encodable in a SUB). 4966 emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP, 4967 StackOffset::getFixed(-ProbeSize), TII, 4968 MachineInstr::FrameSetup, false, false, nullptr, 4969 EmitAsyncCFI && !HasFP, CFAOffset); 4970 CFAOffset += StackOffset::getFixed(ProbeSize); 4971 // STR XZR, [SP] 4972 BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui)) 4973 .addReg(AArch64::XZR) 4974 .addReg(AArch64::SP) 4975 .addImm(0) 4976 .setMIFlags(MachineInstr::FrameSetup); 4977 } 4978 } else if (NumBlocks != 0) { 4979 // SUB ScratchReg, SP, #FrameSize (or equivalent if FrameSize is not 4980 // encodable in ADD). ScrathReg may temporarily become the CFA register. 4981 emitFrameOffset(*MBB, MBBI, DL, ScratchReg, AArch64::SP, 4982 StackOffset::getFixed(-ProbeSize * NumBlocks), TII, 4983 MachineInstr::FrameSetup, false, false, nullptr, 4984 EmitAsyncCFI && !HasFP, CFAOffset); 4985 CFAOffset += StackOffset::getFixed(ProbeSize * NumBlocks); 4986 MBBI = inlineStackProbeLoopExactMultiple(MBBI, ProbeSize, ScratchReg); 4987 MBB = MBBI->getParent(); 4988 if (EmitAsyncCFI && !HasFP) { 4989 // Set the CFA register back to SP. 4990 const AArch64RegisterInfo &RegInfo = 4991 *MF.getSubtarget<AArch64Subtarget>().getRegisterInfo(); 4992 unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true); 4993 unsigned CFIIndex = 4994 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg)); 4995 BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 4996 .addCFIIndex(CFIIndex) 4997 .setMIFlags(MachineInstr::FrameSetup); 4998 } 4999 } 5000 5001 if (ResidualSize != 0) { 5002 // SUB SP, SP, #ResidualSize (or equivalent if ResidualSize is not encodable 5003 // in SUB). 5004 emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP, 5005 StackOffset::getFixed(-ResidualSize), TII, 5006 MachineInstr::FrameSetup, false, false, nullptr, 5007 EmitAsyncCFI && !HasFP, CFAOffset); 5008 if (ResidualSize > AArch64::StackProbeMaxUnprobedStack) { 5009 // STR XZR, [SP] 5010 BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui)) 5011 .addReg(AArch64::XZR) 5012 .addReg(AArch64::SP) 5013 .addImm(0) 5014 .setMIFlags(MachineInstr::FrameSetup); 5015 } 5016 } 5017 } 5018 5019 void AArch64FrameLowering::inlineStackProbe(MachineFunction &MF, 5020 MachineBasicBlock &MBB) const { 5021 // Get the instructions that need to be replaced. We emit at most two of 5022 // these. Remember them in order to avoid complications coming from the need 5023 // to traverse the block while potentially creating more blocks. 5024 SmallVector<MachineInstr *, 4> ToReplace; 5025 for (MachineInstr &MI : MBB) 5026 if (MI.getOpcode() == AArch64::PROBED_STACKALLOC || 5027 MI.getOpcode() == AArch64::PROBED_STACKALLOC_VAR) 5028 ToReplace.push_back(&MI); 5029 5030 for (MachineInstr *MI : ToReplace) { 5031 if (MI->getOpcode() == AArch64::PROBED_STACKALLOC) { 5032 Register ScratchReg = MI->getOperand(0).getReg(); 5033 int64_t FrameSize = MI->getOperand(1).getImm(); 5034 StackOffset CFAOffset = StackOffset::get(MI->getOperand(2).getImm(), 5035 MI->getOperand(3).getImm()); 5036 inlineStackProbeFixed(MI->getIterator(), ScratchReg, FrameSize, 5037 CFAOffset); 5038 } else { 5039 assert(MI->getOpcode() == AArch64::PROBED_STACKALLOC_VAR && 5040 "Stack probe pseudo-instruction expected"); 5041 const AArch64InstrInfo *TII = 5042 MI->getMF()->getSubtarget<AArch64Subtarget>().getInstrInfo(); 5043 Register TargetReg = MI->getOperand(0).getReg(); 5044 (void)TII->probedStackAlloc(MI->getIterator(), TargetReg, true); 5045 } 5046 MI->eraseFromParent(); 5047 } 5048 } 5049 5050 struct StackAccess { 5051 enum AccessType { 5052 NotAccessed = 0, // Stack object not accessed by load/store instructions. 5053 GPR = 1 << 0, // A general purpose register. 5054 PPR = 1 << 1, // A predicate register. 5055 FPR = 1 << 2, // A floating point/Neon/SVE register. 5056 }; 5057 5058 int Idx; 5059 StackOffset Offset; 5060 int64_t Size; 5061 unsigned AccessTypes; 5062 5063 StackAccess() : Idx(0), Offset(), Size(0), AccessTypes(NotAccessed) {} 5064 5065 bool operator<(const StackAccess &Rhs) const { 5066 return std::make_tuple(start(), Idx) < 5067 std::make_tuple(Rhs.start(), Rhs.Idx); 5068 } 5069 5070 bool isCPU() const { 5071 // Predicate register load and store instructions execute on the CPU. 5072 return AccessTypes & (AccessType::GPR | AccessType::PPR); 5073 } 5074 bool isSME() const { return AccessTypes & AccessType::FPR; } 5075 bool isMixed() const { return isCPU() && isSME(); } 5076 5077 int64_t start() const { return Offset.getFixed() + Offset.getScalable(); } 5078 int64_t end() const { return start() + Size; } 5079 5080 std::string getTypeString() const { 5081 switch (AccessTypes) { 5082 case AccessType::FPR: 5083 return "FPR"; 5084 case AccessType::PPR: 5085 return "PPR"; 5086 case AccessType::GPR: 5087 return "GPR"; 5088 case AccessType::NotAccessed: 5089 return "NA"; 5090 default: 5091 return "Mixed"; 5092 } 5093 } 5094 5095 void print(raw_ostream &OS) const { 5096 OS << getTypeString() << " stack object at [SP" 5097 << (Offset.getFixed() < 0 ? "" : "+") << Offset.getFixed(); 5098 if (Offset.getScalable()) 5099 OS << (Offset.getScalable() < 0 ? "" : "+") << Offset.getScalable() 5100 << " * vscale"; 5101 OS << "]"; 5102 } 5103 }; 5104 5105 static inline raw_ostream &operator<<(raw_ostream &OS, const StackAccess &SA) { 5106 SA.print(OS); 5107 return OS; 5108 } 5109 5110 void AArch64FrameLowering::emitRemarks( 5111 const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const { 5112 5113 SMEAttrs Attrs(MF.getFunction()); 5114 if (Attrs.hasNonStreamingInterfaceAndBody()) 5115 return; 5116 5117 const uint64_t HazardSize = 5118 (StackHazardSize) ? StackHazardSize : StackHazardRemarkSize; 5119 5120 if (HazardSize == 0) 5121 return; 5122 5123 const MachineFrameInfo &MFI = MF.getFrameInfo(); 5124 // Bail if function has no stack objects. 5125 if (!MFI.hasStackObjects()) 5126 return; 5127 5128 std::vector<StackAccess> StackAccesses(MFI.getNumObjects()); 5129 5130 size_t NumFPLdSt = 0; 5131 size_t NumNonFPLdSt = 0; 5132 5133 // Collect stack accesses via Load/Store instructions. 5134 for (const MachineBasicBlock &MBB : MF) { 5135 for (const MachineInstr &MI : MBB) { 5136 if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1) 5137 continue; 5138 for (MachineMemOperand *MMO : MI.memoperands()) { 5139 std::optional<int> FI = getMMOFrameID(MMO, MFI); 5140 if (FI && !MFI.isDeadObjectIndex(*FI)) { 5141 int FrameIdx = *FI; 5142 5143 size_t ArrIdx = FrameIdx + MFI.getNumFixedObjects(); 5144 if (StackAccesses[ArrIdx].AccessTypes == StackAccess::NotAccessed) { 5145 StackAccesses[ArrIdx].Idx = FrameIdx; 5146 StackAccesses[ArrIdx].Offset = 5147 getFrameIndexReferenceFromSP(MF, FrameIdx); 5148 StackAccesses[ArrIdx].Size = MFI.getObjectSize(FrameIdx); 5149 } 5150 5151 unsigned RegTy = StackAccess::AccessType::GPR; 5152 if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector) { 5153 if (AArch64::PPRRegClass.contains(MI.getOperand(0).getReg())) 5154 RegTy = StackAccess::PPR; 5155 else 5156 RegTy = StackAccess::FPR; 5157 } else if (AArch64InstrInfo::isFpOrNEON(MI)) { 5158 RegTy = StackAccess::FPR; 5159 } 5160 5161 StackAccesses[ArrIdx].AccessTypes |= RegTy; 5162 5163 if (RegTy == StackAccess::FPR) 5164 ++NumFPLdSt; 5165 else 5166 ++NumNonFPLdSt; 5167 } 5168 } 5169 } 5170 } 5171 5172 if (NumFPLdSt == 0 || NumNonFPLdSt == 0) 5173 return; 5174 5175 llvm::sort(StackAccesses); 5176 StackAccesses.erase(llvm::remove_if(StackAccesses, 5177 [](const StackAccess &S) { 5178 return S.AccessTypes == 5179 StackAccess::NotAccessed; 5180 }), 5181 StackAccesses.end()); 5182 5183 SmallVector<const StackAccess *> MixedObjects; 5184 SmallVector<std::pair<const StackAccess *, const StackAccess *>> HazardPairs; 5185 5186 if (StackAccesses.front().isMixed()) 5187 MixedObjects.push_back(&StackAccesses.front()); 5188 5189 for (auto It = StackAccesses.begin(), End = std::prev(StackAccesses.end()); 5190 It != End; ++It) { 5191 const auto &First = *It; 5192 const auto &Second = *(It + 1); 5193 5194 if (Second.isMixed()) 5195 MixedObjects.push_back(&Second); 5196 5197 if ((First.isSME() && Second.isCPU()) || 5198 (First.isCPU() && Second.isSME())) { 5199 uint64_t Distance = static_cast<uint64_t>(Second.start() - First.end()); 5200 if (Distance < HazardSize) 5201 HazardPairs.emplace_back(&First, &Second); 5202 } 5203 } 5204 5205 auto EmitRemark = [&](llvm::StringRef Str) { 5206 ORE->emit([&]() { 5207 auto R = MachineOptimizationRemarkAnalysis( 5208 "sme", "StackHazard", MF.getFunction().getSubprogram(), &MF.front()); 5209 return R << formatv("stack hazard in '{0}': ", MF.getName()).str() << Str; 5210 }); 5211 }; 5212 5213 for (const auto &P : HazardPairs) 5214 EmitRemark(formatv("{0} is too close to {1}", *P.first, *P.second).str()); 5215 5216 for (const auto *Obj : MixedObjects) 5217 EmitRemark( 5218 formatv("{0} accessed by both GP and FP instructions", *Obj).str()); 5219 } 5220