LLVM 24.0.0git
ARMFrameLowering.cpp
Go to the documentation of this file.
1//===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the ARM implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12//
13// This file contains the ARM implementation of TargetFrameLowering class.
14//
15// On ARM, stack frames are structured as follows:
16//
17// The stack grows downward.
18//
19// All of the individual frame areas on the frame below are optional, i.e. it's
20// possible to create a function so that the particular area isn't present
21// in the frame.
22//
23// At function entry, the "frame" looks as follows:
24//
25// | | Higher address
26// |-----------------------------------|
27// | |
28// | arguments passed on the stack |
29// | |
30// |-----------------------------------| <- sp
31// | | Lower address
32//
33//
34// After the prologue has run, the frame has the following general structure.
35// Technically the last frame area (VLAs) doesn't get created until in the
36// main function body, after the prologue is run. However, it's depicted here
37// for completeness.
38//
39// | | Higher address
40// |-----------------------------------|
41// | |
42// | arguments passed on the stack |
43// | |
44// |-----------------------------------| <- (sp at function entry)
45// | |
46// | varargs from registers |
47// | |
48// |-----------------------------------|
49// | |
50// | prev_lr |
51// | prev_fp |
52// | (a.k.a. "frame record") |
53// | |
54// |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11)
55// | |
56// | callee-saved gpr registers |
57// | |
58// |-----------------------------------|
59// | |
60// | callee-saved fp/simd regs |
61// | |
62// |-----------------------------------|
63// |.empty.space.to.make.part.below....|
64// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
65// |.the.standard.8-byte.alignment.....| compile time; if present)
66// |-----------------------------------|
67// | |
68// | local variables of fixed size |
69// | including spill slots |
70// |-----------------------------------| <- base pointer (not defined by ABI,
71// |.variable-sized.local.variables....| LLVM chooses r6)
72// |.(VLAs)............................| (size of this area is unknown at
73// |...................................| compile time)
74// |-----------------------------------| <- sp
75// | | Lower address
76//
77//
78// To access the data in a frame, at-compile time, a constant offset must be
79// computable from one of the pointers (fp, bp, sp) to access it. The size
80// of the areas with a dotted background cannot be computed at compile-time
81// if they are present, making it required to have all three of fp, bp and
82// sp to be set up to be able to access all contents in the frame areas,
83// assuming all of the frame areas are non-empty.
84//
85// For most functions, some of the frame areas are empty. For those functions,
86// it may not be necessary to set up fp or bp:
87// * A base pointer is definitely needed when there are both VLAs and local
88// variables with more-than-default alignment requirements.
89// * A frame pointer is definitely needed when there are local variables with
90// more-than-default alignment requirements.
91//
92// In some cases when a base pointer is not strictly needed, it is generated
93// anyway when offsets from the frame pointer to access local variables become
94// so large that the offset can't be encoded in the immediate fields of loads
95// or stores.
96//
97// The frame pointer might be chosen to be r7 or r11, depending on the target
98// architecture and operating system. See ARMSubtarget::getFramePointerReg for
99// details.
100//
101// Outgoing function arguments must be at the bottom of the stack frame when
102// calling another function. If we do not have variable-sized stack objects, we
103// can allocate a "reserved call frame" area at the bottom of the local
104// variable area, large enough for all outgoing calls. If we do have VLAs, then
105// the stack pointer must be decremented and incremented around each call to
106// make space for the arguments below the VLAs.
107//
108//===----------------------------------------------------------------------===//
109
110#include "ARMFrameLowering.h"
111#include "ARMBaseInstrInfo.h"
112#include "ARMBaseRegisterInfo.h"
113#include "ARMConstantPoolValue.h"
115#include "ARMSubtarget.h"
118#include "Utils/ARMBaseInfo.h"
119#include "llvm/ADT/BitVector.h"
120#include "llvm/ADT/STLExtras.h"
121#include "llvm/ADT/SmallPtrSet.h"
122#include "llvm/ADT/SmallVector.h"
138#include "llvm/IR/Attributes.h"
139#include "llvm/IR/CallingConv.h"
140#include "llvm/IR/DebugLoc.h"
141#include "llvm/IR/Function.h"
142#include "llvm/IR/Module.h"
143#include "llvm/MC/MCAsmInfo.h"
144#include "llvm/MC/MCInstrDesc.h"
145#include "llvm/Support/CodeGen.h"
147#include "llvm/Support/Debug.h"
151#include <algorithm>
152#include <cassert>
153#include <cstddef>
154#include <cstdint>
155#include <iterator>
156#include <utility>
157#include <vector>
158
159#define DEBUG_TYPE "arm-frame-lowering"
160
161using namespace llvm;
162
165 unsigned NumAlignedDPRCS2Regs);
166
176
177/// Get the spill area that Reg should be saved into in the prologue.
180 unsigned NumAlignedDPRCS2Regs,
182 // NoSplit:
183 // push {r0-r12, lr} GPRCS1
184 // vpush {r8-d15} DPRCS1
185 //
186 // SplitR7:
187 // push {r0-r7, lr} GPRCS1
188 // push {r8-r12} GPRCS2
189 // vpush {r8-d15} DPRCS1
190 //
191 // SplitR11WindowsSEH:
192 // push {r0-r10, r12} GPRCS1
193 // vpush {r8-d15} DPRCS1
194 // push {r11, lr} GPRCS3
195 //
196 // SplitR11AAPCSSignRA:
197 // push {r0-r10, r12} GPRSC1
198 // push {r11, lr} GPRCS2
199 // vpush {r8-d15} DPRCS1
200
201 // If FPCXTNS is spilled (for CMSE secure entryfunctions), it is always at
202 // the top of the stack frame.
203 // The DPRCS2 region is used for ABIs which only guarantee 4-byte alignment
204 // of SP. If used, it will be below the other save areas, after the stack has
205 // been re-aligned.
206
207 switch (Reg) {
208 default:
209 dbgs() << "Don't know where to spill " << printReg(Reg, RegInfo) << "\n";
210 llvm_unreachable("Don't know where to spill this register");
211 break;
212
213 case ARM::FPCXTNS:
214 return SpillArea::FPCXT;
215
216 case ARM::FPSCR:
217 case ARM::FPEXC:
218 return SpillArea::FPStatus;
219
220 case ARM::R0:
221 case ARM::R1:
222 case ARM::R2:
223 case ARM::R3:
224 case ARM::R4:
225 case ARM::R5:
226 case ARM::R6:
227 case ARM::R7:
228 return SpillArea::GPRCS1;
229
230 case ARM::R8:
231 case ARM::R9:
232 case ARM::R10:
233 if (Variation == ARMSubtarget::SplitR7)
234 return SpillArea::GPRCS2;
235 else
236 return SpillArea::GPRCS1;
237
238 case ARM::R11:
239 if (Variation == ARMSubtarget::SplitR7 ||
241 return SpillArea::GPRCS2;
242 if (Variation == ARMSubtarget::SplitR11WindowsSEH)
243 return SpillArea::GPRCS3;
244
245 return SpillArea::GPRCS1;
246
247 case ARM::R12:
248 if (Variation == ARMSubtarget::SplitR7)
249 return SpillArea::GPRCS2;
250 else
251 return SpillArea::GPRCS1;
252
253 case ARM::LR:
254 if (Variation == ARMSubtarget::SplitR11AAPCSSignRA)
255 return SpillArea::GPRCS2;
256 if (Variation == ARMSubtarget::SplitR11WindowsSEH)
257 return SpillArea::GPRCS3;
258
259 return SpillArea::GPRCS1;
260
261 case ARM::D0:
262 case ARM::D1:
263 case ARM::D2:
264 case ARM::D3:
265 case ARM::D4:
266 case ARM::D5:
267 case ARM::D6:
268 case ARM::D7:
269 return SpillArea::DPRCS1;
270
271 case ARM::D8:
272 case ARM::D9:
273 case ARM::D10:
274 case ARM::D11:
275 case ARM::D12:
276 case ARM::D13:
277 case ARM::D14:
278 case ARM::D15:
279 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
280 return SpillArea::DPRCS2;
281 else
282 return SpillArea::DPRCS1;
283
284 case ARM::D16:
285 case ARM::D17:
286 case ARM::D18:
287 case ARM::D19:
288 case ARM::D20:
289 case ARM::D21:
290 case ARM::D22:
291 case ARM::D23:
292 case ARM::D24:
293 case ARM::D25:
294 case ARM::D26:
295 case ARM::D27:
296 case ARM::D28:
297 case ARM::D29:
298 case ARM::D30:
299 case ARM::D31:
300 return SpillArea::DPRCS1;
301 }
302}
303
307
309 // iOS always has a FP for backtracking, force other targets to keep their FP
310 // when doing FastISel. The emitted code is currently superior, and in cases
311 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
312 return MF.getSubtarget<ARMSubtarget>().useFastISel();
313}
314
315/// Returns true if the target can safely skip saving callee-saved registers
316/// for noreturn nounwind functions.
318 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
319 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
320 !MF.getFunction().hasFnAttribute(Attribute::UWTable));
321
322 // Frame pointer and link register are not treated as normal CSR, thus we
323 // can always skip CSR saves for nonreturning functions.
324 return true;
325}
326
327/// hasFPImpl - Return true if the specified function should have a dedicated
328/// frame pointer register. This is true if the function has variable sized
329/// allocas or if frame pointer elimination is disabled.
331 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
332 const MachineFrameInfo &MFI = MF.getFrameInfo();
333
334 // Check to see if the target want to forcibly keep frame pointer.
335 if (keepFramePointer(MF))
336 return true;
337
338 // ABI-required frame pointer.
340 return true;
341
342 // Frame pointer required for use within this function.
343 return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
344 MFI.isFrameAddressTaken());
345}
346
347/// isFPReserved - Return true if the frame pointer register should be
348/// considered a reserved register on the scope of the specified function.
350 return hasFP(MF) || MF.framePointerIsReserved();
351}
352
353/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
354/// not required, we reserve argument space for call sites in the function
355/// immediately on entry to the current function. This eliminates the need for
356/// add/sub sp brackets around call sites. Returns true if the call frame is
357/// included as part of the stack frame.
359 const MachineFrameInfo &MFI = MF.getFrameInfo();
360 unsigned CFSize = MFI.getMaxCallFrameSize();
361 // It's not always a good idea to include the call frame as part of the
362 // stack frame. ARM (especially Thumb) has small immediate offset to
363 // address the stack frame. So a large call frame can cause poor codegen
364 // and may even makes it impossible to scavenge a register.
365 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
366 return false;
367
368 return !MFI.hasVarSizedObjects();
369}
370
371/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
372/// call frame pseudos can be simplified. Unlike most targets, having a FP
373/// is not sufficient here since we still may reference some objects via SP
374/// even when FP is available in Thumb2 mode.
375bool
379
380// Returns how much of the incoming argument stack area we should clean up in an
381// epilogue. For the C calling convention this will be 0, for guaranteed tail
382// call conventions it can be positive (a normal return or a tail call to a
383// function that uses less stack space for arguments) or negative (for a tail
384// call to a function that needs more stack space than us for arguments).
387 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
388 bool IsTailCallReturn = false;
389 if (MBB.end() != MBBI) {
390 unsigned RetOpcode = MBBI->getOpcode();
391 IsTailCallReturn = RetOpcode == ARM::TCRETURNdi ||
392 RetOpcode == ARM::TCRETURNri ||
393 RetOpcode == ARM::TCRETURNrinotr12;
394 }
396
397 int ArgumentPopSize = 0;
398 if (IsTailCallReturn) {
399 MachineOperand &StackAdjust = MBBI->getOperand(1);
400
401 // For a tail-call in a callee-pops-arguments environment, some or all of
402 // the stack may actually be in use for the call's arguments, this is
403 // calculated during LowerCall and consumed here...
404 ArgumentPopSize = StackAdjust.getImm();
405 } else {
406 // ... otherwise the amount to pop is *all* of the argument space,
407 // conveniently stored in the MachineFunctionInfo by
408 // LowerFormalArguments. This will, of course, be zero for the C calling
409 // convention.
410 ArgumentPopSize = AFI->getArgumentStackToRestore();
411 }
412
413 return ArgumentPopSize;
414}
415
416// Given a load or a store instruction, generate an appropriate unwinding SEH
417// code on Windows.
419 const TargetInstrInfo &TII,
420 unsigned Flags) {
421 unsigned Opc = MBBI->getOpcode();
422 MachineBasicBlock *MBB = MBBI->getParent();
423 MachineFunction &MF = *MBB->getParent();
424 DebugLoc DL = MBBI->getDebugLoc();
427 const ARMBaseRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
428
429 Flags |= MachineInstr::NoMerge;
430
431 switch (Opc) {
432 default:
433 report_fatal_error("No SEH Opcode for instruction " + TII.getName(Opc));
434 break;
435 case ARM::t2ADDri: // add.w r11, sp, #xx
436 case ARM::t2ADDri12: // add.w r11, sp, #xx
437 case ARM::t2MOVTi16: // movt r4, #xx
438 case ARM::tBL: // bl __chkstk
439 // These are harmless if used for just setting up a frame pointer,
440 // but that frame pointer can't be relied upon for unwinding, unless
441 // set up with SEH_SaveSP.
442 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
443 .addImm(/*Wide=*/1)
444 .setMIFlags(Flags);
445 break;
446
447 case ARM::t2MOVi16: { // mov(w) r4, #xx
448 bool Wide = MBBI->getOperand(1).getImm() >= 256;
449 if (!Wide) {
450 MachineInstrBuilder NewInstr =
451 BuildMI(MF, DL, TII.get(ARM::tMOVi8)).setMIFlags(MBBI->getFlags());
452 NewInstr.add(MBBI->getOperand(0));
453 NewInstr.add(t1CondCodeOp(/*isDead=*/true));
454 for (MachineOperand &MO : llvm::drop_begin(MBBI->operands()))
455 NewInstr.add(MO);
456 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
457 MBB->erase(MBBI);
458 MBBI = NewMBBI;
459 }
460 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)).addImm(Wide).setMIFlags(Flags);
461 break;
462 }
463
464 case ARM::tBLXr: // blx r12 (__chkstk)
465 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
466 .addImm(/*Wide=*/0)
467 .setMIFlags(Flags);
468 break;
469
470 case ARM::t2MOVi32imm: // movw+movt
471 // This pseudo instruction expands into two mov instructions. If the
472 // second operand is a symbol reference, this will stay as two wide
473 // instructions, movw+movt. If they're immediates, the first one can
474 // end up as a narrow mov though.
475 // As two SEH instructions are appended here, they won't get interleaved
476 // between the two final movw/movt instructions, but it doesn't make any
477 // practical difference.
478 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
479 .addImm(/*Wide=*/1)
480 .setMIFlags(Flags);
481 MBB->insertAfter(MBBI, MIB);
482 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
483 .addImm(/*Wide=*/1)
484 .setMIFlags(Flags);
485 break;
486
487 case ARM::t2STR_PRE:
488 if (MBBI->getOperand(0).getReg() == ARM::SP &&
489 MBBI->getOperand(2).getReg() == ARM::SP &&
490 MBBI->getOperand(3).getImm() == -4) {
491 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
492 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs))
493 .addImm(1ULL << Reg)
494 .addImm(/*Wide=*/1)
495 .setMIFlags(Flags);
496 } else {
497 report_fatal_error("No matching SEH Opcode for t2STR_PRE");
498 }
499 break;
500
501 case ARM::t2LDR_POST:
502 if (MBBI->getOperand(1).getReg() == ARM::SP &&
503 MBBI->getOperand(2).getReg() == ARM::SP &&
504 MBBI->getOperand(3).getImm() == 4) {
505 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
506 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs))
507 .addImm(1ULL << Reg)
508 .addImm(/*Wide=*/1)
509 .setMIFlags(Flags);
510 } else {
511 report_fatal_error("No matching SEH Opcode for t2LDR_POST");
512 }
513 break;
514
515 case ARM::t2LDMIA_RET:
516 case ARM::t2LDMIA_UPD:
517 case ARM::t2STMDB_UPD: {
518 unsigned Mask = 0;
519 bool Wide = false;
520 for (unsigned i = 4, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) {
521 const MachineOperand &MO = MBBI->getOperand(i);
522 if (!MO.isReg() || MO.isImplicit())
523 continue;
524 unsigned Reg = RegInfo->getSEHRegNum(MO.getReg());
525 if (Reg == 15)
526 Reg = 14;
527 if (Reg >= 8 && Reg <= 13)
528 Wide = true;
529 else if (Opc == ARM::t2LDMIA_UPD && Reg == 14)
530 Wide = true;
531 Mask |= 1 << Reg;
532 }
533 if (!Wide) {
534 unsigned NewOpc;
535 switch (Opc) {
536 case ARM::t2LDMIA_RET:
537 NewOpc = ARM::tPOP_RET;
538 break;
539 case ARM::t2LDMIA_UPD:
540 NewOpc = ARM::tPOP;
541 break;
542 case ARM::t2STMDB_UPD:
543 NewOpc = ARM::tPUSH;
544 break;
545 default:
547 }
548 MachineInstrBuilder NewInstr =
549 BuildMI(MF, DL, TII.get(NewOpc)).setMIFlags(MBBI->getFlags());
550 for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
551 NewInstr.add(MBBI->getOperand(i));
552 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
553 MBB->erase(MBBI);
554 MBBI = NewMBBI;
555 }
556 unsigned SEHOpc =
557 (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs;
558 MIB = BuildMI(MF, DL, TII.get(SEHOpc))
559 .addImm(Mask)
560 .addImm(Wide ? 1 : 0)
561 .setMIFlags(Flags);
562 break;
563 }
564 case ARM::VSTMDDB_UPD:
565 case ARM::VLDMDIA_UPD: {
566 int First = -1, Last = 0;
567 for (const MachineOperand &MO : llvm::drop_begin(MBBI->operands(), 4)) {
568 unsigned Reg = RegInfo->getSEHRegNum(MO.getReg());
569 if (First == -1)
570 First = Reg;
571 Last = Reg;
572 }
573 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveFRegs))
574 .addImm(First)
575 .addImm(Last)
576 .setMIFlags(Flags);
577 break;
578 }
579 case ARM::tSUBspi:
580 case ARM::tADDspi:
581 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc))
582 .addImm(MBBI->getOperand(2).getImm() * 4)
583 .addImm(/*Wide=*/0)
584 .setMIFlags(Flags);
585 break;
586 case ARM::t2SUBspImm:
587 case ARM::t2SUBspImm12:
588 case ARM::t2ADDspImm:
589 case ARM::t2ADDspImm12:
590 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc))
591 .addImm(MBBI->getOperand(2).getImm())
592 .addImm(/*Wide=*/1)
593 .setMIFlags(Flags);
594 break;
595
596 case ARM::tMOVr:
597 if (MBBI->getOperand(1).getReg() == ARM::SP &&
598 (Flags & MachineInstr::FrameSetup)) {
599 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
600 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
601 .addImm(Reg)
602 .setMIFlags(Flags);
603 } else if (MBBI->getOperand(0).getReg() == ARM::SP &&
604 (Flags & MachineInstr::FrameDestroy)) {
605 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
606 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
607 .addImm(Reg)
608 .setMIFlags(Flags);
609 } else {
610 report_fatal_error("No SEH Opcode for MOV");
611 }
612 break;
613
614 case ARM::tBX_RET:
615 case ARM::t2BXAUT_RET:
616 case ARM::CLEANUPRET:
617 case ARM::CATCHRET:
618 case ARM::TCRETURNri:
619 case ARM::TCRETURNrinotr12:
620 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret))
621 .addImm(/*Wide=*/0)
622 .setMIFlags(Flags);
623 break;
624
625 case ARM::TCRETURNdi:
626 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret))
627 .addImm(/*Wide=*/1)
628 .setMIFlags(Flags);
629 break;
630 }
631 return MBB->insertAfter(MBBI, MIB);
632}
633
636 if (MBBI == MBB.begin())
638 return std::prev(MBBI);
639}
640
644 const ARMBaseInstrInfo &TII, unsigned MIFlags) {
645 if (Start.isValid())
646 Start = std::next(Start);
647 else
648 Start = MBB.begin();
649
650 for (auto MI = Start; MI != End;) {
651 auto Next = std::next(MI);
652 // Check if this instruction already has got a SEH opcode added. In that
653 // case, don't do this generic mapping.
654 if (Next != End && isSEHInstruction(*Next)) {
655 MI = std::next(Next);
656 while (MI != End && isSEHInstruction(*MI))
657 ++MI;
658 continue;
659 }
660 insertSEH(MI, TII, MIFlags);
661 MI = Next;
662 }
663}
664
667 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
668 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
669 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
670 if (isARM)
671 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
672 Pred, PredReg, TII, MIFlags);
673 else
674 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
675 Pred, PredReg, TII, MIFlags);
676}
677
678static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
680 const ARMBaseInstrInfo &TII, int NumBytes,
681 unsigned MIFlags = MachineInstr::NoFlags,
683 unsigned PredReg = 0) {
684 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
685 MIFlags, Pred, PredReg);
686}
687
689 int RegSize;
690 switch (MI.getOpcode()) {
691 case ARM::VSTMDDB_UPD:
692 RegSize = 8;
693 break;
694 case ARM::STMDB_UPD:
695 case ARM::t2STMDB_UPD:
696 RegSize = 4;
697 break;
698 case ARM::t2STR_PRE:
699 case ARM::STR_PRE_IMM:
700 return 4;
701 default:
702 llvm_unreachable("Unknown push or pop like instruction");
703 }
704
705 int count = 0;
706 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
707 // pred) so the list starts at 4.
708 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
709 count += RegSize;
710 return count;
711}
712
714 size_t StackSizeInBytes) {
715 const MachineFrameInfo &MFI = MF.getFrameInfo();
716 const Function &F = MF.getFunction();
717 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
718
719 StackProbeSize =
720 F.getFnAttributeAsParsedInteger("stack-probe-size", StackProbeSize);
721 return (StackSizeInBytes >= StackProbeSize) &&
722 !F.hasFnAttribute("no-stack-arg-probe");
723}
724
725namespace {
726
727struct StackAdjustingInsts {
728 struct InstInfo {
730 unsigned SPAdjust;
731 bool BeforeFPSet;
732
733#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
734 void dump() {
735 dbgs() << " " << (BeforeFPSet ? "before-fp " : " ")
736 << "sp-adjust=" << SPAdjust;
737 I->dump();
738 }
739#endif
740 };
741
743
744 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
745 bool BeforeFPSet = false) {
746 InstInfo Info = {I, SPAdjust, BeforeFPSet};
747 Insts.push_back(Info);
748 }
749
750 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
751 auto Info =
752 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
753 assert(Info != Insts.end() && "invalid sp adjusting instruction");
754 Info->SPAdjust += ExtraBytes;
755 }
756
757 void emitDefCFAOffsets(MachineBasicBlock &MBB, bool HasFP) {
758 CFIInstBuilder CFIBuilder(MBB, MBB.end(), MachineInstr::FrameSetup);
759 unsigned CFAOffset = 0;
760 for (auto &Info : Insts) {
761 if (HasFP && !Info.BeforeFPSet)
762 return;
763
764 CFAOffset += Info.SPAdjust;
765 CFIBuilder.setInsertPoint(std::next(Info.I));
766 CFIBuilder.buildDefCFAOffset(CFAOffset);
767 }
768 }
769
770#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
771 void dump() {
772 dbgs() << "StackAdjustingInsts:\n";
773 for (auto &Info : Insts)
774 Info.dump();
775 }
776#endif
777};
778
779} // end anonymous namespace
780
781/// Emit an instruction sequence that will align the address in
782/// register Reg by zero-ing out the lower bits. For versions of the
783/// architecture that support Neon, this must be done in a single
784/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
785/// single instruction. That function only gets called when optimizing
786/// spilling of D registers on a core with the Neon instruction set
787/// present.
789 const TargetInstrInfo &TII,
792 const DebugLoc &DL, const unsigned Reg,
793 const Align Alignment,
794 const bool MustBeSingleInstruction) {
795 const ARMSubtarget &AST = MF.getSubtarget<ARMSubtarget>();
796 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
797 const unsigned AlignMask = Alignment.value() - 1U;
798 const unsigned NrBitsToZero = Log2(Alignment);
799 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
800 if (!AFI->isThumbFunction()) {
801 // if the BFC instruction is available, use that to zero the lower
802 // bits:
803 // bfc Reg, #0, log2(Alignment)
804 // otherwise use BIC, if the mask to zero the required number of bits
805 // can be encoded in the bic immediate field
806 // bic Reg, Reg, Alignment-1
807 // otherwise, emit
808 // lsr Reg, Reg, log2(Alignment)
809 // lsl Reg, Reg, log2(Alignment)
810 if (CanUseBFC) {
811 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
813 .addImm(~AlignMask)
815 } else if (AlignMask <= 255) {
816 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
818 .addImm(AlignMask)
820 .add(condCodeOp());
821 } else {
822 assert(!MustBeSingleInstruction &&
823 "Shouldn't call emitAligningInstructions demanding a single "
824 "instruction to be emitted for large stack alignment for a target "
825 "without BFC.");
826 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
828 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
830 .add(condCodeOp());
831 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
833 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
835 .add(condCodeOp());
836 }
837 } else {
838 // Since this is only reached for Thumb-2 targets, the BFC instruction
839 // should always be available.
840 assert(CanUseBFC);
841 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
843 .addImm(~AlignMask)
845 }
846}
847
848/// We need the offset of the frame pointer relative to other MachineFrameInfo
849/// offsets which are encoded relative to SP at function begin.
850/// See also emitPrologue() for how the FP is set up.
851/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
852/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
853/// this to produce a conservative estimate that we check in an assert() later.
854static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI,
855 const MachineFunction &MF) {
858 // For Thumb1, push.w isn't available, so the first push will always push
859 // r7 and lr onto the stack first.
860 if (AFI.isThumb1OnlyFunction())
861 return -AFI.getArgRegsSaveSize() - (2 * 4);
862 // This is a conservative estimation: Assume the frame pointer being r7 and
863 // pc("r15") up to r8 getting spilled before (= 8 registers).
864 int MaxRegBytes = 8 * 4;
865 if (PushPopSplit == ARMSubtarget::SplitR11AAPCSSignRA)
866 // Here, r11 can be stored below all of r4-r15.
867 MaxRegBytes = 11 * 4;
868 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) {
869 // Here, r11 can be stored below all of r4-r15 plus d8-d15.
870 MaxRegBytes = 11 * 4 + 8 * 8;
871 }
872 int FPCXTSaveSize =
873 (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
874 return -FPCXTSaveSize - AFI.getArgRegsSaveSize() - MaxRegBytes;
875}
876
878 MachineBasicBlock &MBB) const {
880 MachineFrameInfo &MFI = MF.getFrameInfo();
882 const TargetMachine &TM = MF.getTarget();
883 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
884 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
886 "This emitPrologue does not support Thumb1!");
887 bool isARM = !AFI->isThumbFunction();
888 Align Alignment = STI.getFrameLowering()->getStackAlign();
889 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
890 unsigned NumBytes = MFI.getStackSize();
891 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
892 int FPCXTSaveSize = 0;
893 bool NeedsWinCFI = MF.needsWinCFI();
895 STI.getPushPopSplitVariation(MF);
896
897 LLVM_DEBUG(dbgs() << "Emitting prologue for " << MF.getName() << "\n");
898
899 // Debug location must be unknown since the first debug location is used
900 // to determine the end of the prologue.
901 DebugLoc dl;
902
903 Register FramePtr = RegInfo->getFrameRegister(MF);
904
905 // Determine the sizes of each callee-save spill areas and record which frame
906 // belongs to which callee-save spill areas.
907 unsigned GPRCS1Size = 0, GPRCS2Size = 0, FPStatusSize = 0,
908 DPRCS1Size = 0, GPRCS3Size = 0, DPRCS2Size = 0;
909 int FramePtrSpillFI = 0;
910 int D8SpillFI = 0;
911
912 // All calls are tail calls in GHC calling conv, and functions have no
913 // prologue/epilogue.
915 return;
916
917 StackAdjustingInsts DefCFAOffsetCandidates;
918 bool HasFP = hasFP(MF);
919
920 if (!AFI->hasStackFrame() &&
921 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
922 if (NumBytes != 0) {
923 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
925 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes, true);
926 }
927 if (!NeedsWinCFI)
928 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
929 if (NeedsWinCFI && MBBI != MBB.begin()) {
931 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_PrologEnd))
933 MF.setHasWinCFI(true);
934 }
935 return;
936 }
937
938 // Determine spill area sizes, and some important frame indices.
939 SpillArea FramePtrSpillArea = SpillArea::GPRCS1;
940 bool BeforeFPPush = true;
941 for (const CalleeSavedInfo &I : CSI) {
942 MCRegister Reg = I.getReg();
943 int FI = I.getFrameIdx();
944
945 SpillArea Area = getSpillArea(Reg, PushPopSplit,
946 AFI->getNumAlignedDPRCS2Regs(), RegInfo);
947
948 if (Reg == FramePtr.asMCReg()) {
949 FramePtrSpillFI = FI;
950 FramePtrSpillArea = Area;
951 }
952 if (Reg == ARM::D8)
953 D8SpillFI = FI;
954
955 switch (Area) {
956 case SpillArea::FPCXT:
957 FPCXTSaveSize += 4;
958 break;
960 GPRCS1Size += 4;
961 break;
963 GPRCS2Size += 4;
964 break;
966 FPStatusSize += 4;
967 break;
969 DPRCS1Size += 8;
970 break;
972 GPRCS3Size += 4;
973 break;
975 DPRCS2Size += 8;
976 break;
977 }
978 }
979
980 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
981 DPRCS1Push, GPRCS3Push;
982
983 // Move past the PAC computation.
984 if (AFI->shouldSignReturnAddress())
985 LastPush = MBBI++;
986
987 // Move past FPCXT area.
988 if (FPCXTSaveSize > 0) {
989 LastPush = MBBI++;
990 DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, BeforeFPPush);
991 }
992
993 // Allocate the vararg register save area.
994 if (ArgRegsSaveSize) {
995 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
997 LastPush = std::prev(MBBI);
998 DefCFAOffsetCandidates.addInst(LastPush, ArgRegsSaveSize, BeforeFPPush);
999 }
1000
1001 // Move past area 1.
1002 if (GPRCS1Size > 0) {
1003 GPRCS1Push = LastPush = MBBI++;
1004 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, BeforeFPPush);
1005 if (FramePtrSpillArea == SpillArea::GPRCS1)
1006 BeforeFPPush = false;
1007 }
1008
1009 // Determine starting offsets of spill areas. These offsets are all positive
1010 // offsets from the bottom of the lowest-addressed callee-save area
1011 // (excluding DPRCS2, which is th the re-aligned stack region) to the bottom
1012 // of the spill area in question.
1013 unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
1014 unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
1015 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
1016 unsigned FPStatusOffset = GPRCS2Offset - FPStatusSize;
1017
1018 Align DPRAlign = DPRCS1Size ? std::min(Align(8), Alignment) : Align(4);
1019 unsigned DPRGapSize = (ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1020 GPRCS2Size + FPStatusSize) %
1021 DPRAlign.value();
1022
1023 unsigned DPRCS1Offset = FPStatusOffset - DPRGapSize - DPRCS1Size;
1024
1025 if (HasFP) {
1026 // Offset from the CFA to the saved frame pointer, will be negative.
1027 [[maybe_unused]] int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
1028 LLVM_DEBUG(dbgs() << "FramePtrSpillFI: " << FramePtrSpillFI
1029 << ", FPOffset: " << FPOffset << "\n");
1030 assert(getMaxFPOffset(STI, *AFI, MF) <= FPOffset &&
1031 "Max FP estimation is wrong");
1032 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
1033 NumBytes);
1034 }
1035 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1036 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1037 AFI->setDPRCalleeSavedArea1Offset(DPRCS1Offset);
1038
1039 // Move past area 2.
1040 if (GPRCS2Size > 0) {
1042 GPRCS2Push = LastPush = MBBI++;
1043 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size, BeforeFPPush);
1044 if (FramePtrSpillArea == SpillArea::GPRCS2)
1045 BeforeFPPush = false;
1046 }
1047
1048 // Move past FP status save area.
1049 if (FPStatusSize > 0) {
1050 while (MBBI != MBB.end()) {
1051 unsigned Opc = MBBI->getOpcode();
1052 if (Opc == ARM::VMRS || Opc == ARM::VMRS_FPEXC)
1053 MBBI++;
1054 else
1055 break;
1056 }
1057 LastPush = MBBI++;
1058 DefCFAOffsetCandidates.addInst(LastPush, FPStatusSize);
1059 }
1060
1061 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
1062 // .cfi_offset operations will reflect that.
1063 if (DPRGapSize) {
1064 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
1065 if (LastPush != MBB.end() &&
1066 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
1067 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
1068 else {
1069 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
1071 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize, BeforeFPPush);
1072 }
1073 }
1074
1075 // Move past DPRCS1Size.
1076 if (DPRCS1Size > 0) {
1077 // Since vpush register list cannot have gaps, there may be multiple vpush
1078 // instructions in the prologue.
1079 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
1080 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI),
1081 BeforeFPPush);
1082 DPRCS1Push = LastPush = MBBI++;
1083 }
1084 }
1085
1086 // Move past the aligned DPRCS2 area.
1087 if (DPRCS2Size > 0) {
1089 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
1090 // leaves the stack pointer pointing to the DPRCS2 area.
1091 //
1092 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
1093 NumBytes += MFI.getObjectOffset(D8SpillFI);
1094 } else
1095 NumBytes = DPRCS1Offset;
1096
1097 // Move GPRCS3, if using using SplitR11WindowsSEH.
1098 if (GPRCS3Size > 0) {
1100 GPRCS3Push = LastPush = MBBI++;
1101 DefCFAOffsetCandidates.addInst(LastPush, GPRCS3Size, BeforeFPPush);
1102 if (FramePtrSpillArea == SpillArea::GPRCS3)
1103 BeforeFPPush = false;
1104 NumBytes -= GPRCS3Size;
1105 }
1106
1107 bool NeedsWinCFIStackAlloc = NeedsWinCFI;
1108 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH && HasFP)
1109 NeedsWinCFIStackAlloc = false;
1110
1111 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
1112 uint32_t NumWords = NumBytes >> 2;
1113
1114 if (NumWords < 65536) {
1115 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
1116 .addImm(NumWords)
1119 } else {
1120 // Split into two instructions here, instead of using t2MOVi32imm,
1121 // to allow inserting accurate SEH instructions (including accurate
1122 // instruction size for each of them).
1123 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
1124 .addImm(NumWords & 0xffff)
1127 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVTi16), ARM::R4)
1128 .addReg(ARM::R4)
1129 .addImm(NumWords >> 16)
1132 }
1133
1134 const ARMTargetLowering *TLI = STI.getTargetLowering();
1135 RTLIB::LibcallImpl ChkStkLibcall = TLI->getLibcallImpl(RTLIB::STACK_PROBE);
1136 if (ChkStkLibcall == RTLIB::Unsupported)
1137 reportFatalUsageError("no available implementation of __chkstk");
1138 const char *ChkStk = TLI->getLibcallImplName(ChkStkLibcall).data();
1139
1140 switch (TM.getCodeModel()) {
1141 case CodeModel::Tiny:
1142 llvm_unreachable("Tiny code model not available on ARM.");
1143 case CodeModel::Small:
1144 case CodeModel::Medium:
1145 case CodeModel::Kernel:
1146 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
1148 .addExternalSymbol(ChkStk)
1149 .addReg(ARM::R4, RegState::Implicit)
1151 break;
1152 case CodeModel::Large:
1153 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
1154 .addExternalSymbol(ChkStk)
1156
1157 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
1159 .addReg(ARM::R12, RegState::Kill)
1160 .addReg(ARM::R4, RegState::Implicit)
1162 break;
1163 }
1164
1165 MachineInstrBuilder Instr, SEH;
1166 Instr = BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
1167 .addReg(ARM::SP, RegState::Kill)
1168 .addReg(ARM::R4, RegState::Kill)
1171 .add(condCodeOp());
1172 if (NeedsWinCFIStackAlloc) {
1173 SEH = BuildMI(MF, dl, TII.get(ARM::SEH_StackAlloc))
1174 .addImm(NumBytes)
1175 .addImm(/*Wide=*/1)
1177 MBB.insertAfter(Instr, SEH);
1178 }
1179 NumBytes = 0;
1180 }
1181
1182 if (NumBytes) {
1183 // Adjust SP after all the callee-save spills.
1184 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
1185 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
1186 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
1187 else {
1188 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
1190 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
1191 }
1192
1193 if (HasFP && isARM)
1194 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
1195 // Note it's not safe to do this in Thumb2 mode because it would have
1196 // taken two instructions:
1197 // mov sp, r7
1198 // sub sp, #24
1199 // If an interrupt is taken between the two instructions, then sp is in
1200 // an inconsistent state (pointing to the middle of callee-saved area).
1201 // The interrupt handler can end up clobbering the registers.
1202 AFI->setShouldRestoreSPFromFP(true);
1203 }
1204
1205 // Set FP to point to the stack slot that contains the previous FP.
1206 // For iOS, FP is R7, which has now been stored in spill area 1.
1207 // Otherwise, if this is not iOS, all the callee-saved registers go
1208 // into spill area 1, including the FP in R11. In either case, it
1209 // is in area one and the adjustment needs to take place just after
1210 // that push.
1212 if (HasFP) {
1213 MachineBasicBlock::iterator FPPushInst;
1214 // Offset from SP immediately after the push which saved the FP to the FP
1215 // save slot.
1216 int64_t FPOffsetAfterPush;
1217 switch (FramePtrSpillArea) {
1218 case SpillArea::GPRCS1:
1219 FPPushInst = GPRCS1Push;
1220 FPOffsetAfterPush = MFI.getObjectOffset(FramePtrSpillFI) +
1221 ArgRegsSaveSize + FPCXTSaveSize +
1222 sizeOfSPAdjustment(*FPPushInst);
1223 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS1, offset "
1224 << FPOffsetAfterPush << " after that push\n");
1225 break;
1226 case SpillArea::GPRCS2:
1227 FPPushInst = GPRCS2Push;
1228 FPOffsetAfterPush = MFI.getObjectOffset(FramePtrSpillFI) +
1229 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1230 sizeOfSPAdjustment(*FPPushInst);
1231 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS2, offset "
1232 << FPOffsetAfterPush << " after that push\n");
1233 break;
1234 case SpillArea::GPRCS3:
1235 FPPushInst = GPRCS3Push;
1236 FPOffsetAfterPush = MFI.getObjectOffset(FramePtrSpillFI) +
1237 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1238 FPStatusSize + GPRCS2Size + DPRCS1Size + DPRGapSize +
1239 sizeOfSPAdjustment(*FPPushInst);
1240 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS3, offset "
1241 << FPOffsetAfterPush << " after that push\n");
1242 break;
1243 default:
1244 llvm_unreachable("frame pointer in unknown spill area");
1245 break;
1246 }
1247 AfterPush = std::next(FPPushInst);
1248 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1249 assert(FPOffsetAfterPush == 0);
1250
1251 // Emit the MOV or ADD to set up the frame pointer register.
1252 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, dl, TII,
1253 FramePtr, ARM::SP, FPOffsetAfterPush,
1255
1256 if (!NeedsWinCFI) {
1257 // Emit DWARF info to find the CFA using the frame pointer from this
1258 // point onward.
1259 CFIInstBuilder CFIBuilder(MBB, AfterPush, MachineInstr::FrameSetup);
1260 if (FPOffsetAfterPush != 0)
1261 CFIBuilder.buildDefCFA(FramePtr, -MFI.getObjectOffset(FramePtrSpillFI));
1262 else
1263 CFIBuilder.buildDefCFARegister(FramePtr);
1264 }
1265 }
1266
1267 // Emit a SEH opcode indicating the prologue end. The rest of the prologue
1268 // instructions below don't need to be replayed to unwind the stack.
1269 if (NeedsWinCFI && MBBI != MBB.begin()) {
1271 if (HasFP && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1272 End = AfterPush;
1274 BuildMI(MBB, End, dl, TII.get(ARM::SEH_PrologEnd))
1276 MF.setHasWinCFI(true);
1277 }
1278
1279 // Now that the prologue's actual instructions are finalised, we can insert
1280 // the necessary DWARF cf instructions to describe the situation. Start by
1281 // recording where each register ended up:
1282 if (!NeedsWinCFI) {
1283 for (const auto &Entry : reverse(CSI)) {
1284 MCRegister Reg = Entry.getReg();
1285 int FI = Entry.getFrameIdx();
1287 switch (getSpillArea(Reg, PushPopSplit, AFI->getNumAlignedDPRCS2Regs(),
1288 RegInfo)) {
1289 case SpillArea::GPRCS1:
1290 CFIPos = std::next(GPRCS1Push);
1291 break;
1292 case SpillArea::GPRCS2:
1293 CFIPos = std::next(GPRCS2Push);
1294 break;
1295 case SpillArea::DPRCS1:
1296 CFIPos = std::next(DPRCS1Push);
1297 break;
1298 case SpillArea::GPRCS3:
1299 CFIPos = std::next(GPRCS3Push);
1300 break;
1302 case SpillArea::FPCXT:
1303 case SpillArea::DPRCS2:
1304 // FPCXT and DPRCS2 are not represented in the DWARF info.
1305 break;
1306 }
1307
1308 if (CFIPos.isValid()) {
1310 .buildOffset(Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg,
1311 MFI.getObjectOffset(FI));
1312 }
1313 }
1314 }
1315
1316 // Now we can emit descriptions of where the canonical frame address was
1317 // throughout the process. If we have a frame pointer, it takes over the job
1318 // half-way through, so only the first few .cfi_def_cfa_offset instructions
1319 // actually get emitted.
1320 if (!NeedsWinCFI) {
1321 LLVM_DEBUG(DefCFAOffsetCandidates.dump());
1322 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
1323 }
1324
1325 if (STI.isTargetELF() && hasFP(MF))
1327 AFI->getFramePtrSpillOffset());
1328
1329 AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
1330 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1331 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1332 AFI->setFPStatusSavesSize(FPStatusSize);
1333 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
1334 AFI->setDPRCalleeSavedArea1Size(DPRCS1Size);
1335 AFI->setGPRCalleeSavedArea3Size(GPRCS3Size);
1336
1337 // If we need dynamic stack realignment, do it here. Be paranoid and make
1338 // sure if we also have VLAs, we have a base pointer for frame access.
1339 // If aligned NEON registers were spilled, the stack has already been
1340 // realigned.
1341 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) {
1342 Align MaxAlign = MFI.getMaxAlign();
1344 if (!AFI->isThumbFunction()) {
1345 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
1346 false);
1347 } else {
1348 // We cannot use sp as source/dest register here, thus we're using r4 to
1349 // perform the calculations. We're emitting the following sequence:
1350 // mov r4, sp
1351 // -- use emitAligningInstructions to produce best sequence to zero
1352 // -- out lower bits in r4
1353 // mov sp, r4
1354 // FIXME: It will be better just to find spare register here.
1355 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
1356 .addReg(ARM::SP, RegState::Kill)
1358 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
1359 false);
1360 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1361 .addReg(ARM::R4, RegState::Kill)
1363 }
1364
1365 AFI->setShouldRestoreSPFromFP(true);
1366 }
1367
1368 // If we need a base pointer, set it up here. It's whatever the value
1369 // of the stack pointer is at this point. Any variable size objects
1370 // will be allocated after this, so we can still use the base pointer
1371 // to reference locals.
1372 // FIXME: Clarify FrameSetup flags here.
1373 if (RegInfo->hasBasePointer(MF) && !MBB.isEHFuncletEntry()) {
1374 if (isARM)
1375 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
1376 .addReg(ARM::SP)
1378 .add(condCodeOp());
1379 else
1380 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
1381 .addReg(ARM::SP)
1383 }
1384
1385 // If the frame has variable sized objects then the epilogue must restore
1386 // the sp from fp. We can assume there's an FP here since hasFP already
1387 // checks for hasVarSizedObjects.
1388 if (MFI.hasVarSizedObjects())
1389 AFI->setShouldRestoreSPFromFP(true);
1390}
1391
1393 MachineBasicBlock &MBB) const {
1394 MachineFrameInfo &MFI = MF.getFrameInfo();
1396 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1397 const ARMBaseInstrInfo &TII =
1398 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1399 assert(!AFI->isThumb1OnlyFunction() &&
1400 "This emitEpilogue does not support Thumb1!");
1401 bool isARM = !AFI->isThumbFunction();
1403 STI.getPushPopSplitVariation(MF);
1404
1405 LLVM_DEBUG(dbgs() << "Emitting epilogue for " << MF.getName() << "\n");
1406
1407 // Amount of stack space we reserved next to incoming args for either
1408 // varargs registers or stack arguments in tail calls made by this function.
1409 unsigned ReservedArgStack = AFI->getArgRegsSaveSize();
1410
1411 // How much of the stack used by incoming arguments this function is expected
1412 // to restore in this particular epilogue.
1413 int IncomingArgStackToRestore = getArgumentStackToRestore(MF, MBB);
1414 int NumBytes = (int)MFI.getStackSize();
1415 Register FramePtr = RegInfo->getFrameRegister(MF);
1416
1417 // All calls are tail calls in GHC calling conv, and functions have no
1418 // prologue/epilogue.
1420 return;
1421
1422 // First put ourselves on the first (from top) terminator instructions.
1423 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1424 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1425
1426 MachineBasicBlock::iterator RangeStart;
1427 if (!AFI->hasStackFrame()) {
1428 if (MF.hasWinCFI()) {
1429 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
1431 RangeStart = initMBBRange(MBB, MBBI);
1432 }
1433
1434 if (NumBytes + IncomingArgStackToRestore != 0)
1435 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1436 NumBytes + IncomingArgStackToRestore,
1438 } else {
1439 // Unwind MBBI to point to first LDR / VLDRD.
1440 if (MBBI != MBB.begin()) {
1441 do {
1442 --MBBI;
1443 } while (MBBI != MBB.begin() &&
1445 if (!MBBI->getFlag(MachineInstr::FrameDestroy))
1446 ++MBBI;
1447 }
1448
1449 if (MF.hasWinCFI()) {
1450 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
1452 RangeStart = initMBBRange(MBB, MBBI);
1453 }
1454
1455 // Move SP to start of FP callee save spill area.
1456 NumBytes -=
1457 (ReservedArgStack + AFI->getFPCXTSaveAreaSize() +
1461
1462 // Reset SP based on frame pointer only if the stack frame extends beyond
1463 // frame pointer stack slot or target is ELF and the function has FP.
1464 if (AFI->shouldRestoreSPFromFP()) {
1465 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1466 if (NumBytes) {
1467 if (isARM)
1468 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1469 ARMCC::AL, 0, TII,
1471 else {
1472 // It's not possible to restore SP from FP in a single instruction.
1473 // For iOS, this looks like:
1474 // mov sp, r7
1475 // sub sp, #24
1476 // This is bad, if an interrupt is taken after the mov, sp is in an
1477 // inconsistent state.
1478 // Use the first callee-saved register as a scratch register.
1479 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
1480 "No scratch register to restore SP from FP!");
1481 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
1483 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1484 .addReg(ARM::R4)
1487 }
1488 } else {
1489 // Thumb2 or ARM.
1490 if (isARM)
1491 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
1494 .add(condCodeOp())
1496 else
1497 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1501 }
1502 } else if (NumBytes &&
1503 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
1504 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
1506
1507 // Increment past our save areas.
1508 if (AFI->getGPRCalleeSavedArea3Size()) {
1510 (void)PushPopSplit;
1511 MBBI++;
1512 }
1513
1514 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedArea1Size()) {
1515 MBBI++;
1516 // Since vpop register list cannot have gaps, there may be multiple vpop
1517 // instructions in the epilogue.
1518 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
1519 MBBI++;
1520 }
1521 if (AFI->getDPRCalleeSavedGapSize()) {
1522 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
1523 "unexpected DPR alignment gap");
1524 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(),
1526 }
1527
1528 if (AFI->getGPRCalleeSavedArea2Size()) {
1530 (void)PushPopSplit;
1531 MBBI++;
1532 }
1533 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
1534
1535 if (ReservedArgStack || IncomingArgStackToRestore) {
1536 assert((int)ReservedArgStack + IncomingArgStackToRestore >= 0 &&
1537 "attempting to restore negative stack amount");
1538 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1539 ReservedArgStack + IncomingArgStackToRestore,
1541 }
1542
1543 // Validate PAC, It should have been already popped into R12. For CMSE entry
1544 // function, the validation instruction is emitted during expansion of the
1545 // tBXNS_RET, since the validation must use the value of SP at function
1546 // entry, before saving, resp. after restoring, FPCXTNS.
1547 if (AFI->shouldSignReturnAddress() && !AFI->isCmseNSEntryFunction()) {
1548 bool CanUseBXAut =
1549 STI.isThumb() && STI.hasV8_1MMainlineOps() && STI.hasPACBTI();
1550 auto TMBBI = MBB.getFirstTerminator();
1551 bool IsBXReturn =
1552 TMBBI != MBB.end() && TMBBI->getOpcode() == ARM::tBX_RET;
1553 if (IsBXReturn && CanUseBXAut)
1554 TMBBI->setDesc(STI.getInstrInfo()->get(ARM::t2BXAUT_RET));
1555 else
1556 BuildMI(MBB, MBBI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2AUT));
1557 }
1558 }
1559
1560 if (MF.hasWinCFI()) {
1561 insertSEHRange(MBB, RangeStart, MBB.end(), TII, MachineInstr::FrameDestroy);
1562 BuildMI(MBB, MBB.end(), dl, TII.get(ARM::SEH_EpilogEnd))
1564 }
1565}
1566
1567/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1568/// debug info. It's the same as what we use for resolving the code-gen
1569/// references for now. FIXME: This can go wrong when references are
1570/// SP-relative and simple call frames aren't used.
1572 int FI,
1573 Register &FrameReg) const {
1574 return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
1575}
1576
1579 int FI) const {
1580 const MachineFrameInfo &MFI = MF.getFrameInfo();
1581 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1583}
1584
1586 int FI, Register &FrameReg,
1587 int SPAdj) const {
1588 const MachineFrameInfo &MFI = MF.getFrameInfo();
1589 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1590 MF.getSubtarget().getRegisterInfo());
1591 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1592 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1593 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
1594 bool isFixed = MFI.isFixedObjectIndex(FI);
1595
1596 FrameReg = ARM::SP;
1597 Offset += SPAdj;
1598
1599 // SP can move around if there are allocas. We may also lose track of SP
1600 // when emergency spilling inside a non-reserved call frame setup.
1601 bool hasMovingSP = !hasReservedCallFrame(MF);
1602
1603 // When dynamically realigning the stack, use the frame pointer for
1604 // parameters, and the stack/base pointer for locals.
1605 if (RegInfo->hasStackRealignment(MF)) {
1606 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
1607 if (isFixed) {
1608 FrameReg = RegInfo->getFrameRegister(MF);
1609 Offset = FPOffset;
1610 } else if (hasMovingSP) {
1611 assert(RegInfo->hasBasePointer(MF) &&
1612 "VLAs and dynamic stack alignment, but missing base pointer!");
1613 FrameReg = RegInfo->getBaseRegister();
1614 Offset -= SPAdj;
1615 }
1616 return Offset;
1617 }
1618
1619 // If there is a frame pointer, use it when we can.
1620 if (hasFP(MF) && AFI->hasStackFrame()) {
1621 // Use frame pointer to reference fixed objects. Use it for locals if
1622 // there are VLAs (and thus the SP isn't reliable as a base).
1623 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
1624 FrameReg = RegInfo->getFrameRegister(MF);
1625 return FPOffset;
1626 } else if (hasMovingSP) {
1627 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
1628 if (AFI->isThumb2Function()) {
1629 // Try to use the frame pointer if we can, else use the base pointer
1630 // since it's available. This is handy for the emergency spill slot, in
1631 // particular.
1632 if (FPOffset >= -255 && FPOffset < 0) {
1633 FrameReg = RegInfo->getFrameRegister(MF);
1634 return FPOffset;
1635 }
1636 }
1637 } else if (AFI->isThumbFunction()) {
1638 // Prefer SP to base pointer, if the offset is suitably aligned and in
1639 // range as the effective range of the immediate offset is bigger when
1640 // basing off SP.
1641 // Use add <rd>, sp, #<imm8>
1642 // ldr <rd>, [sp, #<imm8>]
1643 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
1644 return Offset;
1645 // In Thumb2 mode, the negative offset is very limited. Try to avoid
1646 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
1647 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
1648 FrameReg = RegInfo->getFrameRegister(MF);
1649 return FPOffset;
1650 }
1651 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
1652 // Otherwise, use SP or FP, whichever is closer to the stack slot.
1653 FrameReg = RegInfo->getFrameRegister(MF);
1654 return FPOffset;
1655 }
1656 }
1657 // Use the base pointer if we have one.
1658 // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
1659 // That can happen if we forced a base pointer for a large call frame.
1660 if (RegInfo->hasBasePointer(MF)) {
1661 FrameReg = RegInfo->getBaseRegister();
1662 Offset -= SPAdj;
1663 }
1664 return Offset;
1665}
1666
1667void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
1670 unsigned StmOpc, unsigned StrOpc,
1671 bool NoGap,
1672 function_ref<bool(unsigned)> Func) const {
1673 MachineFunction &MF = *MBB.getParent();
1676
1677 DebugLoc DL;
1678
1679 using RegAndKill = std::pair<unsigned, bool>;
1680
1682 unsigned i = CSI.size();
1683 while (i != 0) {
1684 unsigned LastReg = 0;
1685 for (; i != 0; --i) {
1686 MCRegister Reg = CSI[i-1].getReg();
1687 if (!Func(Reg))
1688 continue;
1689
1690 const MachineRegisterInfo &MRI = MF.getRegInfo();
1691 bool isLiveIn = MRI.isLiveIn(Reg);
1692 if (!isLiveIn && !MRI.isReserved(Reg))
1693 MBB.addLiveIn(Reg);
1694 // If NoGap is true, push consecutive registers and then leave the rest
1695 // for other instructions. e.g.
1696 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
1697 if (NoGap && LastReg && LastReg != Reg-1)
1698 break;
1699 LastReg = Reg;
1700 // Do not set a kill flag on values that are also marked as live-in. This
1701 // happens with the @llvm-returnaddress intrinsic and with arguments
1702 // passed in callee saved registers.
1703 // Omitting the kill flags is conservatively correct even if the live-in
1704 // is not used after all.
1705 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
1706 }
1707
1708 if (Regs.empty())
1709 continue;
1710
1711 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1712 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1713 });
1714
1715 if (Regs.size() > 1 || StrOpc== 0) {
1716 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1717 .addReg(ARM::SP)
1720 for (const auto &[Reg, Kill] : Regs)
1722 } else if (Regs.size() == 1) {
1723 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1724 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1725 .addReg(ARM::SP)
1727 .addImm(-4)
1729 }
1730 Regs.clear();
1731
1732 // Put any subsequent vpush instructions before this one: they will refer to
1733 // higher register numbers so need to be pushed first in order to preserve
1734 // monotonicity.
1735 if (MI != MBB.begin())
1736 --MI;
1737 }
1738}
1739
1740void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1743 unsigned LdmOpc, unsigned LdrOpc,
1744 bool isVarArg, bool NoGap,
1745 function_ref<bool(unsigned)> Func) const {
1746 MachineFunction &MF = *MBB.getParent();
1747 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1748 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1749 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1750 bool hasPAC = AFI->shouldSignReturnAddress();
1751 DebugLoc DL;
1752 bool isTailCall = false;
1753 bool isInterrupt = false;
1754 bool isTrap = false;
1755 bool isCmseEntry = false;
1757 STI.getPushPopSplitVariation(MF);
1758 if (MBB.end() != MI) {
1759 DL = MI->getDebugLoc();
1760 unsigned RetOpcode = MI->getOpcode();
1761 isTailCall =
1762 (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri ||
1763 RetOpcode == ARM::TCRETURNrinotr12);
1764 isInterrupt =
1765 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1766 isTrap = RetOpcode == ARM::TRAP || RetOpcode == ARM::tTRAP;
1767 isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
1768 }
1769
1770 SmallVector<unsigned, 4> Regs;
1771 unsigned i = CSI.size();
1772 while (i != 0) {
1773 unsigned LastReg = 0;
1774 bool DeleteRet = false;
1775 for (; i != 0; --i) {
1776 CalleeSavedInfo &Info = CSI[i-1];
1777 MCRegister Reg = Info.getReg();
1778 if (!Func(Reg))
1779 continue;
1780
1781 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1782 !isCmseEntry && !isTrap && AFI->getArgumentStackToRestore() == 0 &&
1783 STI.hasV5TOps() && MBB.succ_empty() && !hasPAC &&
1784 (PushPopSplit != ARMSubtarget::SplitR11WindowsSEH &&
1785 PushPopSplit != ARMSubtarget::SplitR11AAPCSSignRA)) {
1786 Reg = ARM::PC;
1787 // Fold the return instruction into the LDM.
1788 DeleteRet = true;
1789 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1790 }
1791
1792 // If NoGap is true, pop consecutive registers and then leave the rest
1793 // for other instructions. e.g.
1794 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1795 if (NoGap && LastReg && LastReg != Reg-1)
1796 break;
1797
1798 LastReg = Reg;
1799 Regs.push_back(Reg);
1800 }
1801
1802 if (Regs.empty())
1803 continue;
1804
1805 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
1806 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1807 });
1808
1809 if (Regs.size() > 1 || LdrOpc == 0) {
1810 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1811 .addReg(ARM::SP)
1814 for (unsigned Reg : Regs)
1815 MIB.addReg(Reg, getDefRegState(true));
1816 if (DeleteRet) {
1817 if (MI != MBB.end()) {
1818 MIB.copyImplicitOps(*MI);
1820 }
1821 }
1822 MI = MIB;
1823 } else if (Regs.size() == 1) {
1824 // If we adjusted the reg to PC from LR above, switch it back here. We
1825 // only do that for LDM.
1826 if (Regs[0] == ARM::PC)
1827 Regs[0] = ARM::LR;
1828 MachineInstrBuilder MIB =
1829 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1830 .addReg(ARM::SP, RegState::Define)
1831 .addReg(ARM::SP)
1833 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1834 // that refactoring is complete (eventually).
1835 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1836 MIB.addReg(0);
1838 } else
1839 MIB.addImm(4);
1840 MIB.add(predOps(ARMCC::AL));
1841 }
1842 Regs.clear();
1843
1844 // Put any subsequent vpop instructions after this one: they will refer to
1845 // higher register numbers so need to be popped afterwards.
1846 if (MI != MBB.end())
1847 ++MI;
1848 }
1849}
1850
1851void ARMFrameLowering::emitFPStatusSaves(MachineBasicBlock &MBB,
1854 unsigned PushOpc) const {
1855 MachineFunction &MF = *MBB.getParent();
1856 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1857
1859 auto RegPresent = [&CSI](MCRegister Reg) {
1860 return llvm::any_of(CSI, [Reg](const CalleeSavedInfo &C) {
1861 return C.getReg() == Reg;
1862 });
1863 };
1864
1865 // If we need to save FPSCR, then we must move FPSCR into R4 with the VMRS
1866 // instruction.
1867 if (RegPresent(ARM::FPSCR)) {
1868 BuildMI(MBB, MI, DebugLoc(), TII.get(ARM::VMRS), ARM::R4)
1871
1872 Regs.push_back(ARM::R4);
1873 }
1874
1875 // If we need to save FPEXC, then we must move FPEXC into R5 with the
1876 // VMRS_FPEXC instruction.
1877 if (RegPresent(ARM::FPEXC)) {
1878 BuildMI(MBB, MI, DebugLoc(), TII.get(ARM::VMRS_FPEXC), ARM::R5)
1881
1882 Regs.push_back(ARM::R5);
1883 }
1884
1885 // If neither FPSCR and FPEXC are present, then do nothing.
1886 if (Regs.size() == 0)
1887 return;
1888
1889 // Push both R4 and R5 onto the stack, if present.
1890 MachineInstrBuilder MIB =
1891 BuildMI(MBB, MI, DebugLoc(), TII.get(PushOpc), ARM::SP)
1892 .addReg(ARM::SP)
1895
1896 for (Register Reg : Regs) {
1897 MIB.addReg(Reg);
1898 }
1899}
1900
1901void ARMFrameLowering::emitFPStatusRestores(
1903 MutableArrayRef<CalleeSavedInfo> CSI, unsigned LdmOpc) const {
1904 MachineFunction &MF = *MBB.getParent();
1905 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1906
1907 auto RegPresent = [&CSI](MCRegister Reg) {
1908 return llvm::any_of(CSI, [Reg](const CalleeSavedInfo &C) {
1909 return C.getReg() == Reg;
1910 });
1911 };
1912
1913 // Do nothing if we don't need to restore any FP status registers.
1914 if (!RegPresent(ARM::FPSCR) && !RegPresent(ARM::FPEXC))
1915 return;
1916
1917 // Pop registers off of the stack.
1918 MachineInstrBuilder MIB =
1919 BuildMI(MBB, MI, DebugLoc(), TII.get(LdmOpc), ARM::SP)
1920 .addReg(ARM::SP)
1923
1924 // If FPSCR was saved, it will be popped into R4.
1925 if (RegPresent(ARM::FPSCR)) {
1926 MIB.addReg(ARM::R4, RegState::Define);
1927 }
1928
1929 // If FPEXC was saved, it will be popped into R5.
1930 if (RegPresent(ARM::FPEXC)) {
1931 MIB.addReg(ARM::R5, RegState::Define);
1932 }
1933
1934 // Move the FPSCR value back into the register with the VMSR instruction.
1935 if (RegPresent(ARM::FPSCR)) {
1936 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VMSR))
1937 .addReg(ARM::R4)
1940 }
1941
1942 // Move the FPEXC value back into the register with the VMSR_FPEXC
1943 // instruction.
1944 if (RegPresent(ARM::FPEXC)) {
1945 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VMSR_FPEXC))
1946 .addReg(ARM::R5)
1949 }
1950}
1951
1952/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1953/// starting from d8. Also insert stack realignment code and leave the stack
1954/// pointer pointing to the d8 spill slot.
1957 unsigned NumAlignedDPRCS2Regs,
1959 const TargetRegisterInfo *TRI) {
1960 MachineFunction &MF = *MBB.getParent();
1962 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1964 MachineFrameInfo &MFI = MF.getFrameInfo();
1965
1966 // Mark the D-register spill slots as properly aligned. Since MFI computes
1967 // stack slot layout backwards, this can actually mean that the d-reg stack
1968 // slot offsets can be wrong. The offset for d8 will always be correct.
1969 for (const CalleeSavedInfo &I : CSI) {
1970 unsigned DNum = I.getReg() - ARM::D8;
1971 if (DNum > NumAlignedDPRCS2Regs - 1)
1972 continue;
1973 int FI = I.getFrameIdx();
1974 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1975 // registers will be 8-byte aligned.
1976 MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16));
1977
1978 // The stack slot for D8 needs to be maximally aligned because this is
1979 // actually the point where we align the stack pointer. MachineFrameInfo
1980 // computes all offsets relative to the incoming stack pointer which is a
1981 // bit weird when realigning the stack. Any extra padding for this
1982 // over-alignment is not realized because the code inserted below adjusts
1983 // the stack pointer by numregs * 8 before aligning the stack pointer.
1984 if (DNum == 0)
1985 MFI.setObjectAlignment(FI, MFI.getMaxAlign());
1986 }
1987
1988 // Move the stack pointer to the d8 spill slot, and align it at the same
1989 // time. Leave the stack slot address in the scratch register r4.
1990 //
1991 // sub r4, sp, #numregs * 8
1992 // bic r4, r4, #align - 1
1993 // mov sp, r4
1994 //
1995 bool isThumb = AFI->isThumbFunction();
1996 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1997 AFI->setShouldRestoreSPFromFP(true);
1998
1999 // sub r4, sp, #numregs * 8
2000 // The immediate is <= 64, so it doesn't need any special encoding.
2001 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
2002 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
2003 .addReg(ARM::SP)
2004 .addImm(8 * NumAlignedDPRCS2Regs)
2006 .add(condCodeOp());
2007
2008 Align MaxAlign = MF.getFrameInfo().getMaxAlign();
2009 // We must set parameter MustBeSingleInstruction to true, since
2010 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
2011 // stack alignment. Luckily, this can always be done since all ARM
2012 // architecture versions that support Neon also support the BFC
2013 // instruction.
2014 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
2015
2016 // mov sp, r4
2017 // The stack pointer must be adjusted before spilling anything, otherwise
2018 // the stack slots could be clobbered by an interrupt handler.
2019 // Leave r4 live, it is used below.
2020 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
2021 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
2022 .addReg(ARM::R4)
2024 if (!isThumb)
2025 MIB.add(condCodeOp());
2026
2027 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
2028 // r4 holds the stack slot address.
2029 unsigned NextReg = ARM::D8;
2030
2031 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
2032 // The writeback is only needed when emitting two vst1.64 instructions.
2033 if (NumAlignedDPRCS2Regs >= 6) {
2034 MCRegister SupReg =
2035 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2036 MBB.addLiveIn(SupReg);
2037 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
2038 .addReg(ARM::R4, RegState::Kill)
2039 .addImm(16)
2040 .addReg(NextReg)
2043 NextReg += 4;
2044 NumAlignedDPRCS2Regs -= 4;
2045 }
2046
2047 // We won't modify r4 beyond this point. It currently points to the next
2048 // register to be spilled.
2049 unsigned R4BaseReg = NextReg;
2050
2051 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
2052 if (NumAlignedDPRCS2Regs >= 4) {
2053 MCRegister SupReg =
2054 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2055 MBB.addLiveIn(SupReg);
2056 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
2057 .addReg(ARM::R4)
2058 .addImm(16)
2059 .addReg(NextReg)
2062 NextReg += 4;
2063 NumAlignedDPRCS2Regs -= 4;
2064 }
2065
2066 // 16-byte aligned vst1.64 with 2 d-regs.
2067 if (NumAlignedDPRCS2Regs >= 2) {
2068 MCRegister SupReg =
2069 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QPRRegClass);
2070 MBB.addLiveIn(SupReg);
2071 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
2072 .addReg(ARM::R4)
2073 .addImm(16)
2074 .addReg(SupReg)
2076 NextReg += 2;
2077 NumAlignedDPRCS2Regs -= 2;
2078 }
2079
2080 // Finally, use a vanilla vstr.64 for the odd last register.
2081 if (NumAlignedDPRCS2Regs) {
2082 MBB.addLiveIn(NextReg);
2083 // vstr.64 uses addrmode5 which has an offset scale of 4.
2084 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
2085 .addReg(NextReg)
2086 .addReg(ARM::R4)
2087 .addImm((NextReg - R4BaseReg) * 2)
2089 }
2090
2091 // The last spill instruction inserted should kill the scratch register r4.
2092 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
2093}
2094
2095/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
2096/// iterator to the following instruction.
2099 unsigned NumAlignedDPRCS2Regs) {
2100 // sub r4, sp, #numregs * 8
2101 // bic r4, r4, #align - 1
2102 // mov sp, r4
2103 ++MI; ++MI; ++MI;
2104 assert(MI->mayStore() && "Expecting spill instruction");
2105
2106 // These switches all fall through.
2107 switch(NumAlignedDPRCS2Regs) {
2108 case 7:
2109 ++MI;
2110 assert(MI->mayStore() && "Expecting spill instruction");
2111 [[fallthrough]];
2112 default:
2113 ++MI;
2114 assert(MI->mayStore() && "Expecting spill instruction");
2115 [[fallthrough]];
2116 case 1:
2117 case 2:
2118 case 4:
2119 assert(MI->killsRegister(ARM::R4, /*TRI=*/nullptr) && "Missed kill flag");
2120 ++MI;
2121 }
2122 return MI;
2123}
2124
2125/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
2126/// starting from d8. These instructions are assumed to execute while the
2127/// stack is still aligned, unlike the code inserted by emitPopInst.
2130 unsigned NumAlignedDPRCS2Regs,
2132 const TargetRegisterInfo *TRI) {
2133 MachineFunction &MF = *MBB.getParent();
2135 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
2137
2138 // Find the frame index assigned to d8.
2139 int D8SpillFI = 0;
2140 for (const CalleeSavedInfo &I : CSI)
2141 if (I.getReg() == ARM::D8) {
2142 D8SpillFI = I.getFrameIdx();
2143 break;
2144 }
2145
2146 // Materialize the address of the d8 spill slot into the scratch register r4.
2147 // This can be fairly complicated if the stack frame is large, so just use
2148 // the normal frame index elimination mechanism to do it. This code runs as
2149 // the initial part of the epilog where the stack and base pointers haven't
2150 // been changed yet.
2151 bool isThumb = AFI->isThumbFunction();
2152 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
2153
2154 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
2155 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
2156 .addFrameIndex(D8SpillFI)
2157 .addImm(0)
2159 .add(condCodeOp());
2160
2161 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
2162 unsigned NextReg = ARM::D8;
2163
2164 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
2165 if (NumAlignedDPRCS2Regs >= 6) {
2166 MCRegister SupReg =
2167 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2168 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
2169 .addReg(ARM::R4, RegState::Define)
2170 .addReg(ARM::R4, RegState::Kill)
2171 .addImm(16)
2174 NextReg += 4;
2175 NumAlignedDPRCS2Regs -= 4;
2176 }
2177
2178 // We won't modify r4 beyond this point. It currently points to the next
2179 // register to be spilled.
2180 unsigned R4BaseReg = NextReg;
2181
2182 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
2183 if (NumAlignedDPRCS2Regs >= 4) {
2184 MCRegister SupReg =
2185 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2186 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
2187 .addReg(ARM::R4)
2188 .addImm(16)
2191 NextReg += 4;
2192 NumAlignedDPRCS2Regs -= 4;
2193 }
2194
2195 // 16-byte aligned vld1.64 with 2 d-regs.
2196 if (NumAlignedDPRCS2Regs >= 2) {
2197 MCRegister SupReg =
2198 TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, &ARM::QPRRegClass);
2199 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
2200 .addReg(ARM::R4)
2201 .addImm(16)
2203 NextReg += 2;
2204 NumAlignedDPRCS2Regs -= 2;
2205 }
2206
2207 // Finally, use a vanilla vldr.64 for the remaining odd register.
2208 if (NumAlignedDPRCS2Regs)
2209 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
2210 .addReg(ARM::R4)
2211 .addImm(2 * (NextReg - R4BaseReg))
2213
2214 // Last store kills r4.
2215 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
2216}
2217
2221 if (CSI.empty())
2222 return false;
2223
2224 MachineFunction &MF = *MBB.getParent();
2227 STI.getPushPopSplitVariation(MF);
2228 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2229
2230 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
2231 unsigned PushOneOpc = AFI->isThumbFunction() ?
2232 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
2233 unsigned FltOpc = ARM::VSTMDDB_UPD;
2234 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
2235 // Compute PAC in R12.
2236 if (AFI->shouldSignReturnAddress()) {
2237 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2PAC))
2239 }
2240 // Save the non-secure floating point context.
2241 if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
2242 return C.getReg() == ARM::FPCXTNS;
2243 })) {
2244 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
2245 ARM::SP)
2246 .addReg(ARM::SP)
2247 .addImm(-4)
2249 }
2250
2251 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2252 RegInfo](unsigned Reg, SpillArea TestArea) {
2253 return getSpillArea(Reg, PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) ==
2254 TestArea;
2255 };
2256 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) {
2257 return CheckRegArea(Reg, SpillArea::GPRCS1);
2258 };
2259 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) {
2260 return CheckRegArea(Reg, SpillArea::GPRCS2);
2261 };
2262 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) {
2263 return CheckRegArea(Reg, SpillArea::DPRCS1);
2264 };
2265 auto IsGPRCS3 = [&CheckRegArea](unsigned Reg) {
2266 return CheckRegArea(Reg, SpillArea::GPRCS3);
2267 };
2268
2269 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS1);
2270 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS2);
2271 emitFPStatusSaves(MBB, MI, CSI, PushOpc);
2272 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, IsDPRCS1);
2273 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS3);
2274
2275 // The code above does not insert spill code for the aligned DPRCS2 registers.
2276 // The stack realignment code will be inserted between the push instructions
2277 // and these spills.
2278 if (NumAlignedDPRCS2Regs)
2279 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
2280
2281 return true;
2282}
2283
2287 if (CSI.empty())
2288 return false;
2289
2290 MachineFunction &MF = *MBB.getParent();
2292 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2293
2294 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
2295 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
2297 STI.getPushPopSplitVariation(MF);
2298
2299 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
2300 // registers. Do that here instead.
2301 if (NumAlignedDPRCS2Regs)
2302 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
2303
2304 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
2305 unsigned LdrOpc =
2306 AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
2307 unsigned FltOpc = ARM::VLDMDIA_UPD;
2308
2309 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2310 RegInfo](unsigned Reg, SpillArea TestArea) {
2311 return getSpillArea(Reg, PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) ==
2312 TestArea;
2313 };
2314 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) {
2315 return CheckRegArea(Reg, SpillArea::GPRCS1);
2316 };
2317 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) {
2318 return CheckRegArea(Reg, SpillArea::GPRCS2);
2319 };
2320 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) {
2321 return CheckRegArea(Reg, SpillArea::DPRCS1);
2322 };
2323 auto IsGPRCS3 = [&CheckRegArea](unsigned Reg) {
2324 return CheckRegArea(Reg, SpillArea::GPRCS3);
2325 };
2326
2327 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS3);
2328 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, IsDPRCS1);
2329 emitFPStatusRestores(MBB, MI, CSI, PopOpc);
2330 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS2);
2331 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS1);
2332
2333 return true;
2334}
2335
2336// FIXME: Make generic?
2338 const ARMBaseInstrInfo &TII,
2339 const ARMSubtarget &STI,
2341 BitVector &SavedRegs,
2342 bool BigFrameOffsets) {
2343 unsigned FnSize = 0;
2344
2345 bool KCFI = MF.getFunction().getParent()->getModuleFlag("kcfi");
2346
2347 if (MF.shouldSplitStack()) {
2348 // Split stack prologue saves r4,r5; makes a copy of sp and loads
2349 // a literal; compares the two, and if sp < literal, pushes
2350 // further registers and calls __morestack.
2351 FnSize += 0x24;
2352 }
2353
2354 // Count the number of saved high registers, which take more effort
2355 // to push and pop in the prologue and epilogue.
2356 unsigned SavedHighRegs = 0;
2357 for (auto Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11, ARM::R12})
2358 if (SavedRegs.test(Reg))
2359 ++SavedHighRegs;
2360
2361 // Size of a particularly large Thumb1 stack setup prologue:
2362 // update sp for variadic functions (2 bytes)
2363 // + push registers (2 bytes for PUSH {low regs} + 4 bytes per high register
2364 // that needs to be copied into a low reg and then pushed)
2365 // + frame pointer (might use r11, requiring pushing it first, 6 bytes)
2366 // + stack update (up to 12 bytes if a constant load is needed and a branch
2367 // required later to skip the constant)
2368 // + stack realignment (8, if needed)
2369 // + make base pointer (2).
2370 unsigned PrologueSize = 2 + 4 * SavedHighRegs + 6 + 12 + 2;
2371 if (RegInfo->hasStackRealignment(MF))
2372 PrologueSize += 8;
2373 FnSize += PrologueSize;
2374
2375 // Size of a large epilogue:
2376 // restore sp from frame pointer (6 bytes if it's in r11)
2377 // + pop registers (2 bytes + 4 per high register, as above)
2378 // + pop r11 if it was saved to make frame pointer (4 bytes)
2379 // + pop return address into a low reg (2 bytes)
2380 // + update sp to undo variadic function setup (2 bytes)
2381 // + BX to where you popped the return address (2 bytes)
2382 unsigned EpilogueSize = 6 + 2 + 4 * SavedHighRegs + 4 + 2 + 2;
2383
2384 bool FirstBlock = true;
2385 for (auto &MBB : MF) {
2386 if (!FirstBlock) {
2387 // We might have to insert padding to align the start of this basic
2388 // block.
2389 unsigned Alignment = MBB.getMaxBytesForAlignment();
2390 FnSize += Alignment;
2391 }
2392
2393 unsigned SizeBeforeThisBB = FnSize;
2394
2395 bool seenBranch = false, seenConstantLoad = false;
2396 for (auto &MI : MBB) {
2397 unsigned InstSize;
2398 switch (MI.getOpcode()) {
2399 case ARM::tADDframe:
2400 if (BigFrameOffsets)
2401 // We might need two ADD instructions, or even a constant
2402 // load. In the latter case we must count the constant as
2403 // well as the load instruction and the addition, for 8
2404 // bytes total.
2405 InstSize = 8;
2406 else
2407 InstSize = 2;
2408 break;
2409 case ARM::tLDRspi:
2410 case ARM::tSTRspi:
2411 if (BigFrameOffsets)
2412 // In a really nasty case, accessing a stack slot might
2413 // require saving and restoring a scratch register (4 bytes)
2414 // to make space to load (2 bytes) a constant (4 bytes) to
2415 // add to SP or FP (2 bytes) and then do the load/store to
2416 // the resulting register (2 bytes).
2417 InstSize = 14;
2418 else
2419 InstSize = 2;
2420 break;
2421 case TargetOpcode::COPY:
2422 // In some situations, COPY has to go via a high register, to
2423 // avoid corrupting the PSR flags: Thumb moves between low and
2424 // high registers don't write the PSR, whereas low/low moves
2425 // do.
2426 InstSize = 4; // may have to go via a high reg
2427 break;
2428 case ARM::MEMCPY:
2429 InstSize = 4; // becomes one LDMIA_UPD + STMIA_UPD pair
2430 break;
2431
2432 case ARM::Int_eh_sjlj_dispatchsetup:
2433 // Worst case is 6 bytes, loading a constant from a literal pool.
2434 InstSize = 6;
2435 break;
2436
2437 case ARM::tLDRpci_pic:
2438 InstSize = 4; // ordinary LDRpci + add to pc
2439 break;
2440
2441 case ARM::ADJCALLSTACKDOWN:
2442 case ARM::ADJCALLSTACKUP:
2443 InstSize = 2;
2444 break;
2445
2446 case ARM::tBLXNS_CALL:
2447 // A call across a CMSE trust boundary involves a lot of work. We must
2448 // clear all the registers that might contain our own secrets, which
2449 // means pushing them first. So first push low registers, then move
2450 // four high regs into them and push those too.
2451 InstSize = 2 + 2 * 4 + 2;
2452 // Then we must clear the low bit of the target register, because
2453 // instead of indicating Arm/Thumb it indicates the CMSE security
2454 // status. That takes two instructions.
2455 InstSize += 4;
2456 // Now actually clear all the registers, via a MOV for each one. This
2457 // includes argument registers as well as saved regs, so it can be
2458 // r1-r12 inclusive.
2459 InstSize += 2 * 12;
2460 // Clear the PSR flags (a wide instruction even in Armv8-M Baseline).
2461 InstSize += 4;
2462 // Perform the BLXNS call itself.
2463 InstSize += 2;
2464 // Now pop all the saved registers, which takes the same amount of
2465 // effort as pushing them did.
2466 InstSize += 2 + 2 * 4 + 2;
2467 break;
2468
2469 case ARM::tBXNS_RET:
2470 // When returning across a CMSE boundary, we must potentially clear all
2471 // the registers that we haven't restored to the caller's value: r0-r3
2472 // and r12. We also clear the PSR flags, and finally return via BXNS.
2473 InstSize = 5 * 2 + 4 + 2;
2474 break;
2475
2476 case TargetOpcode::LOAD_STACK_GUARD:
2477 if (STI.genExecuteOnly())
2478 // In execute-only code generation, it costs seven 2-byte
2479 // instructions (MOV + 3 ADD + 3 LSL) to load an arbitrary
2480 // 32-bit constant, plus two 4-byte MSRs to save/restore the
2481 // flags those instructions clobber. Then we load from the
2482 // resulting address with one more 2-byte instruction.
2483 InstSize = 7 * 2 + 2 * 4 + 8;
2484 else
2485 // If we're not generating execute-only code, the constant
2486 // just costs an LDR and a literal, and then another LDR is
2487 // needed to load from that address.
2488 InstSize = 2 * 2 + 4;
2489 break;
2490
2491 default:
2492 InstSize = TII.getInstSizeInBytes(MI);
2493 break;
2494 }
2495
2496 FnSize += InstSize;
2497
2498 // If the instruction loads a constant, score the size of the
2499 // constant, in case it can't be shared with other basic blocks.
2500 for (MachineMemOperand *MO : MI.memoperands()) {
2501 const PseudoSourceValue *PSV =
2503 MO->getPointerInfo().V);
2504 if (PSV && PSV->kind() == PseudoSourceValue::ConstantPool) {
2505 unsigned ConstSize = MO->getType().getSizeInBytes();
2506 FnSize += ConstSize;
2507 seenConstantLoad = true;
2508 }
2509 }
2510
2511 // If the instruction is a return or a tailcall, count the size
2512 // of an epilogue. (We do this for each return, in case the
2513 // epilogue must be duplicated.)
2514 if (MI.isReturn() || TII.isTailCall(MI)) {
2515 FnSize += EpilogueSize;
2516 }
2517
2518 // If the instruction is a call, and KCFI is enabled, then count the
2519 // cost of a KCFI_CHECK_Thumb1 pseudo.
2520 if (KCFI && MI.isCall() && MI.getCFIType()) {
2521 const MCInstrDesc &MCID = TII.get(ARM::KCFI_CHECK_Thumb1);
2522 FnSize += MCID.getSize();
2523 }
2524
2525 if (MI.isUnconditionalBranch())
2526 seenBranch = true;
2527 }
2528
2529 // If there's no branch instruction in the block and we saw a constant,
2530 // count a branch + realignment to 4 bytes, in case we have to branch round
2531 // it.
2532 if (seenConstantLoad && !seenBranch) {
2533 FnSize += 4;
2534 }
2535
2536 // Also, if the block is really, really big, then count an extra 4 bytes
2537 // (again branch + realignment) for potentially splitting it in order to
2538 // put constants in the middle, avoiding the problem of an LDR not being
2539 // able to reach all the way to the end. The LDR offset limit is 1024
2540 // bytes; the splitting itself adds some cost, but since any function this
2541 // large is likely to have already gone over the "must stack LR" limit, we
2542 // can keep things simple by assuming we split at half that rate.
2543 unsigned BBSize = FnSize - SizeBeforeThisBB;
2544 FnSize += 4 * BBSize / 512;
2545 }
2546 if (MF.getJumpTableInfo()) {
2547 for (auto &Table : MF.getJumpTableInfo()->getJumpTables()) {
2548 unsigned TableLen = Table.MBBs.size();
2549 unsigned TableSizeBytes = TableLen * 4;
2550 FnSize += TableSizeBytes;
2551 }
2552 }
2553 LLVM_DEBUG(dbgs() << "Estimated function size for " << MF.getName() << " = "
2554 << FnSize << " bytes\n");
2555 return FnSize;
2556}
2557
2558/// estimateRSStackSizeLimit - Look at each instruction that references stack
2559/// frames and return the stack size limit beyond which some of these
2560/// instructions will require a scratch register during their expansion later.
2561// FIXME: Move to TII?
2563 const TargetFrameLowering *TFI,
2564 bool &HasNonSPFrameIndex) {
2565 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2566 const ARMBaseInstrInfo &TII =
2567 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2568 unsigned Limit = (1 << 12) - 1;
2569 for (auto &MBB : MF) {
2570 for (auto &MI : MBB) {
2571 if (MI.isDebugInstr())
2572 continue;
2573 if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE)
2574 continue;
2575 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2576 if (!MI.getOperand(i).isFI())
2577 continue;
2578
2579 // When using ADDri to get the address of a stack object, 255 is the
2580 // largest offset guaranteed to fit in the immediate offset.
2581 if (MI.getOpcode() == ARM::ADDri) {
2582 Limit = std::min(Limit, (1U << 8) - 1);
2583 break;
2584 }
2585 // t2ADDri will not require an extra register, it can reuse the
2586 // destination.
2587 if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
2588 break;
2589
2590 const MCInstrDesc &MCID = MI.getDesc();
2591 const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i);
2592 if (RegClass && !RegClass->contains(ARM::SP))
2593 HasNonSPFrameIndex = true;
2594
2595 // Otherwise check the addressing mode.
2596 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
2598 case ARMII::AddrMode2:
2599 // Default 12 bit limit.
2600 break;
2601 case ARMII::AddrMode3:
2603 Limit = std::min(Limit, (1U << 8) - 1);
2604 break;
2606 Limit = std::min(Limit, ((1U << 8) - 1) * 2);
2607 break;
2608 case ARMII::AddrMode5:
2611 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
2612 break;
2614 // i12 supports only positive offset so these will be converted to
2615 // i8 opcodes. See llvm::rewriteT2FrameIndex.
2616 if (TFI->hasFP(MF) && AFI->hasStackFrame())
2617 Limit = std::min(Limit, (1U << 8) - 1);
2618 break;
2619 case ARMII::AddrMode4:
2620 case ARMII::AddrMode6:
2621 // Addressing modes 4 & 6 (load/store) instructions can't encode an
2622 // immediate offset for stack references.
2623 return 0;
2625 Limit = std::min(Limit, ((1U << 7) - 1) * 1);
2626 break;
2628 Limit = std::min(Limit, ((1U << 7) - 1) * 2);
2629 break;
2631 Limit = std::min(Limit, ((1U << 7) - 1) * 4);
2632 break;
2633 default:
2634 llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
2635 }
2636 break; // At most one FI per instruction
2637 }
2638 }
2639 }
2640
2641 return Limit;
2642}
2643
2644// In functions that realign the stack, it can be an advantage to spill the
2645// callee-saved vector registers after realigning the stack. The vst1 and vld1
2646// instructions take alignment hints that can improve performance.
2647static void
2649 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
2650 if (!MF.getSubtarget<ARMSubtarget>().getCLOpts().align_neon_spills)
2651 return;
2652
2653 // Naked functions don't spill callee-saved registers.
2654 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
2655 return;
2656
2657 // We are planning to use NEON instructions vst1 / vld1.
2658 if (!MF.getSubtarget<ARMSubtarget>().hasNEON())
2659 return;
2660
2661 // Don't bother if the default stack alignment is sufficiently high.
2663 return;
2664
2665 // Aligned spills require stack realignment.
2666 if (!static_cast<const ARMBaseRegisterInfo *>(
2668 return;
2669
2670 // We always spill contiguous d-registers starting from d8. Count how many
2671 // needs spilling. The register allocator will almost always use the
2672 // callee-saved registers in order, but it can happen that there are holes in
2673 // the range. Registers above the hole will be spilled to the standard DPRCS
2674 // area.
2675 unsigned NumSpills = 0;
2676 for (; NumSpills < 8; ++NumSpills)
2677 if (!SavedRegs.test(ARM::D8 + NumSpills))
2678 break;
2679
2680 // Don't do this for just one d-register. It's not worth it.
2681 if (NumSpills < 2)
2682 return;
2683
2684 // Spill the first NumSpills D-registers after realigning the stack.
2685 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
2686
2687 // A scratch register is required for the vst1 / vld1 instructions.
2688 SavedRegs.set(ARM::R4);
2689}
2690
2692 // For CMSE entry functions, we want to save the FPCXT_NS immediately
2693 // upon function entry (resp. restore it immediately before return)
2694 if (STI.hasV8_1MMainlineOps() &&
2696 return false;
2697
2698 // We are disabling shrinkwrapping for now when PAC is enabled, as
2699 // shrinkwrapping can cause clobbering of r12 when the PAC code is
2700 // generated. A follow-up patch will fix this in a more performant manner.
2702 true /* SpillsLR */))
2703 return false;
2704
2705 return true;
2706}
2707
2709 const MachineFunction &MF) const {
2710 const auto &Subtarget = MF.getSubtarget<ARMSubtarget>();
2711 return Subtarget.createAAPCSFrameChain() && hasFP(MF);
2712}
2713
2714// Thumb1 may require a spill when storing to a frame index through FP (or any
2715// access with execute-only), for cases where FP is a high register (R11). This
2716// scans the function for cases where this may happen.
2718 const TargetFrameLowering &TFI) {
2719 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2720 if (!AFI->isThumb1OnlyFunction())
2721 return false;
2722
2723 const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2724 for (const auto &MBB : MF)
2725 for (const auto &MI : MBB) {
2726 if (MI.isDebugInstr())
2727 continue;
2728 if (MI.getOpcode() == ARM::tSTRspi || MI.getOpcode() == ARM::tSTRi ||
2729 STI.genExecuteOnly())
2730 for (const auto &Op : MI.operands())
2731 if (Op.isFI()) {
2732 Register Reg;
2733 TFI.getFrameIndexReference(MF, Op.getIndex(), Reg);
2734 if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP)
2735 return true;
2736 }
2737 }
2738 return false;
2739}
2740
2742 BitVector &SavedRegs,
2743 RegScavenger *RS) const {
2745 // This tells PEI to spill the FP as if it is any other callee-save register
2746 // to take advantage the eliminateFrameIndex machinery. This also ensures it
2747 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
2748 // to combine multiple loads / stores.
2749 bool CanEliminateFrame = !(requiresAAPCSFrameRecord(MF) && hasFP(MF)) &&
2751 bool CS1Spilled = false;
2752 bool LRSpilled = false;
2753 unsigned NumGPRSpills = 0;
2754 unsigned NumFPRSpills = 0;
2755 SmallVector<unsigned, 4> UnspilledCS1GPRs;
2756 SmallVector<unsigned, 4> UnspilledCS2GPRs;
2757 const Function &F = MF.getFunction();
2758 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
2759 MF.getSubtarget().getRegisterInfo());
2760 const ARMBaseInstrInfo &TII =
2761 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2763 MachineFrameInfo &MFI = MF.getFrameInfo();
2766 (void)TRI; // Silence unused warning in non-assert builds.
2767 Register FramePtr = STI.getFramePointerReg();
2769 STI.getPushPopSplitVariation(MF);
2770
2771 // For a floating point interrupt, save these registers always, since LLVM
2772 // currently doesn't model reads/writes to these registers.
2773 if (F.hasFnAttribute("interrupt") && F.hasFnAttribute("save-fp")) {
2774 SavedRegs.set(ARM::FPSCR);
2775 SavedRegs.set(ARM::R4);
2776
2777 // This register will only be present on non-MClass registers.
2778 if (STI.isMClass()) {
2779 SavedRegs.reset(ARM::FPEXC);
2780 } else {
2781 SavedRegs.set(ARM::FPEXC);
2782 SavedRegs.set(ARM::R5);
2783 }
2784 }
2785
2786 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
2787 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
2788 // since it's not always possible to restore sp from fp in a single
2789 // instruction.
2790 // FIXME: It will be better just to find spare register here.
2791 if (AFI->isThumb2Function() &&
2792 (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
2793 SavedRegs.set(ARM::R4);
2794
2795 // If a stack probe will be emitted, spill R4 and LR, since they are
2796 // clobbered by the stack probe call.
2797 // This estimate should be a safe, conservative estimate. The actual
2798 // stack probe is enabled based on the size of the local objects;
2799 // this estimate also includes the varargs store size.
2800 if (STI.isTargetWindows() &&
2801 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
2802 SavedRegs.set(ARM::R4);
2803 SavedRegs.set(ARM::LR);
2804 }
2805
2806 if (AFI->isThumb1OnlyFunction()) {
2807 // Spill LR if Thumb1 function uses variable length argument lists.
2808 if (AFI->getArgRegsSaveSize() > 0)
2809 SavedRegs.set(ARM::LR);
2810
2811 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
2812 // requires stack alignment. We don't know for sure what the stack size
2813 // will be, but for this, an estimate is good enough. If there anything
2814 // changes it, it'll be a spill, which implies we've used all the registers
2815 // and so R4 is already used, so not marking it here will be OK.
2816 // FIXME: It will be better just to find spare register here.
2817 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
2818 MFI.estimateStackSize(MF) > 508)
2819 SavedRegs.set(ARM::R4);
2820 }
2821
2822 // See if we can spill vector registers to aligned stack.
2823 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
2824
2825 // Spill the BasePtr if it's used.
2826 if (RegInfo->hasBasePointer(MF))
2827 SavedRegs.set(RegInfo->getBaseRegister());
2828
2829 // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
2830 if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
2831 CanEliminateFrame = false;
2832
2833 // When return address signing is enabled R12 is treated as callee-saved.
2834 if (AFI->shouldSignReturnAddress())
2835 CanEliminateFrame = false;
2836
2837 // Don't spill FP if the frame can be eliminated. This is determined
2838 // by scanning the callee-save registers to see if any is modified.
2839 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
2840 for (unsigned i = 0; CSRegs[i]; ++i) {
2841 unsigned Reg = CSRegs[i];
2842 bool Spilled = false;
2843 if (SavedRegs.test(Reg)) {
2844 Spilled = true;
2845 CanEliminateFrame = false;
2846 }
2847
2848 if (!ARM::GPRRegClass.contains(Reg)) {
2849 if (Spilled) {
2850 if (ARM::SPRRegClass.contains(Reg))
2851 NumFPRSpills++;
2852 else if (ARM::DPRRegClass.contains(Reg))
2853 NumFPRSpills += 2;
2854 else if (ARM::QPRRegClass.contains(Reg))
2855 NumFPRSpills += 4;
2856 }
2857 continue;
2858 }
2859
2860 if (Spilled) {
2861 NumGPRSpills++;
2862
2863 if (PushPopSplit != ARMSubtarget::SplitR7) {
2864 if (Reg == ARM::LR)
2865 LRSpilled = true;
2866 CS1Spilled = true;
2867 continue;
2868 }
2869
2870 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
2871 switch (Reg) {
2872 case ARM::LR:
2873 LRSpilled = true;
2874 [[fallthrough]];
2875 case ARM::R0: case ARM::R1:
2876 case ARM::R2: case ARM::R3:
2877 case ARM::R4: case ARM::R5:
2878 case ARM::R6: case ARM::R7:
2879 CS1Spilled = true;
2880 break;
2881 default:
2882 break;
2883 }
2884 } else {
2885 if (PushPopSplit != ARMSubtarget::SplitR7) {
2886 UnspilledCS1GPRs.push_back(Reg);
2887 continue;
2888 }
2889
2890 switch (Reg) {
2891 case ARM::R0: case ARM::R1:
2892 case ARM::R2: case ARM::R3:
2893 case ARM::R4: case ARM::R5:
2894 case ARM::R6: case ARM::R7:
2895 case ARM::LR:
2896 UnspilledCS1GPRs.push_back(Reg);
2897 break;
2898 default:
2899 UnspilledCS2GPRs.push_back(Reg);
2900 break;
2901 }
2902 }
2903 }
2904
2905 bool ForceLRSpill = false;
2906
2907 // If any of the stack slot references may be out of range of an immediate
2908 // offset, make sure a register (or a spill slot) is available for the
2909 // register scavenger. Note that if we're indexing off the frame pointer, the
2910 // effective stack size is 4 bytes larger since the FP points to the stack
2911 // slot of the previous FP. Also, if we have variable sized objects in the
2912 // function, stack slot references will often be negative, and some of
2913 // our instructions are positive-offset only, so conservatively consider
2914 // that case to want a spill slot (or register) as well. Similarly, if
2915 // the function adjusts the stack pointer during execution and the
2916 // adjustments aren't already part of our stack size estimate, our offset
2917 // calculations may be off, so be conservative.
2918 // FIXME: We could add logic to be more precise about negative offsets
2919 // and which instructions will need a scratch register for them. Is it
2920 // worth the effort and added fragility?
2921 unsigned EstimatedStackSize =
2922 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
2923
2924 // Determine biggest (positive) SP offset in MachineFrameInfo.
2925 int MaxFixedOffset = 0;
2926 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
2927 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
2928 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
2929 }
2930
2931 bool HasFP = hasFP(MF);
2932 if (HasFP) {
2933 if (AFI->hasStackFrame())
2934 EstimatedStackSize += 4;
2935 } else {
2936 // If FP is not used, SP will be used to access arguments, so count the
2937 // size of arguments into the estimation.
2938 EstimatedStackSize += MaxFixedOffset;
2939 }
2940 EstimatedStackSize += 16; // For possible paddings.
2941
2942 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
2943 bool HasNonSPFrameIndex = false;
2944 if (AFI->isThumb1OnlyFunction()) {
2945 // For Thumb1, don't bother to iterate over the function. The only
2946 // instruction that requires an emergency spill slot is a store to a
2947 // frame index.
2948 //
2949 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
2950 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
2951 // a 5-bit unsigned immediate.
2952 //
2953 // We could try to check if the function actually contains a tSTRspi
2954 // that might need the spill slot, but it's not really important.
2955 // Functions with VLAs or extremely large call frames are rare, and
2956 // if a function is allocating more than 1KB of stack, an extra 4-byte
2957 // slot probably isn't relevant.
2958 //
2959 // A special case is the scenario where r11 is used as FP, where accesses
2960 // to a frame index will require its value to be moved into a low reg.
2961 // This is handled later on, once we are able to determine if we have any
2962 // fp-relative accesses.
2963 if (RegInfo->hasBasePointer(MF))
2964 EstimatedRSStackSizeLimit = (1U << 5) * 4;
2965 else
2966 EstimatedRSStackSizeLimit = (1U << 8) * 4;
2967 EstimatedRSFixedSizeLimit = (1U << 5) * 4;
2968 } else {
2969 EstimatedRSStackSizeLimit =
2970 estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
2971 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
2972 }
2973 // Final estimate of whether sp or bp-relative accesses might require
2974 // scavenging.
2975 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
2976
2977 // If the stack pointer moves and we don't have a base pointer, the
2978 // estimate logic doesn't work. The actual offsets might be larger when
2979 // we're constructing a call frame, or we might need to use negative
2980 // offsets from fp.
2981 bool HasMovingSP = MFI.hasVarSizedObjects() ||
2982 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
2983 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
2984
2985 // If we have a frame pointer, we assume arguments will be accessed
2986 // relative to the frame pointer. Check whether fp-relative accesses to
2987 // arguments require scavenging.
2988 //
2989 // We could do slightly better on Thumb1; in some cases, an sp-relative
2990 // offset would be legal even though an fp-relative offset is not.
2991 int MaxFPOffset = getMaxFPOffset(STI, *AFI, MF);
2992 bool HasLargeArgumentList =
2993 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
2994
2995 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
2996 HasLargeArgumentList || HasNonSPFrameIndex;
2997 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
2998 << "; EstimatedStack: " << EstimatedStackSize
2999 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
3000 << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
3001
3002 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
3003 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII, STI, RegInfo,
3004 SavedRegs, BigFrameOffsets);
3005
3006 if (FnSize >= (1 << 11)) {
3007 // Force LR to be spilled if the Thumb function size is > 2048. This
3008 // enables use of BL to implement far jump.
3009 CanEliminateFrame = false;
3010 ForceLRSpill = true;
3011 }
3012 }
3013
3014 if (BigFrameOffsets ||
3015 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
3016 AFI->setHasStackFrame(true);
3017
3018 // Save the FP if:
3019 // 1. We currently need it (HasFP), OR
3020 // 2. We might need it later due to stack realignment from aligned DPRCS2
3021 // saves (which will make hasFP() become true in emitPrologue).
3022 if (HasFP || (isFPReserved(MF) && AFI->getNumAlignedDPRCS2Regs() > 0)) {
3023 SavedRegs.set(FramePtr);
3024 // If the frame pointer is required by the ABI, also spill LR so that we
3025 // emit a complete frame record.
3027 !LRSpilled) {
3028 SavedRegs.set(ARM::LR);
3029 LRSpilled = true;
3030 NumGPRSpills++;
3031 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
3032 if (LRPos != UnspilledCS1GPRs.end())
3033 UnspilledCS1GPRs.erase(LRPos);
3034 }
3035 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
3036 if (FPPos != UnspilledCS1GPRs.end())
3037 UnspilledCS1GPRs.erase(FPPos);
3038 NumGPRSpills++;
3039 if (FramePtr == ARM::R7)
3040 CS1Spilled = true;
3041 }
3042
3043 // This is the number of extra spills inserted for callee-save GPRs which
3044 // would not otherwise be used by the function. When greater than zero it
3045 // guaranteees that it is possible to scavenge a register to hold the
3046 // address of a stack slot. On Thumb1, the register must be a valid operand
3047 // to tSTRi, i.e. r4-r7. For other subtargets, this is any GPR, i.e. r4-r11
3048 // or lr.
3049 //
3050 // If we don't insert a spill, we instead allocate an emergency spill
3051 // slot, which can be used by scavenging to spill an arbitrary register.
3052 //
3053 // We currently don't try to figure out whether any specific instruction
3054 // requires scavening an additional register.
3055 unsigned NumExtraCSSpill = 0;
3056
3057 if (AFI->isThumb1OnlyFunction()) {
3058 // For Thumb1-only targets, we need some low registers when we save and
3059 // restore the high registers (which aren't allocatable, but could be
3060 // used by inline assembly) because the push/pop instructions can not
3061 // access high registers. If necessary, we might need to push more low
3062 // registers to ensure that there is at least one free that can be used
3063 // for the saving & restoring, and preferably we should ensure that as
3064 // many as are needed are available so that fewer push/pop instructions
3065 // are required.
3066
3067 // Low registers which are not currently pushed, but could be (r4-r7).
3068 SmallVector<unsigned, 4> AvailableRegs;
3069
3070 // Unused argument registers (r0-r3) can be clobbered in the prologue for
3071 // free.
3072 int EntryRegDeficit = 0;
3073 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
3074 if (!MF.getRegInfo().isLiveIn(Reg)) {
3075 --EntryRegDeficit;
3077 << printReg(Reg, TRI)
3078 << " is unused argument register, EntryRegDeficit = "
3079 << EntryRegDeficit << "\n");
3080 }
3081 }
3082
3083 // Unused return registers can be clobbered in the epilogue for free.
3084 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
3086 << " return regs used, ExitRegDeficit = "
3087 << ExitRegDeficit << "\n");
3088
3089 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
3090 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
3091
3092 // r4-r6 can be used in the prologue if they are pushed by the first push
3093 // instruction.
3094 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
3095 if (SavedRegs.test(Reg)) {
3096 --RegDeficit;
3097 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3098 << " is saved low register, RegDeficit = "
3099 << RegDeficit << "\n");
3100 } else {
3101 AvailableRegs.push_back(Reg);
3102 LLVM_DEBUG(
3103 dbgs()
3104 << printReg(Reg, TRI)
3105 << " is non-saved low register, adding to AvailableRegs\n");
3106 }
3107 }
3108
3109 // r7 can be used if it is not being used as the frame pointer.
3110 if (!HasFP || FramePtr != ARM::R7) {
3111 if (SavedRegs.test(ARM::R7)) {
3112 --RegDeficit;
3113 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
3114 << RegDeficit << "\n");
3115 } else {
3116 AvailableRegs.push_back(ARM::R7);
3117 LLVM_DEBUG(
3118 dbgs()
3119 << "%r7 is non-saved low register, adding to AvailableRegs\n");
3120 }
3121 }
3122
3123 // Each of r8-r11 needs to be copied to a low register, then pushed.
3124 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
3125 if (SavedRegs.test(Reg)) {
3126 ++RegDeficit;
3127 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3128 << " is saved high register, RegDeficit = "
3129 << RegDeficit << "\n");
3130 }
3131 }
3132
3133 // LR can only be used by PUSH, not POP, and can't be used at all if the
3134 // llvm.returnaddress intrinsic is used. This is only worth doing if we
3135 // are more limited at function entry than exit.
3136 if ((EntryRegDeficit > ExitRegDeficit) &&
3137 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
3139 if (SavedRegs.test(ARM::LR)) {
3140 --RegDeficit;
3141 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
3142 << RegDeficit << "\n");
3143 } else {
3144 AvailableRegs.push_back(ARM::LR);
3145 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
3146 }
3147 }
3148
3149 // If there are more high registers that need pushing than low registers
3150 // available, push some more low registers so that we can use fewer push
3151 // instructions. This might not reduce RegDeficit all the way to zero,
3152 // because we can only guarantee that r4-r6 are available, but r8-r11 may
3153 // need saving.
3154 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
3155 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
3156 unsigned Reg = AvailableRegs.pop_back_val();
3157 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3158 << " to make up reg deficit\n");
3159 SavedRegs.set(Reg);
3160 NumGPRSpills++;
3161 CS1Spilled = true;
3162 assert(!MRI.isReserved(Reg) && "Should not be reserved");
3163 if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
3164 NumExtraCSSpill++;
3165 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
3166 if (Reg == ARM::LR)
3167 LRSpilled = true;
3168 }
3169 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
3170 << "\n");
3171 }
3172
3173 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
3174 // restore LR in that case.
3175 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
3176
3177 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
3178 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
3179 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
3180 SavedRegs.set(ARM::LR);
3181 NumGPRSpills++;
3183 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
3184 if (LRPos != UnspilledCS1GPRs.end())
3185 UnspilledCS1GPRs.erase(LRPos);
3186
3187 ForceLRSpill = false;
3188 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
3189 !AFI->isThumb1OnlyFunction())
3190 NumExtraCSSpill++;
3191 }
3192
3193 // If stack and double are 8-byte aligned and we are spilling an odd number
3194 // of GPRs, spill one extra callee save GPR so we won't have to pad between
3195 // the integer and double callee save areas.
3196 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
3197 const Align TargetAlign = getStackAlign();
3198 if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
3199 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
3200 for (unsigned Reg : UnspilledCS1GPRs) {
3201 // Don't spill high register if the function is thumb. In the case of
3202 // Windows on ARM, accept R11 (frame pointer)
3203 if (!AFI->isThumbFunction() ||
3204 (STI.isTargetWindows() && Reg == ARM::R11) ||
3205 isARMLowRegister(Reg) ||
3206 (Reg == ARM::LR && !ExpensiveLRRestore)) {
3207 SavedRegs.set(Reg);
3208 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3209 << " to make up alignment\n");
3210 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
3211 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
3212 NumExtraCSSpill++;
3213 break;
3214 }
3215 }
3216 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
3217 unsigned Reg = UnspilledCS2GPRs.front();
3218 SavedRegs.set(Reg);
3219 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3220 << " to make up alignment\n");
3221 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
3222 NumExtraCSSpill++;
3223 }
3224 }
3225
3226 // Estimate if we might need to scavenge registers at some point in order
3227 // to materialize a stack offset. If so, either spill one additional
3228 // callee-saved register or reserve a special spill slot to facilitate
3229 // register scavenging. Thumb1 needs a spill slot for stack pointer
3230 // adjustments and for frame index accesses when FP is high register,
3231 // even when the frame itself is small.
3232 unsigned RegsNeeded = 0;
3233 if (BigFrameOffsets || canSpillOnFrameIndexAccess(MF, *this)) {
3234 RegsNeeded++;
3235 // With thumb1 execute-only we may need an additional register for saving
3236 // and restoring the CPSR.
3237 if (AFI->isThumb1OnlyFunction() && STI.genExecuteOnly() && !STI.useMovt())
3238 RegsNeeded++;
3239 }
3240
3241 if (RegsNeeded > NumExtraCSSpill) {
3242 // If any non-reserved CS register isn't spilled, just spill one or two
3243 // extra. That should take care of it!
3244 unsigned NumExtras = TargetAlign.value() / 4;
3246 while (NumExtras && !UnspilledCS1GPRs.empty()) {
3247 unsigned Reg = UnspilledCS1GPRs.pop_back_val();
3248 if (!MRI.isReserved(Reg) &&
3249 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
3250 Extras.push_back(Reg);
3251 NumExtras--;
3252 }
3253 }
3254 // For non-Thumb1 functions, also check for hi-reg CS registers
3255 if (!AFI->isThumb1OnlyFunction()) {
3256 while (NumExtras && !UnspilledCS2GPRs.empty()) {
3257 unsigned Reg = UnspilledCS2GPRs.pop_back_val();
3258 if (!MRI.isReserved(Reg)) {
3259 Extras.push_back(Reg);
3260 NumExtras--;
3261 }
3262 }
3263 }
3264 if (NumExtras == 0) {
3265 for (unsigned Reg : Extras) {
3266 SavedRegs.set(Reg);
3267 if (!MRI.isPhysRegUsed(Reg))
3268 NumExtraCSSpill++;
3269 }
3270 }
3271 while ((RegsNeeded > NumExtraCSSpill) && RS) {
3272 // Reserve a slot closest to SP or frame pointer.
3273 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
3274 const TargetRegisterClass &RC = ARM::GPRRegClass;
3275 unsigned Size = TRI->getSpillSize(RC);
3276 Align Alignment = TRI->getSpillAlign(RC);
3277 RS->addScavengingFrameIndex(
3278 MFI.CreateSpillStackObject(Size, Alignment));
3279 --RegsNeeded;
3280 }
3281 }
3282 }
3283
3284 if (ForceLRSpill)
3285 SavedRegs.set(ARM::LR);
3286 AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
3287}
3288
3290 MachineFrameInfo &MFI = MF.getFrameInfo();
3291 if (!MFI.isCalleeSavedInfoValid())
3292 return;
3293
3294 // Check if all terminators do not implicitly use LR. Then we can 'restore' LR
3295 // into PC so it is not live out of the return block: Clear the Restored bit
3296 // in that case.
3297 for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) {
3298 if (Info.getReg() != ARM::LR)
3299 continue;
3300 if (all_of(MF, [](const MachineBasicBlock &MBB) {
3301 return all_of(MBB.terminators(), [](const MachineInstr &Term) {
3302 return !Term.isReturn() || Term.getOpcode() == ARM::LDMIA_RET ||
3303 Term.getOpcode() == ARM::t2LDMIA_RET ||
3304 Term.getOpcode() == ARM::tPOP_RET;
3305 });
3306 })) {
3307 Info.setRestored(false);
3308 break;
3309 }
3310 }
3311}
3312
3318
3320 BitVector &SavedRegs) const {
3322
3323 // If we have the "returned" parameter attribute which guarantees that we
3324 // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
3325 // record that fact for IPRA.
3326 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3327 if (AFI->getPreservesR0())
3328 SavedRegs.set(ARM::R0);
3329}
3330
3333 std::vector<CalleeSavedInfo> &CSI) const {
3334 // For CMSE entry functions, handle floating-point context as if it was a
3335 // callee-saved register.
3336 if (STI.hasV8_1MMainlineOps() &&
3338 CSI.emplace_back(ARM::FPCXTNS);
3339 CSI.back().setRestored(false);
3340 }
3341
3342 // For functions, which sign their return address, upon function entry, the
3343 // return address PAC is computed in R12. Treat R12 as a callee-saved register
3344 // in this case.
3345 const auto &AFI = *MF.getInfo<ARMFunctionInfo>();
3346 if (AFI.shouldSignReturnAddress()) {
3347 // The order of register must match the order we push them, because the
3348 // PEI assigns frame indices in that order. That order depends on the
3349 // PushPopSplitVariation, there are only two cases which we use with return
3350 // address signing:
3351 switch (STI.getPushPopSplitVariation(MF)) {
3353 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8
3354 CSI.insert(find_if(CSI,
3355 [=](const auto &CS) {
3356 MCRegister Reg = CS.getReg();
3357 return Reg == ARM::R10 || Reg == ARM::R11 ||
3358 Reg == ARM::R8 || Reg == ARM::R9 ||
3359 ARM::DPRRegClass.contains(Reg);
3360 }),
3361 CalleeSavedInfo(ARM::R12));
3362 break;
3364 // With SplitR11AAPCSSignRA, R12 will always be the highest-addressed CSR
3365 // on the stack.
3366 CSI.insert(CSI.begin(), CalleeSavedInfo(ARM::R12));
3367 break;
3370 "ABI-required frame pointers need a CSR split when signing return "
3371 "address.");
3372 CSI.insert(find_if(CSI,
3373 [=](const auto &CS) {
3374 MCRegister Reg = CS.getReg();
3375 return Reg != ARM::LR;
3376 }),
3377 CalleeSavedInfo(ARM::R12));
3378 break;
3379 default:
3380 llvm_unreachable("Unexpected CSR split with return address signing");
3381 }
3382 }
3383
3384 return false;
3385}
3386
3389 static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
3390 NumEntries = std::size(FixedSpillOffsets);
3391 return FixedSpillOffsets;
3392}
3393
3394MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
3397 const ARMBaseInstrInfo &TII =
3398 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3400 bool isARM = !AFI->isThumbFunction();
3401 DebugLoc dl = I->getDebugLoc();
3402 unsigned Opc = I->getOpcode();
3403 bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode();
3404 unsigned CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
3405
3406 assert(!AFI->isThumb1OnlyFunction() &&
3407 "This eliminateCallFramePseudoInstr does not support Thumb1!");
3408
3409 int PIdx = I->findFirstPredOperandIdx();
3410 ARMCC::CondCodes Pred = (PIdx == -1)
3411 ? ARMCC::AL
3412 : (ARMCC::CondCodes)I->getOperand(PIdx).getImm();
3413 unsigned PredReg = TII.getFramePred(*I);
3414
3415 if (!hasReservedCallFrame(MF)) {
3416 // Bail early if the callee is expected to do the adjustment.
3417 if (IsDestroy && CalleePopAmount != -1U)
3418 return MBB.erase(I);
3419
3420 // If we have alloca, convert as follows:
3421 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
3422 // ADJCALLSTACKUP -> add, sp, sp, amount
3423 unsigned Amount = TII.getFrameSize(*I);
3424 if (Amount != 0) {
3425 // We need to keep the stack aligned properly. To do this, we round the
3426 // amount of space needed for the outgoing arguments up to the next
3427 // alignment boundary.
3428 Amount = alignSPAdjust(Amount);
3429
3430 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
3431 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
3432 Pred, PredReg);
3433 } else {
3434 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
3435 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
3436 Pred, PredReg);
3437 }
3438 }
3439 } else if (CalleePopAmount != -1U) {
3440 // If the calling convention demands that the callee pops arguments from the
3441 // stack, we want to add it back if we have a reserved call frame.
3442 emitSPUpdate(isARM, MBB, I, dl, TII, -CalleePopAmount,
3443 MachineInstr::NoFlags, Pred, PredReg);
3444 }
3445 return MBB.erase(I);
3446}
3447
3448/// Get the minimum constant for ARM that is greater than or equal to the
3449/// argument. In ARM, constants can have any value that can be produced by
3450/// rotating an 8-bit value to the right by an even number of bits within a
3451/// 32-bit word.
3453 unsigned Shifted = 0;
3454
3455 if (Value == 0)
3456 return 0;
3457
3458 while (!(Value & 0xC0000000)) {
3459 Value = Value << 2;
3460 Shifted += 2;
3461 }
3462
3463 bool Carry = (Value & 0x00FFFFFF);
3464 Value = ((Value & 0xFF000000) >> 24) + Carry;
3465
3466 if (Value & 0x0000100)
3467 Value = Value & 0x000001FC;
3468
3469 if (Shifted > 24)
3470 Value = Value >> (Shifted - 24);
3471 else
3472 Value = Value << (24 - Shifted);
3473
3474 return Value;
3475}
3476
3477// The stack limit in the TCB is set to this many bytes above the actual
3478// stack limit.
3480
3481// Adjust the function prologue to enable split stacks. This currently only
3482// supports android and linux.
3483//
3484// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
3485// must be well defined in order to allow for consistent implementations of the
3486// __morestack helper function. The ABI is also not a normal ABI in that it
3487// doesn't follow the normal calling conventions because this allows the
3488// prologue of each function to be optimized further.
3489//
3490// Currently, the ABI looks like (when calling __morestack)
3491//
3492// * r4 holds the minimum stack size requested for this function call
3493// * r5 holds the stack size of the arguments to the function
3494// * the beginning of the function is 3 instructions after the call to
3495// __morestack
3496//
3497// Implementations of __morestack should use r4 to allocate a new stack, r5 to
3498// place the arguments on to the new stack, and the 3-instruction knowledge to
3499// jump directly to the body of the function when working on the new stack.
3500//
3501// An old (and possibly no longer compatible) implementation of __morestack for
3502// ARM can be found at [1].
3503//
3504// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
3506 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3507 unsigned Opcode;
3508 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
3509 bool Thumb = ST->isThumb();
3510 bool Thumb2 = ST->isThumb2();
3511
3512 // Sadly, this currently doesn't support varargs, platforms other than
3513 // android/linux. Note that thumb1/thumb2 are support for android/linux.
3514 if (MF.getFunction().isVarArg())
3515 report_fatal_error("Segmented stacks do not support vararg functions.");
3516 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
3517 report_fatal_error("Segmented stacks not supported on this platform.");
3518
3519 MachineFrameInfo &MFI = MF.getFrameInfo();
3520 const ARMBaseInstrInfo &TII =
3521 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3523 DebugLoc DL;
3524
3525 if (!MFI.needsSplitStackProlog())
3526 return;
3527
3528 uint64_t StackSize = MFI.getStackSize();
3529
3530 // Use R4 and R5 as scratch registers.
3531 // We save R4 and R5 before use and restore them before leaving the function.
3532 unsigned ScratchReg0 = ARM::R4;
3533 unsigned ScratchReg1 = ARM::R5;
3534 unsigned MovOp = ST->useMovt() ? ARM::t2MOVi32imm : ARM::tMOVi32imm;
3535 uint64_t AlignedStackSize;
3536
3537 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
3538 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
3542
3543 // Grab everything that reaches PrologueMBB to update there liveness as well.
3544 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
3546 WalkList.push_back(&PrologueMBB);
3547
3548 do {
3549 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
3550 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
3551 if (BeforePrologueRegion.insert(PredBB).second)
3552 WalkList.push_back(PredBB);
3553 }
3554 } while (!WalkList.empty());
3555
3556 // The order in that list is important.
3557 // The blocks will all be inserted before PrologueMBB using that order.
3558 // Therefore the block that should appear first in the CFG should appear
3559 // first in the list.
3560 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
3561 PostStackMBB};
3562
3563 BeforePrologueRegion.insert_range(AddedBlocks);
3564
3565 for (const auto &LI : PrologueMBB.liveins()) {
3566 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
3567 PredBB->addLiveIn(LI);
3568 }
3569
3570 // Remove the newly added blocks from the list, since we know
3571 // we do not have to do the following updates for them.
3572 for (MachineBasicBlock *B : AddedBlocks) {
3573 BeforePrologueRegion.erase(B);
3574 MF.insert(PrologueMBB.getIterator(), B);
3575 }
3576
3577 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
3578 // Make sure the LiveIns are still sorted and unique.
3579 MBB->sortUniqueLiveIns();
3580 // Replace the edges to PrologueMBB by edges to the sequences
3581 // we are about to add, but only update for immediate predecessors.
3582 if (MBB->isSuccessor(&PrologueMBB))
3583 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
3584 }
3585
3586 // The required stack size that is aligned to ARM constant criterion.
3587 AlignedStackSize = alignToARMConstant(StackSize);
3588
3589 // When the frame size is less than 256 we just compare the stack
3590 // boundary directly to the value of the stack pointer, per gcc.
3591 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
3592
3593 // We will use two of the callee save registers as scratch registers so we
3594 // need to save those registers onto the stack.
3595 // We will use SR0 to hold stack limit and SR1 to hold the stack size
3596 // requested and arguments for __morestack().
3597 // SR0: Scratch Register #0
3598 // SR1: Scratch Register #1
3599 // push {SR0, SR1}
3600 if (Thumb) {
3601 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
3603 .addReg(ScratchReg0)
3604 .addReg(ScratchReg1);
3605 } else {
3606 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
3607 .addReg(ARM::SP, RegState::Define)
3608 .addReg(ARM::SP)
3610 .addReg(ScratchReg0)
3611 .addReg(ScratchReg1);
3612 }
3613
3614 // Emit the relevant DWARF information about the change in stack pointer as
3615 // well as where to find both r4 and r5 (the callee-save registers)
3616 if (!MF.usesWindowsUnwindInfo()) {
3617 CFIInstBuilder CFIBuilder(PrevStackMBB, MachineInstr::NoFlags);
3618 CFIBuilder.buildDefCFAOffset(8);
3619 CFIBuilder.buildOffset(ScratchReg1, -4);
3620 CFIBuilder.buildOffset(ScratchReg0, -8);
3621 }
3622
3623 // mov SR1, sp
3624 if (Thumb) {
3625 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
3626 .addReg(ARM::SP)
3628 } else if (CompareStackPointer) {
3629 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
3630 .addReg(ARM::SP)
3632 .add(condCodeOp());
3633 }
3634
3635 // sub SR1, sp, #StackSize
3636 if (!CompareStackPointer && Thumb) {
3637 if (AlignedStackSize < 256) {
3638 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
3639 .add(condCodeOp())
3640 .addReg(ScratchReg1)
3641 .addImm(AlignedStackSize)
3643 } else {
3644 if (Thumb2 || ST->genExecuteOnly()) {
3645 BuildMI(McrMBB, DL, TII.get(MovOp), ScratchReg0)
3646 .addImm(AlignedStackSize);
3647 } else {
3648 auto MBBI = McrMBB->end();
3649 auto RegInfo = STI.getRegisterInfo();
3650 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
3651 AlignedStackSize);
3652 }
3653 BuildMI(McrMBB, DL, TII.get(ARM::tSUBrr), ScratchReg1)
3654 .add(condCodeOp())
3655 .addReg(ScratchReg1)
3656 .addReg(ScratchReg0)
3658 }
3659 } else if (!CompareStackPointer) {
3660 if (AlignedStackSize < 256) {
3661 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
3662 .addReg(ARM::SP)
3663 .addImm(AlignedStackSize)
3665 .add(condCodeOp());
3666 } else {
3667 auto MBBI = McrMBB->end();
3668 auto RegInfo = STI.getRegisterInfo();
3669 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
3670 AlignedStackSize);
3671 BuildMI(McrMBB, DL, TII.get(ARM::SUBrr), ScratchReg1)
3672 .addReg(ARM::SP)
3673 .addReg(ScratchReg0)
3675 .add(condCodeOp());
3676 }
3677 }
3678
3679 if (Thumb && ST->isThumb1Only()) {
3680 if (ST->genExecuteOnly()) {
3681 BuildMI(GetMBB, DL, TII.get(MovOp), ScratchReg0)
3682 .addExternalSymbol("__STACK_LIMIT");
3683 } else {
3684 unsigned PCLabelId = ARMFI->createPICLabelUId();
3686 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
3688 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
3689
3690 // ldr SR0, [pc, offset(STACK_LIMIT)]
3691 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
3694 }
3695
3696 // ldr SR0, [SR0]
3697 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
3698 .addReg(ScratchReg0)
3699 .addImm(0)
3701 } else {
3702 // Get TLS base address from the coprocessor
3703 // mrc p15, #0, SR0, c13, c0, #3
3704 BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
3705 ScratchReg0)
3706 .addImm(15)
3707 .addImm(0)
3708 .addImm(13)
3709 .addImm(0)
3710 .addImm(3)
3712
3713 // Use the last tls slot on android and a private field of the TCP on linux.
3714 assert(ST->isTargetAndroid() || ST->isTargetLinux());
3715 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
3716
3717 // Get the stack limit from the right offset
3718 // ldr SR0, [sr0, #4 * TlsOffset]
3719 BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
3720 ScratchReg0)
3721 .addReg(ScratchReg0)
3722 .addImm(4 * TlsOffset)
3724 }
3725
3726 // Compare stack limit with stack size requested.
3727 // cmp SR0, SR1
3728 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
3729 BuildMI(GetMBB, DL, TII.get(Opcode))
3730 .addReg(ScratchReg0)
3731 .addReg(ScratchReg1)
3733
3734 // This jump is taken if StackLimit <= SP - stack required.
3735 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
3736 BuildMI(GetMBB, DL, TII.get(Opcode))
3737 .addMBB(PostStackMBB)
3739 .addReg(ARM::CPSR);
3740
3741 // Calling __morestack(StackSize, Size of stack arguments).
3742 // __morestack knows that the stack size requested is in SR0(r4)
3743 // and amount size of stack arguments is in SR1(r5).
3744
3745 // Pass first argument for the __morestack by Scratch Register #0.
3746 // The amount size of stack required
3747 if (Thumb) {
3748 if (AlignedStackSize < 256) {
3749 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
3750 .add(condCodeOp())
3751 .addImm(AlignedStackSize)
3753 } else {
3754 if (Thumb2 || ST->genExecuteOnly()) {
3755 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg0)
3756 .addImm(AlignedStackSize);
3757 } else {
3758 auto MBBI = AllocMBB->end();
3759 auto RegInfo = STI.getRegisterInfo();
3760 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
3761 AlignedStackSize);
3762 }
3763 }
3764 } else {
3765 if (AlignedStackSize < 256) {
3766 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
3767 .addImm(AlignedStackSize)
3769 .add(condCodeOp());
3770 } else {
3771 auto MBBI = AllocMBB->end();
3772 auto RegInfo = STI.getRegisterInfo();
3773 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
3774 AlignedStackSize);
3775 }
3776 }
3777
3778 // Pass second argument for the __morestack by Scratch Register #1.
3779 // The amount size of stack consumed to save function arguments.
3780 if (Thumb) {
3781 if (ARMFI->getArgumentStackSize() < 256) {
3782 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
3783 .add(condCodeOp())
3786 } else {
3787 if (Thumb2 || ST->genExecuteOnly()) {
3788 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg1)
3790 } else {
3791 auto MBBI = AllocMBB->end();
3792 auto RegInfo = STI.getRegisterInfo();
3793 RegInfo->emitLoadConstPool(
3794 *AllocMBB, MBBI, DL, ScratchReg1, 0,
3796 }
3797 }
3798 } else {
3799 if (alignToARMConstant(ARMFI->getArgumentStackSize()) < 256) {
3800 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
3803 .add(condCodeOp());
3804 } else {
3805 auto MBBI = AllocMBB->end();
3806 auto RegInfo = STI.getRegisterInfo();
3807 RegInfo->emitLoadConstPool(
3808 *AllocMBB, MBBI, DL, ScratchReg1, 0,
3810 }
3811 }
3812
3813 // push {lr} - Save return address of this function.
3814 if (Thumb) {
3815 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
3817 .addReg(ARM::LR);
3818 } else {
3819 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
3820 .addReg(ARM::SP, RegState::Define)
3821 .addReg(ARM::SP)
3823 .addReg(ARM::LR);
3824 }
3825
3826 // Emit the DWARF info about the change in stack as well as where to find the
3827 // previous link register
3828 if (!MF.usesWindowsUnwindInfo()) {
3829 CFIInstBuilder CFIBuilder(AllocMBB, MachineInstr::NoFlags);
3830 CFIBuilder.buildDefCFAOffset(12);
3831 CFIBuilder.buildOffset(ARM::LR, -12);
3832 }
3833
3834 // Call __morestack().
3835 if (Thumb) {
3836 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
3838 .addExternalSymbol("__morestack");
3839 } else {
3840 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
3841 .addExternalSymbol("__morestack");
3842 }
3843
3844 // pop {lr} - Restore return address of this original function.
3845 if (Thumb) {
3846 if (ST->isThumb1Only()) {
3847 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
3849 .addReg(ScratchReg0);
3850 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
3851 .addReg(ScratchReg0)
3853 } else {
3854 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
3855 .addReg(ARM::LR, RegState::Define)
3856 .addReg(ARM::SP, RegState::Define)
3857 .addReg(ARM::SP)
3858 .addImm(4)
3860 }
3861 } else {
3862 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
3863 .addReg(ARM::SP, RegState::Define)
3864 .addReg(ARM::SP)
3866 .addReg(ARM::LR);
3867 }
3868
3869 // Restore SR0 and SR1 in case of __morestack() was called.
3870 // __morestack() will skip PostStackMBB block so we need to restore
3871 // scratch registers from here.
3872 // pop {SR0, SR1}
3873 if (Thumb) {
3874 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
3876 .addReg(ScratchReg0)
3877 .addReg(ScratchReg1);
3878 } else {
3879 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
3880 .addReg(ARM::SP, RegState::Define)
3881 .addReg(ARM::SP)
3883 .addReg(ScratchReg0)
3884 .addReg(ScratchReg1);
3885 }
3886
3887 // Update the CFA offset now that we've popped
3888 if (!MF.usesWindowsUnwindInfo())
3890
3891 // Return from this function.
3892 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
3893
3894 // Restore SR0 and SR1 in case of __morestack() was not called.
3895 // pop {SR0, SR1}
3896 if (Thumb) {
3897 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
3899 .addReg(ScratchReg0)
3900 .addReg(ScratchReg1);
3901 } else {
3902 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
3903 .addReg(ARM::SP, RegState::Define)
3904 .addReg(ARM::SP)
3906 .addReg(ScratchReg0)
3907 .addReg(ScratchReg1);
3908 }
3909
3910 // Update the CFA offset now that we've popped
3911 if (!MF.usesWindowsUnwindInfo()) {
3912 CFIInstBuilder CFIBuilder(PostStackMBB, MachineInstr::NoFlags);
3913 CFIBuilder.buildDefCFAOffset(0);
3914
3915 // Tell debuggers that r4 and r5 are now the same as they were in the
3916 // previous function, that they're the "Same Value".
3917 CFIBuilder.buildSameValue(ScratchReg0);
3918 CFIBuilder.buildSameValue(ScratchReg1);
3919 }
3920
3921 // Organizing MBB lists
3922 PostStackMBB->addSuccessor(&PrologueMBB);
3923
3924 AllocMBB->addSuccessor(PostStackMBB);
3925
3926 GetMBB->addSuccessor(PostStackMBB);
3927 GetMBB->addSuccessor(AllocMBB);
3928
3929 McrMBB->addSuccessor(GetMBB);
3930
3931 PrevStackMBB->addSuccessor(McrMBB);
3932
3933#ifdef EXPENSIVE_CHECKS
3934 MF.verify();
3935#endif
3936}
static unsigned estimateRSStackSizeLimit(MachineFunction &MF)
Look at each instruction that references stack frames and return the stack size limit beyond which so...
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
SDValue Pred
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static bool isThumb(const MCSubtargetInfo &STI)
static MachineBasicBlock::iterator skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs)
Skip past the code inserted by emitAlignedDPRCS2Spills, and return an iterator to the following instr...
static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI, const TargetInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const unsigned Reg, const Align Alignment, const bool MustBeSingleInstruction)
Emit an instruction sequence that will align the address in register Reg by zero-ing out the lower bi...
static uint32_t alignToARMConstant(uint32_t Value)
Get the minimum constant for ARM that is greater than or equal to the argument.
static void checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs)
static void insertSEHRange(MachineBasicBlock &MBB, MachineBasicBlock::iterator Start, const MachineBasicBlock::iterator &End, const ARMBaseInstrInfo &TII, unsigned MIFlags)
static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF, const ARMBaseInstrInfo &TII, const ARMSubtarget &STI, const ARMBaseRegisterInfo *RegInfo, BitVector &SavedRegs, bool BigFrameOffsets)
static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI)
Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers starting from d8.
static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI)
Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers starting from d8.
static int getArgumentStackToRestore(MachineFunction &MF, MachineBasicBlock &MBB)
static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, const ARMBaseInstrInfo &TII, int NumBytes, unsigned MIFlags=MachineInstr::NoFlags, ARMCC::CondCodes Pred=ARMCC::AL, unsigned PredReg=0)
static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI, const TargetInstrInfo &TII, unsigned Flags)
SpillArea getSpillArea(Register Reg, ARMSubtarget::PushPopSplitVariation Variation, unsigned NumAlignedDPRCS2Regs, const ARMBaseRegisterInfo *RegInfo)
Get the spill area that Reg should be saved into in the prologue.
static bool canSpillOnFrameIndexAccess(const MachineFunction &MF, const TargetFrameLowering &TFI)
static bool WindowsRequiresStackProbe(const MachineFunction &MF, size_t StackSizeInBytes)
static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI, const MachineFunction &MF)
We need the offset of the frame pointer relative to other MachineFrameInfo offsets which are encoded ...
static MachineBasicBlock::iterator initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI)
static int sizeOfSPAdjustment(const MachineInstr &MI)
static const uint64_t kSplitStackAvailable
static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg, unsigned SrcReg, int NumBytes, unsigned MIFlags=MachineInstr::NoFlags, ARMCC::CondCodes Pred=ARMCC::AL, unsigned PredReg=0)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static const unsigned FramePtr
bool canRealignStack(const MachineFunction &MF) const override
static ARMConstantPoolSymbol * Create(LLVMContext &C, StringRef s, unsigned ID, unsigned char PCAdj, ARMCP::ARMCPModifier Modifier=ARMCP::no_modifier, bool AddCurrentAddress=false)
ARMConstantPoolValue - ARM specific constantpool value.
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF, int FI) const override
getNonLocalFrameIndexReference - This method returns the offset used to reference a frame index locat...
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - Provide a base+offset reference to an FI slot for debug info.
bool keepFramePointer(const MachineFunction &MF) const
static void updateLRRestored(MachineFunction &MF)
Update the IsRestored flag on LR if it is spilled, based on the return instructions.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
ARMFrameLowering(const ARMSubtarget &sti)
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool requiresAAPCSFrameRecord(const MachineFunction &MF) const
bool isFPReserved(const MachineFunction &MF) const
isFPReserved - Return true if the frame pointer register should be considered a reserved register on ...
bool canSimplifyCallFramePseudos(const MachineFunction &MF) const override
canSimplifyCallFramePseudos - If there is a reserved call frame, the call frame pseudos can be simpli...
void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &MBB) const override
Adjust the prologue to have the function use segmented stacks.
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const override
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool hasFPImpl(const MachineFunction &MF) const override
hasFPImpl - Return true if the specified function should have a dedicated frame pointer register.
int ResolveFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg, int SPAdj) const
void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const override
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
const ARMSubtarget & STI
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool enableCalleeSaveSkip(const MachineFunction &MF) const override
Returns true if the target can safely skip saving callee-saved registers for noreturn nounwind functi...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
unsigned getFPCXTSaveAreaSize() const
unsigned getGPRCalleeSavedArea1Size() const
unsigned getDPRCalleeSavedGapSize() const
unsigned getDPRCalleeSavedArea1Size() const
void setDPRCalleeSavedArea1Offset(unsigned o)
void setGPRCalleeSavedArea2Size(unsigned s)
void setFramePtrSpillOffset(unsigned o)
unsigned getGPRCalleeSavedArea2Size() const
unsigned getNumAlignedDPRCS2Regs() const
void setGPRCalleeSavedArea1Size(unsigned s)
unsigned getArgumentStackToRestore() const
void setFPCXTSaveAreaSize(unsigned s)
unsigned getGPRCalleeSavedArea3Size() const
unsigned getFramePtrSpillOffset() const
unsigned getArgRegsSaveSize() const
void setGPRCalleeSavedArea2Offset(unsigned o)
void setGPRCalleeSavedArea1Offset(unsigned o)
void setDPRCalleeSavedArea1Size(unsigned s)
void setDPRCalleeSavedGapSize(unsigned s)
void setFPStatusSavesSize(unsigned s)
unsigned getArgumentStackSize() const
unsigned getReturnRegsCount() const
void setGPRCalleeSavedArea3Size(unsigned s)
unsigned getFPStatusSavesSize() const
const ARMBaseRegisterInfo * getRegisterInfo() const override
const ARMOptions & getCLOpts() const
enum PushPopSplitVariation getPushPopSplitVariation(const MachineFunction &MF) const
PushPopSplitVariation
How the push and pop instructions of callee saved general-purpose registers should be split.
@ SplitR11WindowsSEH
When the stack frame size is not known (because of variable-sized objects or realignment),...
@ SplitR7
R7 and LR must be adjacent, because R7 is the frame pointer, and must point to a frame record consist...
@ SplitR11AAPCSSignRA
When generating AAPCS-compilant frame chains, R11 is the frame pointer, and must be pushed adjacent t...
@ NoSplit
All GPRs can be pushed in a single instruction.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
Helper class for creating CFI instructions and inserting them into MIR.
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildDefCFARegister(MCRegister Reg) const
void buildSameValue(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Module * getParent()
Get the module that this global value is contained inside of...
Describe properties that are true of each instruction in the target description file.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
iterator_range< livein_iterator > liveins() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
LLVM_ABI unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool needsSplitStackProlog() const
Return true if this function requires a split stack prolog, even if it uses no stack space.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool isReturnAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int getStackProtectorIndex() const
Return the index for the stack protector object.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
bool isCalleeSavedInfoValid() const
Has the callee saved info been calculated yet?
LLVM_ABI BitVector getPristineRegs(const MachineFunction &MF) const
Return a set of physical registers that are pristine.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool framePointerIsReserved() const
Returns true if the frame pointer must always either point to a new frame record or be un-modified in...
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
bool needsWinCFI() const
True if this function uses SEH unwind opcodes and needs an unwind table entry.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool usesWindowsUnwindInfo() const
True if this function describes its unwind information with Windows SEH unwind opcodes (....
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
Representation of each machine instruction.
LLVM_ABI bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool isLiveIn(Register Reg) const
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Special value supplied for machine level alias analysis.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
virtual void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getAM2Opc(AddrOpc Opc, unsigned Imm12, ShiftOpc SO, unsigned IdxMode=0)
unsigned getSORegOpc(ShiftOpc ShOp, unsigned Imm)
@ D16
Only 16 D registers.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
static bool isARMLowRegister(MCRegister Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
static bool isSEHInstruction(const MachineInstr &MI)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, MachineFunction &MF, MachineInstr *MI, unsigned NumBytes)
Tries to add registers to the reglist of a given base-updating push/pop instruction to adjust the sta...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr RegState getDefRegState(bool B)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
static MachineOperand t1CondCodeOp(bool isDead=false)
Get the operand corresponding to the conditional code result for Thumb1.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
static MachineOperand condCodeOp(unsigned CCReg=0)
Get the operand corresponding to the conditional code result.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void emitARMRegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, Register DestReg, Register BaseReg, int NumBytes, ARMCC::CondCodes Pred, Register PredReg, const ARMBaseInstrInfo &TII, unsigned MIFlags=0)
emitARMRegPlusImmediate / emitT2RegPlusImmediate - Emits a series of instructions to materializea des...
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
void emitT2RegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, Register DestReg, Register BaseReg, int NumBytes, ARMCC::CondCodes Pred, Register PredReg, const ARMBaseInstrInfo &TII, unsigned MIFlags=0)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82