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