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"
114#include "ARMMachineFunctionInfo.h"
115#include "ARMSubtarget.h"
116#include "MCTargetDesc/ARMAddressingModes.h"
117#include "MCTargetDesc/ARMBaseInfo.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"
123#include "llvm/CodeGen/CFIInstBuilder.h"
124#include "llvm/CodeGen/MachineBasicBlock.h"
125#include "llvm/CodeGen/MachineConstantPool.h"
126#include "llvm/CodeGen/MachineFrameInfo.h"
127#include "llvm/CodeGen/MachineFunction.h"
128#include "llvm/CodeGen/MachineInstr.h"
129#include "llvm/CodeGen/MachineInstrBuilder.h"
130#include "llvm/CodeGen/MachineJumpTableInfo.h"
131#include "llvm/CodeGen/MachineModuleInfo.h"
132#include "llvm/CodeGen/MachineOperand.h"
133#include "llvm/CodeGen/MachineRegisterInfo.h"
134#include "llvm/CodeGen/RegisterScavenging.h"
135#include "llvm/CodeGen/TargetInstrInfo.h"
136#include "llvm/CodeGen/TargetRegisterInfo.h"
137#include "llvm/CodeGen/TargetSubtargetInfo.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"
146#include "llvm/Support/CommandLine.h"
147#include "llvm/Support/Compiler.h"
148#include "llvm/Support/Debug.h"
149#include "llvm/Support/ErrorHandling.h"
150#include "llvm/Support/raw_ostream.h"
151#include "llvm/Target/TargetMachine.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(Val: true),
166 cl::desc("Align ARM NEON spills in prolog and epilog"));
167
168static MachineBasicBlock::iterator
169skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
170 unsigned NumAlignedDPRCS2Regs);
171
172enum class SpillArea {
173 GPRCS1,
174 GPRCS2,
175 FPStatus,
176 DPRCS1,
177 DPRCS2,
178 GPRCS3,
179 FPCXT,
180};
181
182/// Get the spill area that Reg should be saved into in the prologue.
183SpillArea getSpillArea(Register Reg,
184 ARMSubtarget::PushPopSplitVariation Variation,
185 unsigned NumAlignedDPRCS2Regs,
186 const ARMBaseRegisterInfo *RegInfo) {
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, TRI: 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 ||
245 Variation == ARMSubtarget::SplitR11AAPCSSignRA)
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
309ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
310 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
311 STI(sti) {}
312
313bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
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.
322bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
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.
335bool ARMFrameLowering::hasFPImpl(const MachineFunction &MF) const {
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.
344 if (MF.disableFramePointerElim())
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.
354bool ARMFrameLowering::isFPReserved(const MachineFunction &MF) const {
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.
363bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
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
381ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
382 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
383}
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).
390static int getArgumentStackToRestore(MachineFunction &MF,
391 MachineBasicBlock &MBB) {
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 }
400 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
401
402 int ArgumentPopSize = 0;
403 if (IsTailCallReturn) {
404 MachineOperand &StackAdjust = MBBI->getOperand(i: 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.
423static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI,
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();
430 MachineInstrBuilder MIB;
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(reason: "No SEH Opcode for instruction " + TII.getName(Opcode: 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, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
448 .addImm(/*Wide=*/Val: 1)
449 .setMIFlags(Flags);
450 break;
451
452 case ARM::t2MOVi16: { // mov(w) r4, #xx
453 bool Wide = MBBI->getOperand(i: 1).getImm() >= 256;
454 if (!Wide) {
455 MachineInstrBuilder NewInstr =
456 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8)).setMIFlags(MBBI->getFlags());
457 NewInstr.add(MO: MBBI->getOperand(i: 0));
458 NewInstr.add(MO: t1CondCodeOp(/*isDead=*/true));
459 for (MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MBBI->operands()))
460 NewInstr.add(MO);
461 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(I: MBBI, MI: NewInstr);
462 MBB->erase(I: MBBI);
463 MBBI = NewMBBI;
464 }
465 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop)).addImm(Val: Wide).setMIFlags(Flags);
466 break;
467 }
468
469 case ARM::tBLXr: // blx r12 (__chkstk)
470 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
471 .addImm(/*Wide=*/Val: 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, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
484 .addImm(/*Wide=*/Val: 1)
485 .setMIFlags(Flags);
486 MBB->insertAfter(I: MBBI, MI: MIB);
487 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
488 .addImm(/*Wide=*/Val: 1)
489 .setMIFlags(Flags);
490 break;
491
492 case ARM::t2STR_PRE:
493 if (MBBI->getOperand(i: 0).getReg() == ARM::SP &&
494 MBBI->getOperand(i: 2).getReg() == ARM::SP &&
495 MBBI->getOperand(i: 3).getImm() == -4) {
496 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 1).getReg());
497 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveRegs))
498 .addImm(Val: 1ULL << Reg)
499 .addImm(/*Wide=*/Val: 1)
500 .setMIFlags(Flags);
501 } else {
502 report_fatal_error(reason: "No matching SEH Opcode for t2STR_PRE");
503 }
504 break;
505
506 case ARM::t2LDR_POST:
507 if (MBBI->getOperand(i: 1).getReg() == ARM::SP &&
508 MBBI->getOperand(i: 2).getReg() == ARM::SP &&
509 MBBI->getOperand(i: 3).getImm() == 4) {
510 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 0).getReg());
511 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveRegs))
512 .addImm(Val: 1ULL << Reg)
513 .addImm(/*Wide=*/Val: 1)
514 .setMIFlags(Flags);
515 } else {
516 report_fatal_error(reason: "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(i: 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:
551 llvm_unreachable("");
552 }
553 MachineInstrBuilder NewInstr =
554 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: NewOpc)).setMIFlags(MBBI->getFlags());
555 for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
556 NewInstr.add(MO: MBBI->getOperand(i));
557 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(I: MBBI, MI: NewInstr);
558 MBB->erase(I: MBBI);
559 MBBI = NewMBBI;
560 }
561 unsigned SEHOpc =
562 (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs;
563 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: SEHOpc))
564 .addImm(Val: Mask)
565 .addImm(Val: 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(RangeOrContainer: MBBI->operands(), N: 4)) {
573 unsigned Reg = RegInfo->getSEHRegNum(i: MO.getReg());
574 if (First == -1)
575 First = Reg;
576 Last = Reg;
577 }
578 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveFRegs))
579 .addImm(Val: First)
580 .addImm(Val: Last)
581 .setMIFlags(Flags);
582 break;
583 }
584 case ARM::tSUBspi:
585 case ARM::tADDspi:
586 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
587 .addImm(Val: MBBI->getOperand(i: 2).getImm() * 4)
588 .addImm(/*Wide=*/Val: 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, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
596 .addImm(Val: MBBI->getOperand(i: 2).getImm())
597 .addImm(/*Wide=*/Val: 1)
598 .setMIFlags(Flags);
599 break;
600
601 case ARM::tMOVr:
602 if (MBBI->getOperand(i: 1).getReg() == ARM::SP &&
603 (Flags & MachineInstr::FrameSetup)) {
604 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 0).getReg());
605 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveSP))
606 .addImm(Val: Reg)
607 .setMIFlags(Flags);
608 } else if (MBBI->getOperand(i: 0).getReg() == ARM::SP &&
609 (Flags & MachineInstr::FrameDestroy)) {
610 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 1).getReg());
611 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveSP))
612 .addImm(Val: Reg)
613 .setMIFlags(Flags);
614 } else {
615 report_fatal_error(reason: "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, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop_Ret))
626 .addImm(/*Wide=*/Val: 0)
627 .setMIFlags(Flags);
628 break;
629
630 case ARM::TCRETURNdi:
631 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop_Ret))
632 .addImm(/*Wide=*/Val: 1)
633 .setMIFlags(Flags);
634 break;
635 }
636 return MBB->insertAfter(I: MBBI, MI: MIB);
637}
638
639static MachineBasicBlock::iterator
640initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI) {
641 if (MBBI == MBB.begin())
642 return MachineBasicBlock::iterator();
643 return std::prev(x: MBBI);
644}
645
646static void insertSEHRange(MachineBasicBlock &MBB,
647 MachineBasicBlock::iterator Start,
648 const MachineBasicBlock::iterator &End,
649 const ARMBaseInstrInfo &TII, unsigned MIFlags) {
650 if (Start.isValid())
651 Start = std::next(x: Start);
652 else
653 Start = MBB.begin();
654
655 for (auto MI = Start; MI != End;) {
656 auto Next = std::next(x: 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(MI: *Next)) {
660 MI = std::next(x: Next);
661 while (MI != End && isSEHInstruction(MI: *MI))
662 ++MI;
663 continue;
664 }
665 insertSEH(MBBI: MI, TII, Flags: MIFlags);
666 MI = Next;
667 }
668}
669
670static void emitRegPlusImmediate(
671 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
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, BaseReg: SrcReg, NumBytes,
677 Pred, PredReg, TII, MIFlags);
678 else
679 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, BaseReg: SrcReg, NumBytes,
680 Pred, PredReg, TII, MIFlags);
681}
682
683static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
684 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
685 const ARMBaseInstrInfo &TII, int NumBytes,
686 unsigned MIFlags = MachineInstr::NoFlags,
687 ARMCC::CondCodes Pred = ARMCC::AL,
688 unsigned PredReg = 0) {
689 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, DestReg: ARM::SP, SrcReg: ARM::SP, NumBytes,
690 MIFlags, Pred, PredReg);
691}
692
693static int sizeOfSPAdjustment(const MachineInstr &MI) {
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
718static bool WindowsRequiresStackProbe(const MachineFunction &MF,
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(Kind: "stack-probe-size", Default: StackProbeSize);
726 return (StackSizeInBytes >= StackProbeSize) &&
727 !F.hasFnAttribute(Kind: "no-stack-arg-probe");
728}
729
730namespace {
731
732struct StackAdjustingInsts {
733 struct InstInfo {
734 MachineBasicBlock::iterator I;
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
747 SmallVector<InstInfo, 4> Insts;
748
749 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
750 bool BeforeFPSet = false) {
751 InstInfo Info = {.I: I, .SPAdjust: SPAdjust, .BeforeFPSet: BeforeFPSet};
752 Insts.push_back(Elt: Info);
753 }
754
755 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
756 auto Info =
757 llvm::find_if(Range&: Insts, P: [&](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(x: Info.I));
771 CFIBuilder.buildDefCFAOffset(Offset: 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.
793static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
794 const TargetInstrInfo &TII,
795 MachineBasicBlock &MBB,
796 MachineBasicBlock::iterator MBBI,
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(A: 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(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::BFC), DestReg: Reg)
817 .addReg(RegNo: Reg, Flags: RegState::Kill)
818 .addImm(Val: ~AlignMask)
819 .add(MOs: predOps(Pred: ARMCC::AL));
820 } else if (AlignMask <= 255) {
821 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::BICri), DestReg: Reg)
822 .addReg(RegNo: Reg, Flags: RegState::Kill)
823 .addImm(Val: AlignMask)
824 .add(MOs: predOps(Pred: ARMCC::AL))
825 .add(MO: 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(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVsi), DestReg: Reg)
832 .addReg(RegNo: Reg, Flags: RegState::Kill)
833 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsr, Imm: NrBitsToZero))
834 .add(MOs: predOps(Pred: ARMCC::AL))
835 .add(MO: condCodeOp());
836 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVsi), DestReg: Reg)
837 .addReg(RegNo: Reg, Flags: RegState::Kill)
838 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: NrBitsToZero))
839 .add(MOs: predOps(Pred: ARMCC::AL))
840 .add(MO: 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(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2BFC), DestReg: Reg)
847 .addReg(RegNo: Reg, Flags: RegState::Kill)
848 .addImm(Val: ~AlignMask)
849 .add(MOs: predOps(Pred: ARMCC::AL));
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) {
861 ARMSubtarget::PushPopSplitVariation PushPopSplit =
862 STI.getPushPopSplitVariation(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
882void ARMFrameLowering::emitPrologue(MachineFunction &MF,
883 MachineBasicBlock &MBB) const {
884 MachineBasicBlock::iterator MBBI = MBB.begin();
885 MachineFrameInfo &MFI = MF.getFrameInfo();
886 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
887 const TargetMachine &TM = MF.getTarget();
888 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
889 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
890 assert(!AFI->isThumb1OnlyFunction() &&
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();
899 ARMSubtarget::PushPopSplitVariation PushPopSplit =
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.
919 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
920 return;
921
922 StackAdjustingInsts DefCFAOffsetCandidates;
923 bool HasFP = hasFP(MF);
924
925 if (!AFI->hasStackFrame() &&
926 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, StackSizeInBytes: NumBytes))) {
927 if (NumBytes != 0) {
928 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -NumBytes,
929 MIFlags: MachineInstr::FrameSetup);
930 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: NumBytes, BeforeFPSet: true);
931 }
932 if (!NeedsWinCFI)
933 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
934 if (NeedsWinCFI && MBBI != MBB.begin()) {
935 insertSEHRange(MBB, Start: {}, End: MBBI, TII, MIFlags: MachineInstr::FrameSetup);
936 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_PrologEnd))
937 .setMIFlag(MachineInstr::FrameSetup);
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, Variation: PushPopSplit,
951 NumAlignedDPRCS2Regs: 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;
964 case SpillArea::GPRCS1:
965 GPRCS1Size += 4;
966 break;
967 case SpillArea::GPRCS2:
968 GPRCS2Size += 4;
969 break;
970 case SpillArea::FPStatus:
971 FPStatusSize += 4;
972 break;
973 case SpillArea::DPRCS1:
974 DPRCS1Size += 8;
975 break;
976 case SpillArea::GPRCS3:
977 GPRCS3Size += 4;
978 break;
979 case SpillArea::DPRCS2:
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(I: LastPush, SPAdjust: FPCXTSaveSize, BeforeFPSet: BeforeFPPush);
996 }
997
998 // Allocate the vararg register save area.
999 if (ArgRegsSaveSize) {
1000 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -ArgRegsSaveSize,
1001 MIFlags: MachineInstr::FrameSetup);
1002 LastPush = std::prev(x: MBBI);
1003 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: ArgRegsSaveSize, BeforeFPSet: BeforeFPPush);
1004 }
1005
1006 // Move past area 1.
1007 if (GPRCS1Size > 0) {
1008 GPRCS1Push = LastPush = MBBI++;
1009 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS1Size, BeforeFPSet: 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(a: Align(8), b: 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(ObjectIdx: 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(ObjectIdx: 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) {
1046 assert(PushPopSplit != ARMSubtarget::SplitR11WindowsSEH);
1047 GPRCS2Push = LastPush = MBBI++;
1048 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS2Size, BeforeFPSet: 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(I: LastPush, SPAdjust: 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(Subtarget: STI, MF, MI: &*LastPush, NumBytes: DPRGapSize))
1072 DefCFAOffsetCandidates.addExtraBytes(I: LastPush, ExtraBytes: DPRGapSize);
1073 else {
1074 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -DPRGapSize,
1075 MIFlags: MachineInstr::FrameSetup);
1076 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: DPRGapSize, BeforeFPSet: 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(I: MBBI, SPAdjust: sizeOfSPAdjustment(MI: *MBBI),
1086 BeforeFPSet: BeforeFPPush);
1087 DPRCS1Push = LastPush = MBBI++;
1088 }
1089 }
1090
1091 // Move past the aligned DPRCS2 area.
1092 if (DPRCS2Size > 0) {
1093 MBBI = skipAlignedDPRCS2Spills(MI: MBBI, NumAlignedDPRCS2Regs: AFI->getNumAlignedDPRCS2Regs());
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(ObjectIdx: D8SpillFI);
1099 } else
1100 NumBytes = DPRCS1Offset;
1101
1102 // Move GPRCS3, if using using SplitR11WindowsSEH.
1103 if (GPRCS3Size > 0) {
1104 assert(PushPopSplit == ARMSubtarget::SplitR11WindowsSEH);
1105 GPRCS3Push = LastPush = MBBI++;
1106 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS3Size, BeforeFPSet: 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, StackSizeInBytes: NumBytes)) {
1117 uint32_t NumWords = NumBytes >> 2;
1118
1119 if (NumWords < 65536) {
1120 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi16), DestReg: ARM::R4)
1121 .addImm(Val: NumWords)
1122 .setMIFlags(MachineInstr::FrameSetup)
1123 .add(MOs: predOps(Pred: ARMCC::AL));
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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi16), DestReg: ARM::R4)
1129 .addImm(Val: NumWords & 0xffff)
1130 .setMIFlags(MachineInstr::FrameSetup)
1131 .add(MOs: predOps(Pred: ARMCC::AL));
1132 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVTi16), DestReg: ARM::R4)
1133 .addReg(RegNo: ARM::R4)
1134 .addImm(Val: NumWords >> 16)
1135 .setMIFlags(MachineInstr::FrameSetup)
1136 .add(MOs: predOps(Pred: ARMCC::AL));
1137 }
1138
1139 const ARMTargetLowering *TLI = STI.getTargetLowering();
1140 RTLIB::LibcallImpl ChkStkLibcall = TLI->getLibcallImpl(Call: RTLIB::STACK_PROBE);
1141 if (ChkStkLibcall == RTLIB::Unsupported)
1142 reportFatalUsageError(reason: "no available implementation of __chkstk");
1143 const char *ChkStk = TLI->getLibcallImplName(Call: 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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tBL))
1152 .add(MOs: predOps(Pred: ARMCC::AL))
1153 .addExternalSymbol(FnName: ChkStk)
1154 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit)
1155 .setMIFlags(MachineInstr::FrameSetup);
1156 break;
1157 case CodeModel::Large:
1158 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi32imm), DestReg: ARM::R12)
1159 .addExternalSymbol(FnName: ChkStk)
1160 .setMIFlags(MachineInstr::FrameSetup);
1161
1162 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tBLXr))
1163 .add(MOs: predOps(Pred: ARMCC::AL))
1164 .addReg(RegNo: ARM::R12, Flags: RegState::Kill)
1165 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit)
1166 .setMIFlags(MachineInstr::FrameSetup);
1167 break;
1168 }
1169
1170 MachineInstrBuilder Instr, SEH;
1171 Instr = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2SUBrr), DestReg: ARM::SP)
1172 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
1173 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
1174 .setMIFlags(MachineInstr::FrameSetup)
1175 .add(MOs: predOps(Pred: ARMCC::AL))
1176 .add(MO: condCodeOp());
1177 if (NeedsWinCFIStackAlloc) {
1178 SEH = BuildMI(MF, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
1179 .addImm(Val: NumBytes)
1180 .addImm(/*Wide=*/Val: 1)
1181 .setMIFlags(MachineInstr::FrameSetup);
1182 MBB.insertAfter(I: Instr, MI: 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(Subtarget: STI, MF, MI: &*LastPush, NumBytes))
1191 DefCFAOffsetCandidates.addExtraBytes(I: LastPush, ExtraBytes: NumBytes);
1192 else {
1193 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -NumBytes,
1194 MIFlags: MachineInstr::FrameSetup);
1195 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: 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.
1216 MachineBasicBlock::iterator AfterPush;
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(ObjectIdx: FramePtrSpillFI) +
1226 ArgRegsSaveSize + FPCXTSaveSize +
1227 sizeOfSPAdjustment(MI: *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(ObjectIdx: FramePtrSpillFI) +
1234 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1235 sizeOfSPAdjustment(MI: *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(ObjectIdx: FramePtrSpillFI) +
1242 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1243 FPStatusSize + GPRCS2Size + DPRCS1Size + DPRGapSize +
1244 sizeOfSPAdjustment(MI: *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(x: 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(isARM: !AFI->isThumbFunction(), MBB, MBBI&: AfterPush, dl, TII,
1258 DestReg: FramePtr, SrcReg: ARM::SP, NumBytes: FPOffsetAfterPush,
1259 MIFlags: MachineInstr::FrameSetup);
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(Reg: FramePtr, Offset: -MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI));
1267 else
1268 CFIBuilder.buildDefCFARegister(Reg: 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()) {
1275 MachineBasicBlock::iterator End = MBBI;
1276 if (HasFP && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1277 End = AfterPush;
1278 insertSEHRange(MBB, Start: {}, End, TII, MIFlags: MachineInstr::FrameSetup);
1279 BuildMI(BB&: MBB, I: End, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_PrologEnd))
1280 .setMIFlag(MachineInstr::FrameSetup);
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(C: CSI)) {
1289 MCRegister Reg = Entry.getReg();
1290 int FI = Entry.getFrameIdx();
1291 MachineBasicBlock::iterator CFIPos;
1292 switch (getSpillArea(Reg, Variation: PushPopSplit, NumAlignedDPRCS2Regs: AFI->getNumAlignedDPRCS2Regs(),
1293 RegInfo)) {
1294 case SpillArea::GPRCS1:
1295 CFIPos = std::next(x: GPRCS1Push);
1296 break;
1297 case SpillArea::GPRCS2:
1298 CFIPos = std::next(x: GPRCS2Push);
1299 break;
1300 case SpillArea::DPRCS1:
1301 CFIPos = std::next(x: DPRCS1Push);
1302 break;
1303 case SpillArea::GPRCS3:
1304 CFIPos = std::next(x: GPRCS3Push);
1305 break;
1306 case SpillArea::FPStatus:
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()) {
1314 CFIInstBuilder(MBB, CFIPos, MachineInstr::FrameSetup)
1315 .buildOffset(Reg: Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg,
1316 Offset: MFI.getObjectOffset(ObjectIdx: 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))
1331 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
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();
1348 assert(!AFI->isThumb1OnlyFunction());
1349 if (!AFI->isThumbFunction()) {
1350 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, DL: dl, Reg: ARM::SP, Alignment: MaxAlign,
1351 MustBeSingleInstruction: 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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::R4)
1361 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
1362 .add(MOs: predOps(Pred: ARMCC::AL));
1363 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, DL: dl, Reg: ARM::R4, Alignment: MaxAlign,
1364 MustBeSingleInstruction: false);
1365 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1366 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
1367 .add(MOs: predOps(Pred: ARMCC::AL));
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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::MOVr), DestReg: RegInfo->getBaseRegister())
1381 .addReg(RegNo: ARM::SP)
1382 .add(MOs: predOps(Pred: ARMCC::AL))
1383 .add(MO: condCodeOp());
1384 else
1385 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: RegInfo->getBaseRegister())
1386 .addReg(RegNo: ARM::SP)
1387 .add(MOs: predOps(Pred: ARMCC::AL));
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
1397void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
1398 MachineBasicBlock &MBB) const {
1399 MachineFrameInfo &MFI = MF.getFrameInfo();
1400 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
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();
1407 ARMSubtarget::PushPopSplitVariation PushPopSplit =
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.
1424 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
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(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogStart))
1435 .setMIFlag(MachineInstr::FrameDestroy);
1436 RangeStart = initMBBRange(MBB, MBBI);
1437 }
1438
1439 if (NumBytes + IncomingArgStackToRestore != 0)
1440 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1441 NumBytes: NumBytes + IncomingArgStackToRestore,
1442 MIFlags: MachineInstr::FrameDestroy);
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() &&
1449 MBBI->getFlag(Flag: MachineInstr::FrameDestroy));
1450 if (!MBBI->getFlag(Flag: MachineInstr::FrameDestroy))
1451 ++MBBI;
1452 }
1453
1454 if (MF.hasWinCFI()) {
1455 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogStart))
1456 .setMIFlag(MachineInstr::FrameDestroy);
1457 RangeStart = initMBBRange(MBB, MBBI);
1458 }
1459
1460 // Move SP to start of FP callee save spill area.
1461 NumBytes -=
1462 (ReservedArgStack + AFI->getFPCXTSaveAreaSize() +
1463 AFI->getGPRCalleeSavedArea1Size() + AFI->getGPRCalleeSavedArea2Size() +
1464 AFI->getFPStatusSavesSize() + AFI->getDPRCalleeSavedGapSize() +
1465 AFI->getDPRCalleeSavedArea1Size() + AFI->getGPRCalleeSavedArea3Size());
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, DestReg: ARM::SP, BaseReg: FramePtr, NumBytes: -NumBytes,
1474 Pred: ARMCC::AL, PredReg: 0, TII,
1475 MIFlags: MachineInstr::FrameDestroy);
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, DestReg: ARM::R4, BaseReg: FramePtr, NumBytes: -NumBytes,
1487 Pred: ARMCC::AL, PredReg: 0, TII, MIFlags: MachineInstr::FrameDestroy);
1488 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1489 .addReg(RegNo: ARM::R4)
1490 .add(MOs: predOps(Pred: ARMCC::AL))
1491 .setMIFlag(MachineInstr::FrameDestroy);
1492 }
1493 } else {
1494 // Thumb2 or ARM.
1495 if (isARM)
1496 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::MOVr), DestReg: ARM::SP)
1497 .addReg(RegNo: FramePtr)
1498 .add(MOs: predOps(Pred: ARMCC::AL))
1499 .add(MO: condCodeOp())
1500 .setMIFlag(MachineInstr::FrameDestroy);
1501 else
1502 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1503 .addReg(RegNo: FramePtr)
1504 .add(MOs: predOps(Pred: ARMCC::AL))
1505 .setMIFlag(MachineInstr::FrameDestroy);
1506 }
1507 } else if (NumBytes &&
1508 !tryFoldSPUpdateIntoPushPop(Subtarget: STI, MF, MI: &*MBBI, NumBytes))
1509 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
1510 MIFlags: MachineInstr::FrameDestroy);
1511
1512 // Increment past our save areas.
1513 if (AFI->getGPRCalleeSavedArea3Size()) {
1514 assert(PushPopSplit == ARMSubtarget::SplitR11WindowsSEH);
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, NumBytes: AFI->getDPRCalleeSavedGapSize(),
1530 MIFlags: MachineInstr::FrameDestroy);
1531 }
1532
1533 if (AFI->getGPRCalleeSavedArea2Size()) {
1534 assert(PushPopSplit != ARMSubtarget::SplitR11WindowsSEH);
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 NumBytes: ReservedArgStack + IncomingArgStackToRestore,
1545 MIFlags: MachineInstr::FrameDestroy);
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(Opcode: ARM::t2BXAUT_RET));
1560 else
1561 BuildMI(BB&: MBB, I: MBBI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::t2AUT));
1562 }
1563 }
1564
1565 if (MF.hasWinCFI()) {
1566 insertSEHRange(MBB, Start: RangeStart, End: MBB.end(), TII, MIFlags: MachineInstr::FrameDestroy);
1567 BuildMI(BB&: MBB, I: MBB.end(), MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogEnd))
1568 .setMIFlag(MachineInstr::FrameDestroy);
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.
1576StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1577 int FI,
1578 Register &FrameReg) const {
1579 return StackOffset::getFixed(Fixed: ResolveFrameIndexReference(MF, FI, FrameReg, SPAdj: 0));
1580}
1581
1582StackOffset
1583ARMFrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
1584 int FI) const {
1585 const MachineFrameInfo &MFI = MF.getFrameInfo();
1586 int Offset = MFI.getObjectOffset(ObjectIdx: FI) + MFI.getStackSize();
1587 return StackOffset::getFixed(Fixed: Offset);
1588}
1589
1590int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
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(ObjectIdx: FI) + MFI.getStackSize();
1598 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
1599 bool isFixed = MFI.isFixedObjectIndex(ObjectIdx: 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,
1673 MachineBasicBlock::iterator MI,
1674 ArrayRef<CalleeSavedInfo> CSI,
1675 unsigned StmOpc, unsigned StrOpc,
1676 bool NoGap,
1677 function_ref<bool(unsigned)> Func) const {
1678 MachineFunction &MF = *MBB.getParent();
1679 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1680 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1681
1682 DebugLoc DL;
1683
1684 using RegAndKill = std::pair<unsigned, bool>;
1685
1686 SmallVector<RegAndKill, 4> Regs;
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(PhysReg: Reg))
1698 MBB.addLiveIn(PhysReg: 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(Elt: std::make_pair(x&: Reg, /*isKill=*/y: !isLiveIn));
1711 }
1712
1713 if (Regs.empty())
1714 continue;
1715
1716 llvm::sort(C&: Regs, Comp: [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1717 return TRI.getEncodingValue(Reg: LHS.first) < TRI.getEncodingValue(Reg: RHS.first);
1718 });
1719
1720 if (Regs.size() > 1 || StrOpc== 0) {
1721 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: StmOpc), DestReg: ARM::SP)
1722 .addReg(RegNo: ARM::SP)
1723 .setMIFlags(MachineInstr::FrameSetup)
1724 .add(MOs: predOps(Pred: ARMCC::AL));
1725 for (const auto &[Reg, Kill] : Regs)
1726 MIB.addReg(RegNo: Reg, Flags: getKillRegState(B: Kill));
1727 } else if (Regs.size() == 1) {
1728 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: StrOpc), DestReg: ARM::SP)
1729 .addReg(RegNo: Regs[0].first, Flags: getKillRegState(B: Regs[0].second))
1730 .addReg(RegNo: ARM::SP)
1731 .setMIFlags(MachineInstr::FrameSetup)
1732 .addImm(Val: -4)
1733 .add(MOs: predOps(Pred: ARMCC::AL));
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,
1746 MachineBasicBlock::iterator MI,
1747 MutableArrayRef<CalleeSavedInfo> CSI,
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;
1761 ARMSubtarget::PushPopSplitVariation PushPopSplit =
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(Elt: Reg);
1805 }
1806
1807 if (Regs.empty())
1808 continue;
1809
1810 llvm::sort(C&: Regs, Comp: [&](unsigned LHS, unsigned RHS) {
1811 return TRI.getEncodingValue(Reg: LHS) < TRI.getEncodingValue(Reg: RHS);
1812 });
1813
1814 if (Regs.size() > 1 || LdrOpc == 0) {
1815 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: LdmOpc), DestReg: ARM::SP)
1816 .addReg(RegNo: ARM::SP)
1817 .add(MOs: predOps(Pred: ARMCC::AL))
1818 .setMIFlags(MachineInstr::FrameDestroy);
1819 for (unsigned Reg : Regs)
1820 MIB.addReg(RegNo: Reg, Flags: getDefRegState(B: true));
1821 if (DeleteRet) {
1822 if (MI != MBB.end()) {
1823 MIB.copyImplicitOps(OtherMI: *MI);
1824 MI->eraseFromParent();
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(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: LdrOpc), DestReg: Regs[0])
1835 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
1836 .addReg(RegNo: ARM::SP)
1837 .setMIFlags(MachineInstr::FrameDestroy);
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(RegNo: 0);
1842 MIB.addImm(Val: ARM_AM::getAM2Opc(Opc: ARM_AM::add, Imm12: 4, SO: ARM_AM::no_shift));
1843 } else
1844 MIB.addImm(Val: 4);
1845 MIB.add(MOs: predOps(Pred: 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,
1857 MachineBasicBlock::iterator MI,
1858 ArrayRef<CalleeSavedInfo> CSI,
1859 unsigned PushOpc) const {
1860 MachineFunction &MF = *MBB.getParent();
1861 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1862
1863 SmallVector<MCRegister> Regs;
1864 auto RegPresent = [&CSI](MCRegister Reg) {
1865 return llvm::any_of(Range&: CSI, P: [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(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: ARM::VMRS), DestReg: ARM::R4)
1874 .add(MOs: predOps(Pred: ARMCC::AL))
1875 .setMIFlags(MachineInstr::FrameSetup);
1876
1877 Regs.push_back(Elt: 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(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: ARM::VMRS_FPEXC), DestReg: ARM::R5)
1884 .add(MOs: predOps(Pred: ARMCC::AL))
1885 .setMIFlags(MachineInstr::FrameSetup);
1886
1887 Regs.push_back(Elt: 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(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: PushOpc), DestReg: ARM::SP)
1897 .addReg(RegNo: ARM::SP)
1898 .add(MOs: predOps(Pred: ARMCC::AL))
1899 .setMIFlags(MachineInstr::FrameSetup);
1900
1901 for (Register Reg : Regs) {
1902 MIB.addReg(RegNo: Reg);
1903 }
1904}
1905
1906void ARMFrameLowering::emitFPStatusRestores(
1907 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
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(Range&: CSI, P: [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(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: LdmOpc), DestReg: ARM::SP)
1925 .addReg(RegNo: ARM::SP)
1926 .add(MOs: predOps(Pred: ARMCC::AL))
1927 .setMIFlags(MachineInstr::FrameDestroy);
1928
1929 // If FPSCR was saved, it will be popped into R4.
1930 if (RegPresent(ARM::FPSCR)) {
1931 MIB.addReg(RegNo: ARM::R4, Flags: RegState::Define);
1932 }
1933
1934 // If FPEXC was saved, it will be popped into R5.
1935 if (RegPresent(ARM::FPEXC)) {
1936 MIB.addReg(RegNo: ARM::R5, Flags: RegState::Define);
1937 }
1938
1939 // Move the FPSCR value back into the register with the VMSR instruction.
1940 if (RegPresent(ARM::FPSCR)) {
1941 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VMSR))
1942 .addReg(RegNo: ARM::R4)
1943 .add(MOs: predOps(Pred: ARMCC::AL))
1944 .setMIFlags(MachineInstr::FrameDestroy);
1945 }
1946
1947 // Move the FPEXC value back into the register with the VMSR_FPEXC
1948 // instruction.
1949 if (RegPresent(ARM::FPEXC)) {
1950 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VMSR_FPEXC))
1951 .addReg(RegNo: ARM::R5)
1952 .add(MOs: predOps(Pred: ARMCC::AL))
1953 .setMIFlags(MachineInstr::FrameDestroy);
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.
1960static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1961 MachineBasicBlock::iterator MI,
1962 unsigned NumAlignedDPRCS2Regs,
1963 ArrayRef<CalleeSavedInfo> CSI,
1964 const TargetRegisterInfo *TRI) {
1965 MachineFunction &MF = *MBB.getParent();
1966 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1967 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1968 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
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(ObjectIdx: FI, Alignment: 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(ObjectIdx: FI, Alignment: 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(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::R4)
2008 .addReg(RegNo: ARM::SP)
2009 .addImm(Val: 8 * NumAlignedDPRCS2Regs)
2010 .add(MOs: predOps(Pred: ARMCC::AL))
2011 .add(MO: 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, MBBI: MI, DL, Reg: ARM::R4, Alignment: MaxAlign, MustBeSingleInstruction: 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(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::SP)
2027 .addReg(RegNo: ARM::R4)
2028 .add(MOs: predOps(Pred: ARMCC::AL));
2029 if (!isThumb)
2030 MIB.add(MO: 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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2041 MBB.addLiveIn(PhysReg: SupReg);
2042 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1d64Qwb_fixed), DestReg: ARM::R4)
2043 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
2044 .addImm(Val: 16)
2045 .addReg(RegNo: NextReg)
2046 .addReg(RegNo: SupReg, Flags: RegState::ImplicitKill)
2047 .add(MOs: predOps(Pred: ARMCC::AL));
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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2060 MBB.addLiveIn(PhysReg: SupReg);
2061 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1d64Q))
2062 .addReg(RegNo: ARM::R4)
2063 .addImm(Val: 16)
2064 .addReg(RegNo: NextReg)
2065 .addReg(RegNo: SupReg, Flags: RegState::ImplicitKill)
2066 .add(MOs: predOps(Pred: ARMCC::AL));
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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QPRRegClass);
2075 MBB.addLiveIn(PhysReg: SupReg);
2076 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1q64))
2077 .addReg(RegNo: ARM::R4)
2078 .addImm(Val: 16)
2079 .addReg(RegNo: SupReg)
2080 .add(MOs: predOps(Pred: ARMCC::AL));
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(PhysReg: NextReg);
2088 // vstr.64 uses addrmode5 which has an offset scale of 4.
2089 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VSTRD))
2090 .addReg(RegNo: NextReg)
2091 .addReg(RegNo: ARM::R4)
2092 .addImm(Val: (NextReg - R4BaseReg) * 2)
2093 .add(MOs: predOps(Pred: ARMCC::AL));
2094 }
2095
2096 // The last spill instruction inserted should kill the scratch register r4.
2097 std::prev(x: MI)->addRegisterKilled(IncomingReg: ARM::R4, RegInfo: TRI);
2098}
2099
2100/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
2101/// iterator to the following instruction.
2102static MachineBasicBlock::iterator
2103skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
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.
2133static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
2134 MachineBasicBlock::iterator MI,
2135 unsigned NumAlignedDPRCS2Regs,
2136 ArrayRef<CalleeSavedInfo> CSI,
2137 const TargetRegisterInfo *TRI) {
2138 MachineFunction &MF = *MBB.getParent();
2139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2140 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
2141 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
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(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::R4)
2161 .addFrameIndex(Idx: D8SpillFI)
2162 .addImm(Val: 0)
2163 .add(MOs: predOps(Pred: ARMCC::AL))
2164 .add(MO: 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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2173 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1d64Qwb_fixed), DestReg: NextReg)
2174 .addReg(RegNo: ARM::R4, Flags: RegState::Define)
2175 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
2176 .addImm(Val: 16)
2177 .addReg(RegNo: SupReg, Flags: RegState::ImplicitDefine)
2178 .add(MOs: predOps(Pred: ARMCC::AL));
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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2191 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1d64Q), DestReg: NextReg)
2192 .addReg(RegNo: ARM::R4)
2193 .addImm(Val: 16)
2194 .addReg(RegNo: SupReg, Flags: RegState::ImplicitDefine)
2195 .add(MOs: predOps(Pred: ARMCC::AL));
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(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QPRRegClass);
2204 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1q64), DestReg: SupReg)
2205 .addReg(RegNo: ARM::R4)
2206 .addImm(Val: 16)
2207 .add(MOs: predOps(Pred: ARMCC::AL));
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(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLDRD), DestReg: NextReg)
2215 .addReg(RegNo: ARM::R4)
2216 .addImm(Val: 2 * (NextReg - R4BaseReg))
2217 .add(MOs: predOps(Pred: ARMCC::AL));
2218
2219 // Last store kills r4.
2220 std::prev(x: MI)->addRegisterKilled(IncomingReg: ARM::R4, RegInfo: TRI);
2221}
2222
2223bool ARMFrameLowering::spillCalleeSavedRegisters(
2224 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2225 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2226 if (CSI.empty())
2227 return false;
2228
2229 MachineFunction &MF = *MBB.getParent();
2230 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2231 ARMSubtarget::PushPopSplitVariation PushPopSplit =
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(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::t2PAC))
2243 .setMIFlags(MachineInstr::FrameSetup);
2244 }
2245 // Save the non-secure floating point context.
2246 if (llvm::any_of(Range&: CSI, P: [](const CalleeSavedInfo &C) {
2247 return C.getReg() == ARM::FPCXTNS;
2248 })) {
2249 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VSTR_FPCXTNS_pre),
2250 DestReg: ARM::SP)
2251 .addReg(RegNo: ARM::SP)
2252 .addImm(Val: -4)
2253 .add(MOs: predOps(Pred: ARMCC::AL));
2254 }
2255
2256 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2257 RegInfo](unsigned Reg, SpillArea TestArea) {
2258 return getSpillArea(Reg, Variation: 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, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: IsGPRCS1);
2275 emitPushInst(MBB, MI, CSI, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: IsGPRCS2);
2276 emitFPStatusSaves(MBB, MI, CSI, PushOpc);
2277 emitPushInst(MBB, MI, CSI, StmOpc: FltOpc, StrOpc: 0, NoGap: true, Func: IsDPRCS1);
2278 emitPushInst(MBB, MI, CSI, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: 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
2289bool ARMFrameLowering::restoreCalleeSavedRegisters(
2290 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2291 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2292 if (CSI.empty())
2293 return false;
2294
2295 MachineFunction &MF = *MBB.getParent();
2296 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2297 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2298
2299 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
2300 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
2301 ARMSubtarget::PushPopSplitVariation PushPopSplit =
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, Variation: 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, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS3);
2333 emitPopInst(MBB, MI, CSI, LdmOpc: FltOpc, LdrOpc: 0, isVarArg, NoGap: true, Func: IsDPRCS1);
2334 emitFPStatusRestores(MBB, MI, CSI, LdmOpc: PopOpc);
2335 emitPopInst(MBB, MI, CSI, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS2);
2336 emitPopInst(MBB, MI, CSI, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS1);
2337
2338 return true;
2339}
2340
2341// FIXME: Make generic?
2342static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
2343 const ARMBaseInstrInfo &TII,
2344 const ARMSubtarget &STI,
2345 const ARMBaseRegisterInfo *RegInfo,
2346 BitVector &SavedRegs,
2347 bool BigFrameOffsets) {
2348 unsigned FnSize = 0;
2349
2350 bool KCFI = MF.getFunction().getParent()->getModuleFlag(Key: "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(Idx: 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 =
2507 dyn_cast_if_present<const PseudoSourceValue *>(
2508 Val: 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(Inst: 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(Opcode: 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?
2567static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
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(a: Limit, b: (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, OpNum: i);
2597 if (RegClass && !RegClass->contains(Reg: ARM::SP))
2598 HasNonSPFrameIndex = true;
2599
2600 // Otherwise check the addressing mode.
2601 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
2602 case ARMII::AddrMode_i12:
2603 case ARMII::AddrMode2:
2604 // Default 12 bit limit.
2605 break;
2606 case ARMII::AddrMode3:
2607 case ARMII::AddrModeT2_i8neg:
2608 Limit = std::min(a: Limit, b: (1U << 8) - 1);
2609 break;
2610 case ARMII::AddrMode5FP16:
2611 Limit = std::min(a: Limit, b: ((1U << 8) - 1) * 2);
2612 break;
2613 case ARMII::AddrMode5:
2614 case ARMII::AddrModeT2_i8s4:
2615 case ARMII::AddrModeT2_ldrex:
2616 Limit = std::min(a: Limit, b: ((1U << 8) - 1) * 4);
2617 break;
2618 case ARMII::AddrModeT2_i12:
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(a: Limit, b: (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;
2629 case ARMII::AddrModeT2_i7:
2630 Limit = std::min(a: Limit, b: ((1U << 7) - 1) * 1);
2631 break;
2632 case ARMII::AddrModeT2_i7s2:
2633 Limit = std::min(a: Limit, b: ((1U << 7) - 1) * 2);
2634 break;
2635 case ARMII::AddrModeT2_i7s4:
2636 Limit = std::min(a: Limit, b: ((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
2653checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
2654 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
2655 if (!SpillAlignedNEONRegs)
2656 return;
2657
2658 // Naked functions don't spill callee-saved registers.
2659 if (MF.getFunction().hasFnAttribute(Kind: 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.
2667 if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
2668 return;
2669
2670 // Aligned spills require stack realignment.
2671 if (!static_cast<const ARMBaseRegisterInfo *>(
2672 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
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(Idx: 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
2696bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
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() &&
2700 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
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.
2706 if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(
2707 SpillsLR: true /* SpillsLR */))
2708 return false;
2709
2710 return true;
2711}
2712
2713bool ARMFrameLowering::requiresAAPCSFrameRecord(
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.
2722static bool canSpillOnFrameIndexAccess(const MachineFunction &MF,
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.isDebugInstr())
2732 continue;
2733 if (MI.getOpcode() == ARM::tSTRspi || MI.getOpcode() == ARM::tSTRi ||
2734 STI.genExecuteOnly())
2735 for (const auto &Op : MI.operands())
2736 if (Op.isFI()) {
2737 Register Reg;
2738 TFI.getFrameIndexReference(MF, FI: Op.getIndex(), FrameReg&: Reg);
2739 if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP)
2740 return true;
2741 }
2742 }
2743 return false;
2744}
2745
2746void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
2747 BitVector &SavedRegs,
2748 RegScavenger *RS) const {
2749 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2750 // This tells PEI to spill the FP as if it is any other callee-save register
2751 // to take advantage the eliminateFrameIndex machinery. This also ensures it
2752 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
2753 // to combine multiple loads / stores.
2754 bool CanEliminateFrame = !(requiresAAPCSFrameRecord(MF) && hasFP(MF)) &&
2755 !MF.disableFramePointerElim();
2756 bool CS1Spilled = false;
2757 bool LRSpilled = false;
2758 unsigned NumGPRSpills = 0;
2759 unsigned NumFPRSpills = 0;
2760 SmallVector<unsigned, 4> UnspilledCS1GPRs;
2761 SmallVector<unsigned, 4> UnspilledCS2GPRs;
2762 const Function &F = MF.getFunction();
2763 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
2764 MF.getSubtarget().getRegisterInfo());
2765 const ARMBaseInstrInfo &TII =
2766 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2767 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2768 MachineFrameInfo &MFI = MF.getFrameInfo();
2769 MachineRegisterInfo &MRI = MF.getRegInfo();
2770 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2771 (void)TRI; // Silence unused warning in non-assert builds.
2772 Register FramePtr = STI.getFramePointerReg();
2773 ARMSubtarget::PushPopSplitVariation PushPopSplit =
2774 STI.getPushPopSplitVariation(MF);
2775
2776 // For a floating point interrupt, save these registers always, since LLVM
2777 // currently doesn't model reads/writes to these registers.
2778 if (F.hasFnAttribute(Kind: "interrupt") && F.hasFnAttribute(Kind: "save-fp")) {
2779 SavedRegs.set(ARM::FPSCR);
2780 SavedRegs.set(ARM::R4);
2781
2782 // This register will only be present on non-MClass registers.
2783 if (STI.isMClass()) {
2784 SavedRegs.reset(Idx: ARM::FPEXC);
2785 } else {
2786 SavedRegs.set(ARM::FPEXC);
2787 SavedRegs.set(ARM::R5);
2788 }
2789 }
2790
2791 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
2792 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
2793 // since it's not always possible to restore sp from fp in a single
2794 // instruction.
2795 // FIXME: It will be better just to find spare register here.
2796 if (AFI->isThumb2Function() &&
2797 (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
2798 SavedRegs.set(ARM::R4);
2799
2800 // If a stack probe will be emitted, spill R4 and LR, since they are
2801 // clobbered by the stack probe call.
2802 // This estimate should be a safe, conservative estimate. The actual
2803 // stack probe is enabled based on the size of the local objects;
2804 // this estimate also includes the varargs store size.
2805 if (STI.isTargetWindows() &&
2806 WindowsRequiresStackProbe(MF, StackSizeInBytes: MFI.estimateStackSize(MF))) {
2807 SavedRegs.set(ARM::R4);
2808 SavedRegs.set(ARM::LR);
2809 }
2810
2811 if (AFI->isThumb1OnlyFunction()) {
2812 // Spill LR if Thumb1 function uses variable length argument lists.
2813 if (AFI->getArgRegsSaveSize() > 0)
2814 SavedRegs.set(ARM::LR);
2815
2816 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
2817 // requires stack alignment. We don't know for sure what the stack size
2818 // will be, but for this, an estimate is good enough. If there anything
2819 // changes it, it'll be a spill, which implies we've used all the registers
2820 // and so R4 is already used, so not marking it here will be OK.
2821 // FIXME: It will be better just to find spare register here.
2822 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
2823 MFI.estimateStackSize(MF) > 508)
2824 SavedRegs.set(ARM::R4);
2825 }
2826
2827 // See if we can spill vector registers to aligned stack.
2828 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
2829
2830 // Spill the BasePtr if it's used.
2831 if (RegInfo->hasBasePointer(MF))
2832 SavedRegs.set(RegInfo->getBaseRegister());
2833
2834 // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
2835 if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
2836 CanEliminateFrame = false;
2837
2838 // When return address signing is enabled R12 is treated as callee-saved.
2839 if (AFI->shouldSignReturnAddress())
2840 CanEliminateFrame = false;
2841
2842 // Don't spill FP if the frame can be eliminated. This is determined
2843 // by scanning the callee-save registers to see if any is modified.
2844 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MF: &MF);
2845 for (unsigned i = 0; CSRegs[i]; ++i) {
2846 unsigned Reg = CSRegs[i];
2847 bool Spilled = false;
2848 if (SavedRegs.test(Idx: Reg)) {
2849 Spilled = true;
2850 CanEliminateFrame = false;
2851 }
2852
2853 if (!ARM::GPRRegClass.contains(Reg)) {
2854 if (Spilled) {
2855 if (ARM::SPRRegClass.contains(Reg))
2856 NumFPRSpills++;
2857 else if (ARM::DPRRegClass.contains(Reg))
2858 NumFPRSpills += 2;
2859 else if (ARM::QPRRegClass.contains(Reg))
2860 NumFPRSpills += 4;
2861 }
2862 continue;
2863 }
2864
2865 if (Spilled) {
2866 NumGPRSpills++;
2867
2868 if (PushPopSplit != ARMSubtarget::SplitR7) {
2869 if (Reg == ARM::LR)
2870 LRSpilled = true;
2871 CS1Spilled = true;
2872 continue;
2873 }
2874
2875 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
2876 switch (Reg) {
2877 case ARM::LR:
2878 LRSpilled = true;
2879 [[fallthrough]];
2880 case ARM::R0: case ARM::R1:
2881 case ARM::R2: case ARM::R3:
2882 case ARM::R4: case ARM::R5:
2883 case ARM::R6: case ARM::R7:
2884 CS1Spilled = true;
2885 break;
2886 default:
2887 break;
2888 }
2889 } else {
2890 if (PushPopSplit != ARMSubtarget::SplitR7) {
2891 UnspilledCS1GPRs.push_back(Elt: Reg);
2892 continue;
2893 }
2894
2895 switch (Reg) {
2896 case ARM::R0: case ARM::R1:
2897 case ARM::R2: case ARM::R3:
2898 case ARM::R4: case ARM::R5:
2899 case ARM::R6: case ARM::R7:
2900 case ARM::LR:
2901 UnspilledCS1GPRs.push_back(Elt: Reg);
2902 break;
2903 default:
2904 UnspilledCS2GPRs.push_back(Elt: Reg);
2905 break;
2906 }
2907 }
2908 }
2909
2910 bool ForceLRSpill = false;
2911
2912 // If any of the stack slot references may be out of range of an immediate
2913 // offset, make sure a register (or a spill slot) is available for the
2914 // register scavenger. Note that if we're indexing off the frame pointer, the
2915 // effective stack size is 4 bytes larger since the FP points to the stack
2916 // slot of the previous FP. Also, if we have variable sized objects in the
2917 // function, stack slot references will often be negative, and some of
2918 // our instructions are positive-offset only, so conservatively consider
2919 // that case to want a spill slot (or register) as well. Similarly, if
2920 // the function adjusts the stack pointer during execution and the
2921 // adjustments aren't already part of our stack size estimate, our offset
2922 // calculations may be off, so be conservative.
2923 // FIXME: We could add logic to be more precise about negative offsets
2924 // and which instructions will need a scratch register for them. Is it
2925 // worth the effort and added fragility?
2926 unsigned EstimatedStackSize =
2927 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
2928
2929 // Determine biggest (positive) SP offset in MachineFrameInfo.
2930 int MaxFixedOffset = 0;
2931 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
2932 int MaxObjectOffset = MFI.getObjectOffset(ObjectIdx: I) + MFI.getObjectSize(ObjectIdx: I);
2933 MaxFixedOffset = std::max(a: MaxFixedOffset, b: MaxObjectOffset);
2934 }
2935
2936 bool HasFP = hasFP(MF);
2937 if (HasFP) {
2938 if (AFI->hasStackFrame())
2939 EstimatedStackSize += 4;
2940 } else {
2941 // If FP is not used, SP will be used to access arguments, so count the
2942 // size of arguments into the estimation.
2943 EstimatedStackSize += MaxFixedOffset;
2944 }
2945 EstimatedStackSize += 16; // For possible paddings.
2946
2947 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
2948 bool HasNonSPFrameIndex = false;
2949 if (AFI->isThumb1OnlyFunction()) {
2950 // For Thumb1, don't bother to iterate over the function. The only
2951 // instruction that requires an emergency spill slot is a store to a
2952 // frame index.
2953 //
2954 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
2955 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
2956 // a 5-bit unsigned immediate.
2957 //
2958 // We could try to check if the function actually contains a tSTRspi
2959 // that might need the spill slot, but it's not really important.
2960 // Functions with VLAs or extremely large call frames are rare, and
2961 // if a function is allocating more than 1KB of stack, an extra 4-byte
2962 // slot probably isn't relevant.
2963 //
2964 // A special case is the scenario where r11 is used as FP, where accesses
2965 // to a frame index will require its value to be moved into a low reg.
2966 // This is handled later on, once we are able to determine if we have any
2967 // fp-relative accesses.
2968 if (RegInfo->hasBasePointer(MF))
2969 EstimatedRSStackSizeLimit = (1U << 5) * 4;
2970 else
2971 EstimatedRSStackSizeLimit = (1U << 8) * 4;
2972 EstimatedRSFixedSizeLimit = (1U << 5) * 4;
2973 } else {
2974 EstimatedRSStackSizeLimit =
2975 estimateRSStackSizeLimit(MF, TFI: this, HasNonSPFrameIndex);
2976 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
2977 }
2978 // Final estimate of whether sp or bp-relative accesses might require
2979 // scavenging.
2980 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
2981
2982 // If the stack pointer moves and we don't have a base pointer, the
2983 // estimate logic doesn't work. The actual offsets might be larger when
2984 // we're constructing a call frame, or we might need to use negative
2985 // offsets from fp.
2986 bool HasMovingSP = MFI.hasVarSizedObjects() ||
2987 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
2988 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
2989
2990 // If we have a frame pointer, we assume arguments will be accessed
2991 // relative to the frame pointer. Check whether fp-relative accesses to
2992 // arguments require scavenging.
2993 //
2994 // We could do slightly better on Thumb1; in some cases, an sp-relative
2995 // offset would be legal even though an fp-relative offset is not.
2996 int MaxFPOffset = getMaxFPOffset(STI, AFI: *AFI, MF);
2997 bool HasLargeArgumentList =
2998 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
2999
3000 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
3001 HasLargeArgumentList || HasNonSPFrameIndex;
3002 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
3003 << "; EstimatedStack: " << EstimatedStackSize
3004 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
3005 << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
3006
3007 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
3008 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII, STI, RegInfo,
3009 SavedRegs, BigFrameOffsets);
3010
3011 if (FnSize >= (1 << 11)) {
3012 // Force LR to be spilled if the Thumb function size is > 2048. This
3013 // enables use of BL to implement far jump.
3014 CanEliminateFrame = false;
3015 ForceLRSpill = true;
3016 }
3017 }
3018
3019 if (BigFrameOffsets ||
3020 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
3021 AFI->setHasStackFrame(true);
3022
3023 // Save the FP if:
3024 // 1. We currently need it (HasFP), OR
3025 // 2. We might need it later due to stack realignment from aligned DPRCS2
3026 // saves (which will make hasFP() become true in emitPrologue).
3027 if (HasFP || (isFPReserved(MF) && AFI->getNumAlignedDPRCS2Regs() > 0)) {
3028 SavedRegs.set(FramePtr);
3029 // If the frame pointer is required by the ABI, also spill LR so that we
3030 // emit a complete frame record.
3031 if ((requiresAAPCSFrameRecord(MF) || MF.disableFramePointerElim()) &&
3032 !LRSpilled) {
3033 SavedRegs.set(ARM::LR);
3034 LRSpilled = true;
3035 NumGPRSpills++;
3036 auto LRPos = llvm::find(Range&: UnspilledCS1GPRs, Val: ARM::LR);
3037 if (LRPos != UnspilledCS1GPRs.end())
3038 UnspilledCS1GPRs.erase(CI: LRPos);
3039 }
3040 auto FPPos = llvm::find(Range&: UnspilledCS1GPRs, Val: FramePtr);
3041 if (FPPos != UnspilledCS1GPRs.end())
3042 UnspilledCS1GPRs.erase(CI: FPPos);
3043 NumGPRSpills++;
3044 if (FramePtr == ARM::R7)
3045 CS1Spilled = true;
3046 }
3047
3048 // This is the number of extra spills inserted for callee-save GPRs which
3049 // would not otherwise be used by the function. When greater than zero it
3050 // guaranteees that it is possible to scavenge a register to hold the
3051 // address of a stack slot. On Thumb1, the register must be a valid operand
3052 // to tSTRi, i.e. r4-r7. For other subtargets, this is any GPR, i.e. r4-r11
3053 // or lr.
3054 //
3055 // If we don't insert a spill, we instead allocate an emergency spill
3056 // slot, which can be used by scavenging to spill an arbitrary register.
3057 //
3058 // We currently don't try to figure out whether any specific instruction
3059 // requires scavening an additional register.
3060 unsigned NumExtraCSSpill = 0;
3061
3062 if (AFI->isThumb1OnlyFunction()) {
3063 // For Thumb1-only targets, we need some low registers when we save and
3064 // restore the high registers (which aren't allocatable, but could be
3065 // used by inline assembly) because the push/pop instructions can not
3066 // access high registers. If necessary, we might need to push more low
3067 // registers to ensure that there is at least one free that can be used
3068 // for the saving & restoring, and preferably we should ensure that as
3069 // many as are needed are available so that fewer push/pop instructions
3070 // are required.
3071
3072 // Low registers which are not currently pushed, but could be (r4-r7).
3073 SmallVector<unsigned, 4> AvailableRegs;
3074
3075 // Unused argument registers (r0-r3) can be clobbered in the prologue for
3076 // free.
3077 int EntryRegDeficit = 0;
3078 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
3079 if (!MF.getRegInfo().isLiveIn(Reg)) {
3080 --EntryRegDeficit;
3081 LLVM_DEBUG(dbgs()
3082 << printReg(Reg, TRI)
3083 << " is unused argument register, EntryRegDeficit = "
3084 << EntryRegDeficit << "\n");
3085 }
3086 }
3087
3088 // Unused return registers can be clobbered in the epilogue for free.
3089 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
3090 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
3091 << " return regs used, ExitRegDeficit = "
3092 << ExitRegDeficit << "\n");
3093
3094 int RegDeficit = std::max(a: EntryRegDeficit, b: ExitRegDeficit);
3095 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
3096
3097 // r4-r6 can be used in the prologue if they are pushed by the first push
3098 // instruction.
3099 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
3100 if (SavedRegs.test(Idx: Reg)) {
3101 --RegDeficit;
3102 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3103 << " is saved low register, RegDeficit = "
3104 << RegDeficit << "\n");
3105 } else {
3106 AvailableRegs.push_back(Elt: Reg);
3107 LLVM_DEBUG(
3108 dbgs()
3109 << printReg(Reg, TRI)
3110 << " is non-saved low register, adding to AvailableRegs\n");
3111 }
3112 }
3113
3114 // r7 can be used if it is not being used as the frame pointer.
3115 if (!HasFP || FramePtr != ARM::R7) {
3116 if (SavedRegs.test(Idx: ARM::R7)) {
3117 --RegDeficit;
3118 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
3119 << RegDeficit << "\n");
3120 } else {
3121 AvailableRegs.push_back(Elt: ARM::R7);
3122 LLVM_DEBUG(
3123 dbgs()
3124 << "%r7 is non-saved low register, adding to AvailableRegs\n");
3125 }
3126 }
3127
3128 // Each of r8-r11 needs to be copied to a low register, then pushed.
3129 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
3130 if (SavedRegs.test(Idx: Reg)) {
3131 ++RegDeficit;
3132 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3133 << " is saved high register, RegDeficit = "
3134 << RegDeficit << "\n");
3135 }
3136 }
3137
3138 // LR can only be used by PUSH, not POP, and can't be used at all if the
3139 // llvm.returnaddress intrinsic is used. This is only worth doing if we
3140 // are more limited at function entry than exit.
3141 if ((EntryRegDeficit > ExitRegDeficit) &&
3142 !(MF.getRegInfo().isLiveIn(Reg: ARM::LR) &&
3143 MF.getFrameInfo().isReturnAddressTaken())) {
3144 if (SavedRegs.test(Idx: ARM::LR)) {
3145 --RegDeficit;
3146 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
3147 << RegDeficit << "\n");
3148 } else {
3149 AvailableRegs.push_back(Elt: ARM::LR);
3150 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
3151 }
3152 }
3153
3154 // If there are more high registers that need pushing than low registers
3155 // available, push some more low registers so that we can use fewer push
3156 // instructions. This might not reduce RegDeficit all the way to zero,
3157 // because we can only guarantee that r4-r6 are available, but r8-r11 may
3158 // need saving.
3159 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
3160 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
3161 unsigned Reg = AvailableRegs.pop_back_val();
3162 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3163 << " to make up reg deficit\n");
3164 SavedRegs.set(Reg);
3165 NumGPRSpills++;
3166 CS1Spilled = true;
3167 assert(!MRI.isReserved(Reg) && "Should not be reserved");
3168 if (Reg != ARM::LR && !MRI.isPhysRegUsed(PhysReg: Reg))
3169 NumExtraCSSpill++;
3170 UnspilledCS1GPRs.erase(CI: llvm::find(Range&: UnspilledCS1GPRs, Val: Reg));
3171 if (Reg == ARM::LR)
3172 LRSpilled = true;
3173 }
3174 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
3175 << "\n");
3176 }
3177
3178 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
3179 // restore LR in that case.
3180 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
3181
3182 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
3183 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
3184 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
3185 SavedRegs.set(ARM::LR);
3186 NumGPRSpills++;
3187 SmallVectorImpl<unsigned>::iterator LRPos;
3188 LRPos = llvm::find(Range&: UnspilledCS1GPRs, Val: (unsigned)ARM::LR);
3189 if (LRPos != UnspilledCS1GPRs.end())
3190 UnspilledCS1GPRs.erase(CI: LRPos);
3191
3192 ForceLRSpill = false;
3193 if (!MRI.isReserved(PhysReg: ARM::LR) && !MRI.isPhysRegUsed(PhysReg: ARM::LR) &&
3194 !AFI->isThumb1OnlyFunction())
3195 NumExtraCSSpill++;
3196 }
3197
3198 // If stack and double are 8-byte aligned and we are spilling an odd number
3199 // of GPRs, spill one extra callee save GPR so we won't have to pad between
3200 // the integer and double callee save areas.
3201 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
3202 const Align TargetAlign = getStackAlign();
3203 if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
3204 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
3205 for (unsigned Reg : UnspilledCS1GPRs) {
3206 // Don't spill high register if the function is thumb. In the case of
3207 // Windows on ARM, accept R11 (frame pointer)
3208 if (!AFI->isThumbFunction() ||
3209 (STI.isTargetWindows() && Reg == ARM::R11) ||
3210 isARMLowRegister(Reg) ||
3211 (Reg == ARM::LR && !ExpensiveLRRestore)) {
3212 SavedRegs.set(Reg);
3213 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3214 << " to make up alignment\n");
3215 if (!MRI.isReserved(PhysReg: Reg) && !MRI.isPhysRegUsed(PhysReg: Reg) &&
3216 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
3217 NumExtraCSSpill++;
3218 break;
3219 }
3220 }
3221 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
3222 unsigned Reg = UnspilledCS2GPRs.front();
3223 SavedRegs.set(Reg);
3224 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3225 << " to make up alignment\n");
3226 if (!MRI.isReserved(PhysReg: Reg) && !MRI.isPhysRegUsed(PhysReg: Reg))
3227 NumExtraCSSpill++;
3228 }
3229 }
3230
3231 // Estimate if we might need to scavenge registers at some point in order
3232 // to materialize a stack offset. If so, either spill one additional
3233 // callee-saved register or reserve a special spill slot to facilitate
3234 // register scavenging. Thumb1 needs a spill slot for stack pointer
3235 // adjustments and for frame index accesses when FP is high register,
3236 // even when the frame itself is small.
3237 unsigned RegsNeeded = 0;
3238 if (BigFrameOffsets || canSpillOnFrameIndexAccess(MF, TFI: *this)) {
3239 RegsNeeded++;
3240 // With thumb1 execute-only we may need an additional register for saving
3241 // and restoring the CPSR.
3242 if (AFI->isThumb1OnlyFunction() && STI.genExecuteOnly() && !STI.useMovt())
3243 RegsNeeded++;
3244 }
3245
3246 if (RegsNeeded > NumExtraCSSpill) {
3247 // If any non-reserved CS register isn't spilled, just spill one or two
3248 // extra. That should take care of it!
3249 unsigned NumExtras = TargetAlign.value() / 4;
3250 SmallVector<unsigned, 2> Extras;
3251 while (NumExtras && !UnspilledCS1GPRs.empty()) {
3252 unsigned Reg = UnspilledCS1GPRs.pop_back_val();
3253 if (!MRI.isReserved(PhysReg: Reg) &&
3254 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
3255 Extras.push_back(Elt: Reg);
3256 NumExtras--;
3257 }
3258 }
3259 // For non-Thumb1 functions, also check for hi-reg CS registers
3260 if (!AFI->isThumb1OnlyFunction()) {
3261 while (NumExtras && !UnspilledCS2GPRs.empty()) {
3262 unsigned Reg = UnspilledCS2GPRs.pop_back_val();
3263 if (!MRI.isReserved(PhysReg: Reg)) {
3264 Extras.push_back(Elt: Reg);
3265 NumExtras--;
3266 }
3267 }
3268 }
3269 if (NumExtras == 0) {
3270 for (unsigned Reg : Extras) {
3271 SavedRegs.set(Reg);
3272 if (!MRI.isPhysRegUsed(PhysReg: Reg))
3273 NumExtraCSSpill++;
3274 }
3275 }
3276 while ((RegsNeeded > NumExtraCSSpill) && RS) {
3277 // Reserve a slot closest to SP or frame pointer.
3278 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
3279 const TargetRegisterClass &RC = ARM::GPRRegClass;
3280 unsigned Size = TRI->getSpillSize(RC);
3281 Align Alignment = TRI->getSpillAlign(RC);
3282 RS->addScavengingFrameIndex(
3283 FI: MFI.CreateSpillStackObject(Size, Alignment));
3284 --RegsNeeded;
3285 }
3286 }
3287 }
3288
3289 if (ForceLRSpill)
3290 SavedRegs.set(ARM::LR);
3291 AFI->setLRIsSpilled(SavedRegs.test(Idx: ARM::LR));
3292}
3293
3294void ARMFrameLowering::updateLRRestored(MachineFunction &MF) {
3295 MachineFrameInfo &MFI = MF.getFrameInfo();
3296 if (!MFI.isCalleeSavedInfoValid())
3297 return;
3298
3299 // Check if all terminators do not implicitly use LR. Then we can 'restore' LR
3300 // into PC so it is not live out of the return block: Clear the Restored bit
3301 // in that case.
3302 for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) {
3303 if (Info.getReg() != ARM::LR)
3304 continue;
3305 if (all_of(Range&: MF, P: [](const MachineBasicBlock &MBB) {
3306 return all_of(Range: MBB.terminators(), P: [](const MachineInstr &Term) {
3307 return !Term.isReturn() || Term.getOpcode() == ARM::LDMIA_RET ||
3308 Term.getOpcode() == ARM::t2LDMIA_RET ||
3309 Term.getOpcode() == ARM::tPOP_RET;
3310 });
3311 })) {
3312 Info.setRestored(false);
3313 break;
3314 }
3315 }
3316}
3317
3318void ARMFrameLowering::processFunctionBeforeFrameFinalized(
3319 MachineFunction &MF, RegScavenger *RS) const {
3320 TargetFrameLowering::processFunctionBeforeFrameFinalized(MF, RS);
3321 updateLRRestored(MF);
3322}
3323
3324void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
3325 BitVector &SavedRegs) const {
3326 TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
3327
3328 // If we have the "returned" parameter attribute which guarantees that we
3329 // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
3330 // record that fact for IPRA.
3331 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3332 if (AFI->getPreservesR0())
3333 SavedRegs.set(ARM::R0);
3334}
3335
3336bool ARMFrameLowering::assignCalleeSavedSpillSlots(
3337 MachineFunction &MF, const TargetRegisterInfo *TRI,
3338 std::vector<CalleeSavedInfo> &CSI) const {
3339 // For CMSE entry functions, handle floating-point context as if it was a
3340 // callee-saved register.
3341 if (STI.hasV8_1MMainlineOps() &&
3342 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
3343 CSI.emplace_back(args: ARM::FPCXTNS);
3344 CSI.back().setRestored(false);
3345 }
3346
3347 // For functions, which sign their return address, upon function entry, the
3348 // return address PAC is computed in R12. Treat R12 as a callee-saved register
3349 // in this case.
3350 const auto &AFI = *MF.getInfo<ARMFunctionInfo>();
3351 if (AFI.shouldSignReturnAddress()) {
3352 // The order of register must match the order we push them, because the
3353 // PEI assigns frame indices in that order. That order depends on the
3354 // PushPopSplitVariation, there are only two cases which we use with return
3355 // address signing:
3356 switch (STI.getPushPopSplitVariation(MF)) {
3357 case ARMSubtarget::SplitR7:
3358 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8
3359 CSI.insert(position: find_if(Range&: CSI,
3360 P: [=](const auto &CS) {
3361 MCRegister Reg = CS.getReg();
3362 return Reg == ARM::R10 || Reg == ARM::R11 ||
3363 Reg == ARM::R8 || Reg == ARM::R9 ||
3364 ARM::DPRRegClass.contains(Reg);
3365 }),
3366 x: CalleeSavedInfo(ARM::R12));
3367 break;
3368 case ARMSubtarget::SplitR11AAPCSSignRA:
3369 // With SplitR11AAPCSSignRA, R12 will always be the highest-addressed CSR
3370 // on the stack.
3371 CSI.insert(position: CSI.begin(), x: CalleeSavedInfo(ARM::R12));
3372 break;
3373 case ARMSubtarget::NoSplit:
3374 assert(!MF.disableFramePointerElim() &&
3375 "ABI-required frame pointers need a CSR split when signing return "
3376 "address.");
3377 CSI.insert(position: find_if(Range&: CSI,
3378 P: [=](const auto &CS) {
3379 MCRegister Reg = CS.getReg();
3380 return Reg != ARM::LR;
3381 }),
3382 x: CalleeSavedInfo(ARM::R12));
3383 break;
3384 default:
3385 llvm_unreachable("Unexpected CSR split with return address signing");
3386 }
3387 }
3388
3389 return false;
3390}
3391
3392const TargetFrameLowering::SpillSlot *
3393ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
3394 static const SpillSlot FixedSpillOffsets[] = {{.Reg: ARM::FPCXTNS, .Offset: -4}};
3395 NumEntries = std::size(FixedSpillOffsets);
3396 return FixedSpillOffsets;
3397}
3398
3399MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
3400 MachineFunction &MF, MachineBasicBlock &MBB,
3401 MachineBasicBlock::iterator I) const {
3402 const ARMBaseInstrInfo &TII =
3403 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3404 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3405 bool isARM = !AFI->isThumbFunction();
3406 DebugLoc dl = I->getDebugLoc();
3407 unsigned Opc = I->getOpcode();
3408 bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode();
3409 unsigned CalleePopAmount = IsDestroy ? I->getOperand(i: 1).getImm() : 0;
3410
3411 assert(!AFI->isThumb1OnlyFunction() &&
3412 "This eliminateCallFramePseudoInstr does not support Thumb1!");
3413
3414 int PIdx = I->findFirstPredOperandIdx();
3415 ARMCC::CondCodes Pred = (PIdx == -1)
3416 ? ARMCC::AL
3417 : (ARMCC::CondCodes)I->getOperand(i: PIdx).getImm();
3418 unsigned PredReg = TII.getFramePred(MI: *I);
3419
3420 if (!hasReservedCallFrame(MF)) {
3421 // Bail early if the callee is expected to do the adjustment.
3422 if (IsDestroy && CalleePopAmount != -1U)
3423 return MBB.erase(I);
3424
3425 // If we have alloca, convert as follows:
3426 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
3427 // ADJCALLSTACKUP -> add, sp, sp, amount
3428 unsigned Amount = TII.getFrameSize(I: *I);
3429 if (Amount != 0) {
3430 // We need to keep the stack aligned properly. To do this, we round the
3431 // amount of space needed for the outgoing arguments up to the next
3432 // alignment boundary.
3433 Amount = alignSPAdjust(SPAdj: Amount);
3434
3435 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
3436 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: -Amount, MIFlags: MachineInstr::NoFlags,
3437 Pred, PredReg);
3438 } else {
3439 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
3440 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: Amount, MIFlags: MachineInstr::NoFlags,
3441 Pred, PredReg);
3442 }
3443 }
3444 } else if (CalleePopAmount != -1U) {
3445 // If the calling convention demands that the callee pops arguments from the
3446 // stack, we want to add it back if we have a reserved call frame.
3447 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: -CalleePopAmount,
3448 MIFlags: MachineInstr::NoFlags, Pred, PredReg);
3449 }
3450 return MBB.erase(I);
3451}
3452
3453/// Get the minimum constant for ARM that is greater than or equal to the
3454/// argument. In ARM, constants can have any value that can be produced by
3455/// rotating an 8-bit value to the right by an even number of bits within a
3456/// 32-bit word.
3457static uint32_t alignToARMConstant(uint32_t Value) {
3458 unsigned Shifted = 0;
3459
3460 if (Value == 0)
3461 return 0;
3462
3463 while (!(Value & 0xC0000000)) {
3464 Value = Value << 2;
3465 Shifted += 2;
3466 }
3467
3468 bool Carry = (Value & 0x00FFFFFF);
3469 Value = ((Value & 0xFF000000) >> 24) + Carry;
3470
3471 if (Value & 0x0000100)
3472 Value = Value & 0x000001FC;
3473
3474 if (Shifted > 24)
3475 Value = Value >> (Shifted - 24);
3476 else
3477 Value = Value << (24 - Shifted);
3478
3479 return Value;
3480}
3481
3482// The stack limit in the TCB is set to this many bytes above the actual
3483// stack limit.
3484static const uint64_t kSplitStackAvailable = 256;
3485
3486// Adjust the function prologue to enable split stacks. This currently only
3487// supports android and linux.
3488//
3489// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
3490// must be well defined in order to allow for consistent implementations of the
3491// __morestack helper function. The ABI is also not a normal ABI in that it
3492// doesn't follow the normal calling conventions because this allows the
3493// prologue of each function to be optimized further.
3494//
3495// Currently, the ABI looks like (when calling __morestack)
3496//
3497// * r4 holds the minimum stack size requested for this function call
3498// * r5 holds the stack size of the arguments to the function
3499// * the beginning of the function is 3 instructions after the call to
3500// __morestack
3501//
3502// Implementations of __morestack should use r4 to allocate a new stack, r5 to
3503// place the arguments on to the new stack, and the 3-instruction knowledge to
3504// jump directly to the body of the function when working on the new stack.
3505//
3506// An old (and possibly no longer compatible) implementation of __morestack for
3507// ARM can be found at [1].
3508//
3509// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
3510void ARMFrameLowering::adjustForSegmentedStacks(
3511 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3512 unsigned Opcode;
3513 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
3514 bool Thumb = ST->isThumb();
3515 bool Thumb2 = ST->isThumb2();
3516
3517 // Sadly, this currently doesn't support varargs, platforms other than
3518 // android/linux. Note that thumb1/thumb2 are support for android/linux.
3519 if (MF.getFunction().isVarArg())
3520 report_fatal_error(reason: "Segmented stacks do not support vararg functions.");
3521 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
3522 report_fatal_error(reason: "Segmented stacks not supported on this platform.");
3523
3524 MachineFrameInfo &MFI = MF.getFrameInfo();
3525 const ARMBaseInstrInfo &TII =
3526 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3527 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
3528 DebugLoc DL;
3529
3530 if (!MFI.needsSplitStackProlog())
3531 return;
3532
3533 uint64_t StackSize = MFI.getStackSize();
3534
3535 // Use R4 and R5 as scratch registers.
3536 // We save R4 and R5 before use and restore them before leaving the function.
3537 unsigned ScratchReg0 = ARM::R4;
3538 unsigned ScratchReg1 = ARM::R5;
3539 unsigned MovOp = ST->useMovt() ? ARM::t2MOVi32imm : ARM::tMOVi32imm;
3540 uint64_t AlignedStackSize;
3541
3542 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
3543 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
3544 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
3545 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
3546 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
3547
3548 // Grab everything that reaches PrologueMBB to update there liveness as well.
3549 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
3550 SmallVector<MachineBasicBlock *, 2> WalkList;
3551 WalkList.push_back(Elt: &PrologueMBB);
3552
3553 do {
3554 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
3555 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
3556 if (BeforePrologueRegion.insert(Ptr: PredBB).second)
3557 WalkList.push_back(Elt: PredBB);
3558 }
3559 } while (!WalkList.empty());
3560
3561 // The order in that list is important.
3562 // The blocks will all be inserted before PrologueMBB using that order.
3563 // Therefore the block that should appear first in the CFG should appear
3564 // first in the list.
3565 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
3566 PostStackMBB};
3567
3568 BeforePrologueRegion.insert_range(R&: AddedBlocks);
3569
3570 for (const auto &LI : PrologueMBB.liveins()) {
3571 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
3572 PredBB->addLiveIn(RegMaskPair: LI);
3573 }
3574
3575 // Remove the newly added blocks from the list, since we know
3576 // we do not have to do the following updates for them.
3577 for (MachineBasicBlock *B : AddedBlocks) {
3578 BeforePrologueRegion.erase(Ptr: B);
3579 MF.insert(MBBI: PrologueMBB.getIterator(), MBB: B);
3580 }
3581
3582 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
3583 // Make sure the LiveIns are still sorted and unique.
3584 MBB->sortUniqueLiveIns();
3585 // Replace the edges to PrologueMBB by edges to the sequences
3586 // we are about to add, but only update for immediate predecessors.
3587 if (MBB->isSuccessor(MBB: &PrologueMBB))
3588 MBB->ReplaceUsesOfBlockWith(Old: &PrologueMBB, New: AddedBlocks[0]);
3589 }
3590
3591 // The required stack size that is aligned to ARM constant criterion.
3592 AlignedStackSize = alignToARMConstant(Value: StackSize);
3593
3594 // When the frame size is less than 256 we just compare the stack
3595 // boundary directly to the value of the stack pointer, per gcc.
3596 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
3597
3598 // We will use two of the callee save registers as scratch registers so we
3599 // need to save those registers onto the stack.
3600 // We will use SR0 to hold stack limit and SR1 to hold the stack size
3601 // requested and arguments for __morestack().
3602 // SR0: Scratch Register #0
3603 // SR1: Scratch Register #1
3604 // push {SR0, SR1}
3605 if (Thumb) {
3606 BuildMI(BB: PrevStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPUSH))
3607 .add(MOs: predOps(Pred: ARMCC::AL))
3608 .addReg(RegNo: ScratchReg0)
3609 .addReg(RegNo: ScratchReg1);
3610 } else {
3611 BuildMI(BB: PrevStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::STMDB_UPD))
3612 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3613 .addReg(RegNo: ARM::SP)
3614 .add(MOs: predOps(Pred: ARMCC::AL))
3615 .addReg(RegNo: ScratchReg0)
3616 .addReg(RegNo: ScratchReg1);
3617 }
3618
3619 // Emit the relevant DWARF information about the change in stack pointer as
3620 // well as where to find both r4 and r5 (the callee-save registers)
3621 if (!MF.usesWindowsUnwindInfo()) {
3622 CFIInstBuilder CFIBuilder(PrevStackMBB, MachineInstr::NoFlags);
3623 CFIBuilder.buildDefCFAOffset(Offset: 8);
3624 CFIBuilder.buildOffset(Reg: ScratchReg1, Offset: -4);
3625 CFIBuilder.buildOffset(Reg: ScratchReg0, Offset: -8);
3626 }
3627
3628 // mov SR1, sp
3629 if (Thumb) {
3630 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ScratchReg1)
3631 .addReg(RegNo: ARM::SP)
3632 .add(MOs: predOps(Pred: ARMCC::AL));
3633 } else if (CompareStackPointer) {
3634 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVr), DestReg: ScratchReg1)
3635 .addReg(RegNo: ARM::SP)
3636 .add(MOs: predOps(Pred: ARMCC::AL))
3637 .add(MO: condCodeOp());
3638 }
3639
3640 // sub SR1, sp, #StackSize
3641 if (!CompareStackPointer && Thumb) {
3642 if (AlignedStackSize < 256) {
3643 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tSUBi8), DestReg: ScratchReg1)
3644 .add(MO: condCodeOp())
3645 .addReg(RegNo: ScratchReg1)
3646 .addImm(Val: AlignedStackSize)
3647 .add(MOs: predOps(Pred: ARMCC::AL));
3648 } else {
3649 if (Thumb2 || ST->genExecuteOnly()) {
3650 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3651 .addImm(Val: AlignedStackSize);
3652 } else {
3653 auto MBBI = McrMBB->end();
3654 auto RegInfo = STI.getRegisterInfo();
3655 RegInfo->emitLoadConstPool(MBB&: *McrMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3656 Val: AlignedStackSize);
3657 }
3658 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tSUBrr), DestReg: ScratchReg1)
3659 .add(MO: condCodeOp())
3660 .addReg(RegNo: ScratchReg1)
3661 .addReg(RegNo: ScratchReg0)
3662 .add(MOs: predOps(Pred: ARMCC::AL));
3663 }
3664 } else if (!CompareStackPointer) {
3665 if (AlignedStackSize < 256) {
3666 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::SUBri), DestReg: ScratchReg1)
3667 .addReg(RegNo: ARM::SP)
3668 .addImm(Val: AlignedStackSize)
3669 .add(MOs: predOps(Pred: ARMCC::AL))
3670 .add(MO: condCodeOp());
3671 } else {
3672 auto MBBI = McrMBB->end();
3673 auto RegInfo = STI.getRegisterInfo();
3674 RegInfo->emitLoadConstPool(MBB&: *McrMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3675 Val: AlignedStackSize);
3676 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::SUBrr), DestReg: ScratchReg1)
3677 .addReg(RegNo: ARM::SP)
3678 .addReg(RegNo: ScratchReg0)
3679 .add(MOs: predOps(Pred: ARMCC::AL))
3680 .add(MO: condCodeOp());
3681 }
3682 }
3683
3684 if (Thumb && ST->isThumb1Only()) {
3685 if (ST->genExecuteOnly()) {
3686 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3687 .addExternalSymbol(FnName: "__STACK_LIMIT");
3688 } else {
3689 unsigned PCLabelId = ARMFI->createPICLabelUId();
3690 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
3691 C&: MF.getFunction().getContext(), s: "__STACK_LIMIT", ID: PCLabelId, PCAdj: 0);
3692 MachineConstantPool *MCP = MF.getConstantPool();
3693 unsigned CPI = MCP->getConstantPoolIndex(V: NewCPV, Alignment: Align(4));
3694
3695 // ldr SR0, [pc, offset(STACK_LIMIT)]
3696 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tLDRpci), DestReg: ScratchReg0)
3697 .addConstantPoolIndex(Idx: CPI)
3698 .add(MOs: predOps(Pred: ARMCC::AL));
3699 }
3700
3701 // ldr SR0, [SR0]
3702 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tLDRi), DestReg: ScratchReg0)
3703 .addReg(RegNo: ScratchReg0)
3704 .addImm(Val: 0)
3705 .add(MOs: predOps(Pred: ARMCC::AL));
3706 } else {
3707 // Get TLS base address from the coprocessor
3708 // mrc p15, #0, SR0, c13, c0, #3
3709 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: Thumb ? ARM::t2MRC : ARM::MRC),
3710 DestReg: ScratchReg0)
3711 .addImm(Val: 15)
3712 .addImm(Val: 0)
3713 .addImm(Val: 13)
3714 .addImm(Val: 0)
3715 .addImm(Val: 3)
3716 .add(MOs: predOps(Pred: ARMCC::AL));
3717
3718 // Use the last tls slot on android and a private field of the TCP on linux.
3719 assert(ST->isTargetAndroid() || ST->isTargetLinux());
3720 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
3721
3722 // Get the stack limit from the right offset
3723 // ldr SR0, [sr0, #4 * TlsOffset]
3724 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
3725 DestReg: ScratchReg0)
3726 .addReg(RegNo: ScratchReg0)
3727 .addImm(Val: 4 * TlsOffset)
3728 .add(MOs: predOps(Pred: ARMCC::AL));
3729 }
3730
3731 // Compare stack limit with stack size requested.
3732 // cmp SR0, SR1
3733 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
3734 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode))
3735 .addReg(RegNo: ScratchReg0)
3736 .addReg(RegNo: ScratchReg1)
3737 .add(MOs: predOps(Pred: ARMCC::AL));
3738
3739 // This jump is taken if StackLimit <= SP - stack required.
3740 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
3741 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode))
3742 .addMBB(MBB: PostStackMBB)
3743 .addImm(Val: ARMCC::LS)
3744 .addReg(RegNo: ARM::CPSR);
3745
3746 // Calling __morestack(StackSize, Size of stack arguments).
3747 // __morestack knows that the stack size requested is in SR0(r4)
3748 // and amount size of stack arguments is in SR1(r5).
3749
3750 // Pass first argument for the __morestack by Scratch Register #0.
3751 // The amount size of stack required
3752 if (Thumb) {
3753 if (AlignedStackSize < 256) {
3754 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8), DestReg: ScratchReg0)
3755 .add(MO: condCodeOp())
3756 .addImm(Val: AlignedStackSize)
3757 .add(MOs: predOps(Pred: ARMCC::AL));
3758 } else {
3759 if (Thumb2 || ST->genExecuteOnly()) {
3760 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3761 .addImm(Val: AlignedStackSize);
3762 } else {
3763 auto MBBI = AllocMBB->end();
3764 auto RegInfo = STI.getRegisterInfo();
3765 RegInfo->emitLoadConstPool(MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3766 Val: AlignedStackSize);
3767 }
3768 }
3769 } else {
3770 if (AlignedStackSize < 256) {
3771 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVi), DestReg: ScratchReg0)
3772 .addImm(Val: AlignedStackSize)
3773 .add(MOs: predOps(Pred: ARMCC::AL))
3774 .add(MO: condCodeOp());
3775 } else {
3776 auto MBBI = AllocMBB->end();
3777 auto RegInfo = STI.getRegisterInfo();
3778 RegInfo->emitLoadConstPool(MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3779 Val: AlignedStackSize);
3780 }
3781 }
3782
3783 // Pass second argument for the __morestack by Scratch Register #1.
3784 // The amount size of stack consumed to save function arguments.
3785 if (Thumb) {
3786 if (ARMFI->getArgumentStackSize() < 256) {
3787 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8), DestReg: ScratchReg1)
3788 .add(MO: condCodeOp())
3789 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()))
3790 .add(MOs: predOps(Pred: ARMCC::AL));
3791 } else {
3792 if (Thumb2 || ST->genExecuteOnly()) {
3793 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg1)
3794 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3795 } else {
3796 auto MBBI = AllocMBB->end();
3797 auto RegInfo = STI.getRegisterInfo();
3798 RegInfo->emitLoadConstPool(
3799 MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg1, SubIdx: 0,
3800 Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3801 }
3802 }
3803 } else {
3804 if (alignToARMConstant(Value: ARMFI->getArgumentStackSize()) < 256) {
3805 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVi), DestReg: ScratchReg1)
3806 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()))
3807 .add(MOs: predOps(Pred: ARMCC::AL))
3808 .add(MO: condCodeOp());
3809 } else {
3810 auto MBBI = AllocMBB->end();
3811 auto RegInfo = STI.getRegisterInfo();
3812 RegInfo->emitLoadConstPool(
3813 MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg1, SubIdx: 0,
3814 Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3815 }
3816 }
3817
3818 // push {lr} - Save return address of this function.
3819 if (Thumb) {
3820 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPUSH))
3821 .add(MOs: predOps(Pred: ARMCC::AL))
3822 .addReg(RegNo: ARM::LR);
3823 } else {
3824 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::STMDB_UPD))
3825 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3826 .addReg(RegNo: ARM::SP)
3827 .add(MOs: predOps(Pred: ARMCC::AL))
3828 .addReg(RegNo: ARM::LR);
3829 }
3830
3831 // Emit the DWARF info about the change in stack as well as where to find the
3832 // previous link register
3833 if (!MF.usesWindowsUnwindInfo()) {
3834 CFIInstBuilder CFIBuilder(AllocMBB, MachineInstr::NoFlags);
3835 CFIBuilder.buildDefCFAOffset(Offset: 12);
3836 CFIBuilder.buildOffset(Reg: ARM::LR, Offset: -12);
3837 }
3838
3839 // Call __morestack().
3840 if (Thumb) {
3841 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tBL))
3842 .add(MOs: predOps(Pred: ARMCC::AL))
3843 .addExternalSymbol(FnName: "__morestack");
3844 } else {
3845 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::BL))
3846 .addExternalSymbol(FnName: "__morestack");
3847 }
3848
3849 // pop {lr} - Restore return address of this original function.
3850 if (Thumb) {
3851 if (ST->isThumb1Only()) {
3852 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3853 .add(MOs: predOps(Pred: ARMCC::AL))
3854 .addReg(RegNo: ScratchReg0);
3855 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::LR)
3856 .addReg(RegNo: ScratchReg0)
3857 .add(MOs: predOps(Pred: ARMCC::AL));
3858 } else {
3859 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::t2LDR_POST))
3860 .addReg(RegNo: ARM::LR, Flags: RegState::Define)
3861 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3862 .addReg(RegNo: ARM::SP)
3863 .addImm(Val: 4)
3864 .add(MOs: predOps(Pred: ARMCC::AL));
3865 }
3866 } else {
3867 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3868 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3869 .addReg(RegNo: ARM::SP)
3870 .add(MOs: predOps(Pred: ARMCC::AL))
3871 .addReg(RegNo: ARM::LR);
3872 }
3873
3874 // Restore SR0 and SR1 in case of __morestack() was called.
3875 // __morestack() will skip PostStackMBB block so we need to restore
3876 // scratch registers from here.
3877 // pop {SR0, SR1}
3878 if (Thumb) {
3879 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3880 .add(MOs: predOps(Pred: ARMCC::AL))
3881 .addReg(RegNo: ScratchReg0)
3882 .addReg(RegNo: ScratchReg1);
3883 } else {
3884 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3885 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3886 .addReg(RegNo: ARM::SP)
3887 .add(MOs: predOps(Pred: ARMCC::AL))
3888 .addReg(RegNo: ScratchReg0)
3889 .addReg(RegNo: ScratchReg1);
3890 }
3891
3892 // Update the CFA offset now that we've popped
3893 if (!MF.usesWindowsUnwindInfo())
3894 CFIInstBuilder(AllocMBB, MachineInstr::NoFlags).buildDefCFAOffset(Offset: 0);
3895
3896 // Return from this function.
3897 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ST->getReturnOpcode())).add(MOs: predOps(Pred: ARMCC::AL));
3898
3899 // Restore SR0 and SR1 in case of __morestack() was not called.
3900 // pop {SR0, SR1}
3901 if (Thumb) {
3902 BuildMI(BB: PostStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3903 .add(MOs: predOps(Pred: ARMCC::AL))
3904 .addReg(RegNo: ScratchReg0)
3905 .addReg(RegNo: ScratchReg1);
3906 } else {
3907 BuildMI(BB: PostStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3908 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3909 .addReg(RegNo: ARM::SP)
3910 .add(MOs: predOps(Pred: ARMCC::AL))
3911 .addReg(RegNo: ScratchReg0)
3912 .addReg(RegNo: ScratchReg1);
3913 }
3914
3915 // Update the CFA offset now that we've popped
3916 if (!MF.usesWindowsUnwindInfo()) {
3917 CFIInstBuilder CFIBuilder(PostStackMBB, MachineInstr::NoFlags);
3918 CFIBuilder.buildDefCFAOffset(Offset: 0);
3919
3920 // Tell debuggers that r4 and r5 are now the same as they were in the
3921 // previous function, that they're the "Same Value".
3922 CFIBuilder.buildSameValue(Reg: ScratchReg0);
3923 CFIBuilder.buildSameValue(Reg: ScratchReg1);
3924 }
3925
3926 // Organizing MBB lists
3927 PostStackMBB->addSuccessor(Succ: &PrologueMBB);
3928
3929 AllocMBB->addSuccessor(Succ: PostStackMBB);
3930
3931 GetMBB->addSuccessor(Succ: PostStackMBB);
3932 GetMBB->addSuccessor(Succ: AllocMBB);
3933
3934 McrMBB->addSuccessor(Succ: GetMBB);
3935
3936 PrevStackMBB->addSuccessor(Succ: McrMBB);
3937
3938#ifdef EXPENSIVE_CHECKS
3939 MF.verify();
3940#endif
3941}
3942