LLVM 24.0.0git
Thumb1FrameLowering.cpp
Go to the documentation of this file.
1//===- Thumb1FrameLowering.cpp - Thumb1 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 Thumb1 implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Thumb1FrameLowering.h"
14#include "ARMBaseInstrInfo.h"
15#include "ARMBaseRegisterInfo.h"
17#include "ARMSubtarget.h"
18#include "Thumb1InstrInfo.h"
19#include "ThumbRegisterInfo.h"
20#include "Utils/ARMBaseInfo.h"
21#include "llvm/ADT/BitVector.h"
22#include "llvm/ADT/STLExtras.h"
36#include "llvm/IR/DebugLoc.h"
39#include <cassert>
40#include <iterator>
41#include <vector>
42
43#define DEBUG_TYPE "arm-frame-lowering"
44
45using namespace llvm;
46
49
51 const MachineFrameInfo &MFI = MF.getFrameInfo();
52 unsigned CFSize = MFI.getMaxCallFrameSize();
53 // It's not always a good idea to include the call frame as part of the
54 // stack frame. ARM (especially Thumb) has small immediate offset to
55 // address the stack frame. So a large call frame can cause poor codegen
56 // and may even makes it impossible to scavenge a register.
57 if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
58 return false;
59
60 return !MFI.hasVarSizedObjects();
61}
62
65 const TargetInstrInfo &TII,
66 const DebugLoc &dl,
68 int NumBytes, Register ScratchReg,
69 unsigned MIFlags) {
70 // If it would take more than three instructions to adjust the stack pointer
71 // using tADDspi/tSUBspi, load an immediate instead.
72 if (std::abs(NumBytes) > 508 * 3) {
73 // We use a different codepath here from the normal
74 // emitThumbRegPlusImmediate so we don't have to deal with register
75 // scavenging. (Scavenging could try to use the emergency spill slot
76 // before we've actually finished setting up the stack.)
77 if (!ScratchReg.isValid())
78 report_fatal_error("Failed to emit Thumb1 stack adjustment");
79 MachineFunction &MF = *MBB.getParent();
80 const ARMSubtarget &ST = MF.getSubtarget<ARMSubtarget>();
81 if (ST.genExecuteOnly()) {
82 unsigned XOInstr = ST.useMovt() ? ARM::t2MOVi32imm : ARM::tMOVi32imm;
83 BuildMI(MBB, MBBI, dl, TII.get(XOInstr), ScratchReg)
84 .addImm(NumBytes).setMIFlags(MIFlags);
85 } else {
86 MRI.emitLoadConstPool(MBB, MBBI, dl, ScratchReg, 0, NumBytes, ARMCC::AL,
87 0, MIFlags);
88 }
89 BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDhirr), ARM::SP)
90 .addReg(ARM::SP)
91 .addReg(ScratchReg, RegState::Kill)
93 .setMIFlags(MIFlags);
94 return;
95 }
96 // FIXME: This is assuming the heuristics in emitThumbRegPlusImmediate
97 // won't change.
98 emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII, MRI,
99 MIFlags);
100}
101
104 const TargetInstrInfo &TII, const DebugLoc &dl,
105 const ThumbRegisterInfo &MRI, int NumBytes,
106 unsigned MIFlags = MachineInstr::NoFlags) {
107 emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
108 MRI, MIFlags);
109}
110
111
115 const Thumb1InstrInfo &TII =
116 *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
117 const ThumbRegisterInfo *RegInfo =
118 static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
119 if (!hasReservedCallFrame(MF)) {
120 // If we have alloca, convert as follows:
121 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
122 // ADJCALLSTACKUP -> add, sp, sp, amount
123 MachineInstr &Old = *I;
124 DebugLoc dl = Old.getDebugLoc();
125 unsigned Amount = TII.getFrameSize(Old);
126 if (Amount != 0) {
127 // We need to keep the stack aligned properly. To do this, we round the
128 // amount of space needed for the outgoing arguments up to the next
129 // alignment boundary.
130 Amount = alignTo(Amount, getStackAlign());
131
132 // Replace the pseudo instruction with a new instruction...
133 unsigned Opc = Old.getOpcode();
134 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
135 emitCallSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
136 } else {
137 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
138 emitCallSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
139 }
140 }
141 }
142 return MBB.erase(I);
143}
144
146 MachineBasicBlock &MBB) const {
148 MachineFrameInfo &MFI = MF.getFrameInfo();
150 const ThumbRegisterInfo *RegInfo =
151 static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
152 const Thumb1InstrInfo &TII =
153 *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
154
155 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
156 unsigned NumBytes = MFI.getStackSize();
157 assert(NumBytes >= ArgRegsSaveSize &&
158 "ArgRegsSaveSize is included in NumBytes");
159 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
160 assert(STI.getPushPopSplitVariation(MF) == ARMSubtarget::SplitR7 &&
161 "Must use R7 spilt for Thumb1");
162
163 // Debug location must be unknown since the first debug location is used
164 // to determine the end of the prologue.
165 DebugLoc dl;
166
167 Register FramePtr = RegInfo->getFrameRegister(MF);
168 Register BasePtr = RegInfo->getBaseRegister();
169 int CFAOffset = 0;
170
171 // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
172 NumBytes = (NumBytes + 3) & ~3;
173 MFI.setStackSize(NumBytes);
174
175 // Determine the sizes of each callee-save spill areas and record which frame
176 // belongs to which callee-save spill areas.
177 unsigned FRSize = 0, GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
178 int FramePtrSpillFI = 0;
180
181 if (ArgRegsSaveSize) {
182 emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
184 CFAOffset += ArgRegsSaveSize;
185 CFIBuilder.buildDefCFAOffset(CFAOffset);
186 }
187
188 if (!AFI->hasStackFrame()) {
189 if (NumBytes - ArgRegsSaveSize != 0) {
191 -(NumBytes - ArgRegsSaveSize), Register(),
193 CFAOffset += NumBytes - ArgRegsSaveSize;
194 CFIBuilder.buildDefCFAOffset(CFAOffset);
195 }
196 return;
197 }
198
199 bool HasFrameRecordArea = hasFP(MF) && ARM::hGPRRegClass.contains(FramePtr);
200
201 for (const CalleeSavedInfo &I : CSI) {
202 MCRegister Reg = I.getReg();
203 int FI = I.getFrameIdx();
204 if (Reg == FramePtr.asMCReg())
205 FramePtrSpillFI = FI;
206 switch (Reg) {
207 case ARM::R11:
208 if (HasFrameRecordArea) {
209 FRSize += 4;
210 break;
211 }
212 [[fallthrough]];
213 case ARM::R8:
214 case ARM::R9:
215 case ARM::R10:
216 GPRCS2Size += 4;
217 break;
218 case ARM::LR:
219 if (HasFrameRecordArea) {
220 FRSize += 4;
221 break;
222 }
223 [[fallthrough]];
224 case ARM::R4:
225 case ARM::R5:
226 case ARM::R6:
227 case ARM::R7:
228 GPRCS1Size += 4;
229 break;
230 default:
231 DPRCSSize += 8;
232 }
233 }
234
235 MachineBasicBlock::iterator FRPush, GPRCS1Push, GPRCS2Push;
236 if (HasFrameRecordArea) {
237 // Skip Frame Record setup:
238 // push {lr}
239 // mov lr, r11
240 // push {lr}
241 std::advance(MBBI, 2);
242 FRPush = MBBI++;
243 }
244
245 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
246 GPRCS1Push = MBBI;
247 ++MBBI;
248 }
249
250 // Find last push instruction for GPRCS2 - spilling of high registers
251 // (r8-r11) could consist of multiple tPUSH and tMOVr instructions.
252 while (true) {
254 // Skip a run of tMOVr instructions
255 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tMOVr &&
257 MBBI++;
258 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH &&
259 MBBI->getFlag(MachineInstr::FrameSetup)) {
260 GPRCS2Push = MBBI;
261 MBBI++;
262 } else {
263 // We have reached an instruction which is not a push, so the previous
264 // run of tMOVr instructions (which may have been empty) was not part of
265 // the prologue. Reset MBBI back to the last PUSH of the prologue.
266 MBBI = OldMBBI;
267 break;
268 }
269 }
270
271 // Skip past this code sequence, which is emitted to restore the LR if it is
272 // live-in and clobbered by the frame record setup code:
273 // ldr rX, [sp, #Y]
274 // mov lr, rX
275 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tLDRspi &&
276 MBBI->getFlag(MachineInstr::FrameSetup)) {
277 ++MBBI;
278 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tMOVr &&
279 MBBI->getOperand(0).getReg() == ARM::LR &&
280 MBBI->getFlag(MachineInstr::FrameSetup)) {
281 ++MBBI;
282 }
283 }
284
285 // Determine starting offsets of spill areas.
286 unsigned DPRCSOffset = NumBytes - ArgRegsSaveSize -
287 (FRSize + GPRCS1Size + GPRCS2Size + DPRCSSize);
288 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
289 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
290 bool HasFP = hasFP(MF);
291 if (HasFP)
292 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
293 NumBytes);
294 if (HasFrameRecordArea)
295 AFI->setFrameRecordSavedAreaSize(FRSize);
296 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
297 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
298 AFI->setDPRCalleeSavedArea1Offset(DPRCSOffset);
299 NumBytes = DPRCSOffset;
300
301 int FramePtrOffsetInBlock = 0;
302 unsigned adjustedGPRCS1Size = GPRCS1Size;
303 if (GPRCS1Size > 0 && GPRCS2Size == 0 &&
304 tryFoldSPUpdateIntoPushPop(STI, MF, &*(GPRCS1Push), NumBytes)) {
305 FramePtrOffsetInBlock = NumBytes;
306 adjustedGPRCS1Size += NumBytes;
307 NumBytes = 0;
308 }
309 CFAOffset += adjustedGPRCS1Size;
310
311 // Adjust FP so it point to the stack slot that contains the previous FP.
312 if (HasFP) {
314 HasFrameRecordArea ? std::next(FRPush) : std::next(GPRCS1Push);
315 if (HasFrameRecordArea) {
316 // We have just finished pushing the previous FP into the stack,
317 // so simply capture the SP value as the new Frame Pointer.
318 BuildMI(MBB, AfterPush, dl, TII.get(ARM::tMOVr), FramePtr)
319 .addReg(ARM::SP)
322 } else {
323 FramePtrOffsetInBlock +=
324 MFI.getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
325 BuildMI(MBB, AfterPush, dl, TII.get(ARM::tADDrSPi), FramePtr)
326 .addReg(ARM::SP)
327 .addImm(FramePtrOffsetInBlock / 4)
330 }
331
332 CFIBuilder.setInsertPoint(AfterPush);
333 if (FramePtrOffsetInBlock)
334 CFIBuilder.buildDefCFA(FramePtr, CFAOffset - FramePtrOffsetInBlock);
335 else
336 CFIBuilder.buildDefCFARegister(FramePtr);
337 if (NumBytes > 508)
338 // If offset is > 508 then sp cannot be adjusted in a single instruction,
339 // try restoring from fp instead.
340 AFI->setShouldRestoreSPFromFP(true);
341 }
342
343 // Emit call frame information for the callee-saved low registers.
344 if (GPRCS1Size > 0) {
345 CFIBuilder.setInsertPoint(std::next(GPRCS1Push));
346 if (adjustedGPRCS1Size)
347 CFIBuilder.buildDefCFAOffset(CFAOffset);
348 for (const CalleeSavedInfo &I : CSI) {
349 switch (I.getReg()) {
350 case ARM::R8:
351 case ARM::R9:
352 case ARM::R10:
353 case ARM::R11:
354 case ARM::R12:
355 break;
356 case ARM::R0:
357 case ARM::R1:
358 case ARM::R2:
359 case ARM::R3:
360 case ARM::R4:
361 case ARM::R5:
362 case ARM::R6:
363 case ARM::R7:
364 case ARM::LR:
365 CFIBuilder.buildOffset(I.getReg(),
366 MFI.getObjectOffset(I.getFrameIdx()));
367 break;
368 }
369 }
370 }
371
372 // Emit call frame information for the callee-saved high registers.
373 if (GPRCS2Size > 0) {
374 CFIBuilder.setInsertPoint(std::next(GPRCS2Push));
375 for (auto &I : CSI) {
376 switch (I.getReg()) {
377 case ARM::R8:
378 case ARM::R9:
379 case ARM::R10:
380 case ARM::R11:
381 case ARM::R12:
382 CFIBuilder.buildOffset(I.getReg(),
383 MFI.getObjectOffset(I.getFrameIdx()));
384 break;
385 default:
386 break;
387 }
388 }
389 }
390
391 if (NumBytes) {
392 // Insert it after all the callee-save spills.
393 //
394 // For a large stack frame, we might need a scratch register to store
395 // the size of the frame. We know all callee-save registers are free
396 // at this point in the prologue, so pick one.
397 Register ScratchRegister;
398 for (auto &I : CSI) {
399 MCRegister Reg = I.getReg();
400 if (isARMLowRegister(Reg) && !(HasFP && Reg == FramePtr.asMCReg())) {
401 ScratchRegister = Reg;
402 break;
403 }
404 }
405 emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
406 ScratchRegister, MachineInstr::FrameSetup);
407 if (!HasFP) {
408 CFAOffset += NumBytes;
409 CFIBuilder.buildDefCFAOffset(CFAOffset);
410 }
411 }
412
413 if (STI.isTargetELF() && HasFP)
416
417 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
418 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
419 AFI->setDPRCalleeSavedArea1Size(DPRCSSize);
420
421 if (RegInfo->hasStackRealignment(MF)) {
422 const unsigned NrBitsToZero = Log2(MFI.getMaxAlign());
423 // Emit the following sequence, using R4 as a temporary, since we cannot use
424 // SP as a source or destination register for the shifts:
425 // mov r4, sp
426 // lsrs r4, r4, #NrBitsToZero
427 // lsls r4, r4, #NrBitsToZero
428 // mov sp, r4
429 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
430 .addReg(ARM::SP, RegState::Kill)
432
433 BuildMI(MBB, MBBI, dl, TII.get(ARM::tLSRri), ARM::R4)
434 .addDef(ARM::CPSR)
435 .addReg(ARM::R4, RegState::Kill)
436 .addImm(NrBitsToZero)
438
439 BuildMI(MBB, MBBI, dl, TII.get(ARM::tLSLri), ARM::R4)
440 .addDef(ARM::CPSR)
441 .addReg(ARM::R4, RegState::Kill)
442 .addImm(NrBitsToZero)
444
445 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
446 .addReg(ARM::R4, RegState::Kill)
448
449 AFI->setShouldRestoreSPFromFP(true);
450 }
451
452 // If we need a base pointer, set it up here. It's whatever the value
453 // of the stack pointer is at this point. Any variable size objects
454 // will be allocated after this, so we can still use the base pointer
455 // to reference locals.
456 if (RegInfo->hasBasePointer(MF))
457 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
458 .addReg(ARM::SP)
460
461 // If the frame has variable sized objects then the epilogue must restore
462 // the sp from fp. We can assume there's an FP here since hasFP already
463 // checks for hasVarSizedObjects.
464 if (MFI.hasVarSizedObjects())
465 AFI->setShouldRestoreSPFromFP(true);
466
467 // In some cases, virtual registers have been introduced, e.g. by uses of
468 // emitThumbRegPlusImmInReg.
469 MF.getProperties().resetNoVRegs();
470}
471
473 MachineBasicBlock &MBB) const {
474 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
475 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
476 MachineFrameInfo &MFI = MF.getFrameInfo();
478 const ThumbRegisterInfo *RegInfo =
479 static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
480 const Thumb1InstrInfo &TII =
481 *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
482
483 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
484 int NumBytes = (int)MFI.getStackSize();
485 assert((unsigned)NumBytes >= ArgRegsSaveSize &&
486 "ArgRegsSaveSize is included in NumBytes");
487 Register FramePtr = RegInfo->getFrameRegister(MF);
488
489 if (!AFI->hasStackFrame()) {
490 if (NumBytes - ArgRegsSaveSize != 0)
492 NumBytes - ArgRegsSaveSize, Register(),
494 } else {
495 // Unwind MBBI to point to first LDR / VLDRD.
496 if (MBBI != MBB.begin()) {
497 do
498 --MBBI;
499 while (MBBI != MBB.begin() && MBBI->getFlag(MachineInstr::FrameDestroy));
500 if (!MBBI->getFlag(MachineInstr::FrameDestroy))
501 ++MBBI;
502 }
503
504 // Move SP to start of FP callee save spill area.
505 NumBytes -=
508 AFI->getDPRCalleeSavedArea1Size() + ArgRegsSaveSize);
509
510 // We are likely to need a scratch register and we know all callee-save
511 // registers are free at this point in the epilogue, so pick one.
512 Register ScratchRegister;
513 bool HasFP = hasFP(MF);
514 for (auto &I : MFI.getCalleeSavedInfo()) {
515 MCRegister Reg = I.getReg();
516 if (isARMLowRegister(Reg) && !(HasFP && Reg == FramePtr.asMCReg())) {
517 ScratchRegister = Reg;
518 break;
519 }
520 }
521
522 if (AFI->shouldRestoreSPFromFP()) {
523 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
524 // Reset SP based on frame pointer only if the stack frame extends beyond
525 // frame pointer stack slot, the target is ELF and the function has FP, or
526 // the target uses var sized objects.
527 if (NumBytes) {
528 assert(ScratchRegister.isValid() &&
529 "No scratch register to restore SP from FP!");
530 emitThumbRegPlusImmediate(MBB, MBBI, dl, ScratchRegister, FramePtr, -NumBytes,
532 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
533 .addReg(ScratchRegister)
536 } else
537 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
541 } else {
542 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
543 &MBB.front() != &*MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
544 MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
545 if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*PMBBI, NumBytes))
546 emitPrologueEpilogueSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes,
547 ScratchRegister, MachineInstr::FrameDestroy);
548 } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
549 emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes,
550 ScratchRegister, MachineInstr::FrameDestroy);
551 }
552 }
553
554 if (needPopSpecialFixUp(MF)) {
555 bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
556 (void)Done;
557 assert(Done && "Emission of the special fixup failed!?");
558 }
559}
560
562 if (!needPopSpecialFixUp(*MBB.getParent()))
563 return true;
564
565 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
566 return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
567}
568
569bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
570 ARMFunctionInfo *AFI =
571 const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
572 if (AFI->getArgRegsSaveSize())
573 return true;
574
575 // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
576 for (const CalleeSavedInfo &CSI : MF.getFrameInfo().getCalleeSavedInfo())
577 if (CSI.getReg() == ARM::LR)
578 return true;
579
580 return false;
581}
582
583static void findTemporariesForLR(const BitVector &GPRsNoLRSP,
584 const BitVector &PopFriendly,
585 const LiveRegUnits &UsedRegs, unsigned &PopReg,
586 unsigned &TmpReg, MachineRegisterInfo &MRI) {
587 PopReg = TmpReg = 0;
588 for (auto Reg : GPRsNoLRSP.set_bits()) {
589 if (UsedRegs.available(Reg)) {
590 // Remember the first pop-friendly register and exit.
591 if (PopFriendly.test(Reg)) {
592 PopReg = Reg;
593 TmpReg = 0;
594 break;
595 }
596 // Otherwise, remember that the register will be available to
597 // save a pop-friendly register.
598 TmpReg = Reg;
599 }
600 }
601}
602
603bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
604 bool DoIt) const {
606 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
607 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
608 const TargetInstrInfo &TII = *STI.getInstrInfo();
609 const ThumbRegisterInfo *RegInfo =
610 static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
611
612 // If MBBI is a return instruction, or is a tPOP followed by a return
613 // instruction in the successor BB, we may be able to directly restore
614 // LR in the PC.
615 // This is only possible with v5T ops (v4T can't change the Thumb bit via
616 // a POP PC instruction), and only if we do not need to emit any SP update.
617 // Otherwise, we need a temporary register to pop the value
618 // and copy that value into LR.
619 auto MBBI = MBB.getFirstTerminator();
620 bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
621 if (CanRestoreDirectly) {
622 if (MBBI != MBB.end() && MBBI->getOpcode() != ARM::tB)
623 CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
624 MBBI->getOpcode() == ARM::tPOP_RET);
625 else {
626 auto MBBI_prev = MBBI;
627 MBBI_prev--;
628 assert(MBBI_prev->getOpcode() == ARM::tPOP);
629 assert(MBB.succ_size() == 1);
630 if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
631 MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
632 else
633 CanRestoreDirectly = false;
634 }
635 }
636
637 if (CanRestoreDirectly) {
638 if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
639 return true;
640 MachineInstrBuilder MIB =
641 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET))
644 // Copy implicit ops and popped registers, if any.
645 for (auto MO: MBBI->operands())
646 if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
647 MIB.add(MO);
648 MIB.addReg(ARM::PC, RegState::Define);
649 // Erase the old instruction (tBX_RET or tPOP).
650 MBB.erase(MBBI);
651 return true;
652 }
653
654 // Look for a temporary register to use.
655 // First, compute the liveness information.
656 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
657 LiveRegUnits UsedRegs(TRI);
658 UsedRegs.addLiveOuts(MBB);
659 // The semantic of pristines changed recently and now,
660 // the callee-saved registers that are touched in the function
661 // are not part of the pristines set anymore.
662 // Add those callee-saved now.
663 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
664 for (unsigned i = 0; CSRegs[i]; ++i)
665 UsedRegs.addReg(CSRegs[i]);
666
667 DebugLoc dl = DebugLoc();
668 if (MBBI != MBB.end()) {
669 dl = MBBI->getDebugLoc();
670 auto InstUpToMBBI = MBB.end();
671 while (InstUpToMBBI != MBBI)
672 // The pre-decrement is on purpose here.
673 // We want to have the liveness right before MBBI.
674 UsedRegs.stepBackward(*--InstUpToMBBI);
675 }
676
677 // Look for a register that can be directly use in the POP.
678 unsigned PopReg = 0;
679 // And some temporary register, just in case.
680 unsigned TemporaryReg = 0;
681 BitVector PopFriendly =
682 TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::tGPRRegClassID));
683
684 assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
685 // Rebuild the GPRs from the high registers because they are removed
686 // form the GPR reg class for thumb1.
687 BitVector GPRsNoLRSP =
688 TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::hGPRRegClassID));
689 GPRsNoLRSP |= PopFriendly;
690 GPRsNoLRSP.reset(ARM::LR);
691 GPRsNoLRSP.reset(ARM::SP);
692 GPRsNoLRSP.reset(ARM::PC);
693 findTemporariesForLR(GPRsNoLRSP, PopFriendly, UsedRegs, PopReg, TemporaryReg,
694 MF.getRegInfo());
695
696 // If we couldn't find a pop-friendly register, try restoring LR before
697 // popping the other callee-saved registers, so we could use one of them as a
698 // temporary.
699 bool UseLDRSP = false;
700 if (!PopReg && MBBI != MBB.begin()) {
701 auto PrevMBBI = MBBI;
702 PrevMBBI--;
703 if (PrevMBBI->getOpcode() == ARM::tPOP) {
704 UsedRegs.stepBackward(*PrevMBBI);
705 findTemporariesForLR(GPRsNoLRSP, PopFriendly, UsedRegs, PopReg,
706 TemporaryReg, MF.getRegInfo());
707 if (PopReg) {
708 MBBI = PrevMBBI;
709 UseLDRSP = true;
710 }
711 }
712 }
713
714 if (!DoIt && !PopReg && !TemporaryReg)
715 return false;
716
717 assert((PopReg || TemporaryReg) && "Cannot get LR");
718
719 if (UseLDRSP) {
720 assert(PopReg && "Do not know how to get LR");
721 // Load the LR via LDR tmp, [SP, #off]
722 BuildMI(MBB, MBBI, dl, TII.get(ARM::tLDRspi))
723 .addReg(PopReg, RegState::Define)
724 .addReg(ARM::SP)
725 .addImm(MBBI->getNumExplicitOperands() - 2)
728 // Move from the temporary register to the LR.
729 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
730 .addReg(ARM::LR, RegState::Define)
731 .addReg(PopReg, RegState::Kill)
734 // Advance past the pop instruction.
735 MBBI++;
736 // Increment the SP.
738 ArgRegsSaveSize + 4, Register(),
740 return true;
741 }
742
743 if (TemporaryReg) {
744 assert(!PopReg && "Unnecessary MOV is about to be inserted");
745 PopReg = PopFriendly.find_first();
746 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
747 .addReg(TemporaryReg, RegState::Define)
748 .addReg(PopReg, RegState::Kill)
751 }
752
753 if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
754 // We couldn't use the direct restoration above, so
755 // perform the opposite conversion: tPOP_RET to tPOP.
756 MachineInstrBuilder MIB =
757 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP))
760 bool Popped = false;
761 for (auto MO: MBBI->operands())
762 if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
763 MO.getReg() != ARM::PC) {
764 MIB.add(MO);
765 if (!MO.isImplicit())
766 Popped = true;
767 }
768 // Is there anything left to pop?
769 if (!Popped)
770 MBB.erase(MIB.getInstr());
771 // Erase the old instruction.
772 MBB.erase(MBBI);
773 MBBI = BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET))
776 }
777
778 assert(PopReg && "Do not know how to get LR");
779 BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP))
781 .addReg(PopReg, RegState::Define)
783
784 emitPrologueEpilogueSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize,
786
787 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
788 .addReg(ARM::LR, RegState::Define)
789 .addReg(PopReg, RegState::Kill)
792
793 if (TemporaryReg)
794 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
795 .addReg(PopReg, RegState::Define)
796 .addReg(TemporaryReg, RegState::Kill)
799
800 return true;
801}
802
803// TODO: Use std::to_array when we switch to C++20.
804constexpr std::array<Register, 5> OrderedLowRegs = {ARM::R4, ARM::R5, ARM::R6,
805 ARM::R7, ARM::LR};
806constexpr std::array<Register, 4> OrderedHighRegs = {ARM::R8, ARM::R9, ARM::R10,
807 ARM::R11};
808constexpr std::array<Register, 9> OrderedCopyRegs = {ARM::R0, ARM::R1, ARM::R2,
809 ARM::R3, ARM::R4, ARM::R5,
810 ARM::R6, ARM::R7, ARM::LR};
811
812static void splitLowAndHighRegs(const std::set<Register> &Regs,
813 std::set<Register> &LowRegs,
814 std::set<Register> &HighRegs) {
815 for (Register Reg : Regs) {
816 if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
817 LowRegs.insert(Reg);
818 } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
819 HighRegs.insert(Reg);
820 } else {
821 llvm_unreachable("callee-saved register of unexpected class");
822 }
823 }
824}
825
826template <typename It>
827It getNextOrderedReg(It OrderedStartIt, It OrderedEndIt,
828 const std::set<Register> &RegSet) {
829 return std::find_if(OrderedStartIt, OrderedEndIt,
830 [&](Register Reg) { return RegSet.count(Reg); });
831}
832
835 const TargetInstrInfo &TII,
836 const std::set<Register> &RegsToSave,
837 const std::set<Register> &CopyRegs,
838 bool &UsedLRAsTemp) {
839 MachineFunction &MF = *MBB.getParent();
840 const MachineRegisterInfo &MRI = MF.getRegInfo();
841 DebugLoc DL;
842
843 std::set<Register> LowRegs, HighRegs;
844 splitLowAndHighRegs(RegsToSave, LowRegs, HighRegs);
845
846 // Push low regs first
847 if (!LowRegs.empty()) {
849 BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
850 for (unsigned Reg : OrderedLowRegs) {
851 if (LowRegs.count(Reg)) {
852 bool isKill = !MRI.isLiveIn(Reg);
853 if (isKill && !MRI.isReserved(Reg))
854 MBB.addLiveIn(Reg);
855
856 MIB.addReg(Reg, getKillRegState(isKill));
857 }
858 }
860 }
861
862 // Now push the high registers
863 // There are no store instructions that can access high registers directly,
864 // so we have to move them to low registers, and push them.
865 // This might take multiple pushes, as it is possible for there to
866 // be fewer low registers available than high registers which need saving.
867
868 // Find the first register to save.
869 // Registers must be processed in reverse order so that in case we need to use
870 // multiple PUSH instructions, the order of the registers on the stack still
871 // matches the unwind info. They need to be switched back to ascending order
872 // before adding to the PUSH instruction.
873 auto HiRegToSave = getNextOrderedReg(OrderedHighRegs.rbegin(),
874 OrderedHighRegs.rend(),
875 HighRegs);
876
877 while (HiRegToSave != OrderedHighRegs.rend()) {
878 // Find the first low register to use.
879 auto CopyRegIt = getNextOrderedReg(OrderedCopyRegs.rbegin(),
880 OrderedCopyRegs.rend(),
881 CopyRegs);
882
883 // Create the PUSH, but don't insert it yet (the MOVs need to come first).
884 MachineInstrBuilder PushMIB = BuildMI(MF, DL, TII.get(ARM::tPUSH))
887
888 SmallVector<unsigned, 4> RegsToPush;
889 while (HiRegToSave != OrderedHighRegs.rend() &&
890 CopyRegIt != OrderedCopyRegs.rend()) {
891 if (HighRegs.count(*HiRegToSave)) {
892 bool isKill = !MRI.isLiveIn(*HiRegToSave);
893 if (isKill && !MRI.isReserved(*HiRegToSave))
894 MBB.addLiveIn(*HiRegToSave);
895 if (*CopyRegIt == ARM::LR)
896 UsedLRAsTemp = true;
897
898 // Emit a MOV from the high reg to the low reg.
899 BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
900 .addReg(*CopyRegIt, RegState::Define)
901 .addReg(*HiRegToSave, getKillRegState(isKill))
904
905 // Record the register that must be added to the PUSH.
906 RegsToPush.push_back(*CopyRegIt);
907
908 CopyRegIt = getNextOrderedReg(std::next(CopyRegIt),
909 OrderedCopyRegs.rend(),
910 CopyRegs);
911 HiRegToSave = getNextOrderedReg(std::next(HiRegToSave),
912 OrderedHighRegs.rend(),
913 HighRegs);
914 }
915 }
916
917 // Add the low registers to the PUSH, in ascending order.
918 for (unsigned Reg : llvm::reverse(RegsToPush))
919 PushMIB.addReg(Reg, RegState::Kill);
920
921 // Insert the PUSH instruction after the MOVs.
922 MBB.insert(MI, PushMIB);
923 }
924}
925
928 const TargetInstrInfo &TII,
929 const std::set<Register> &RegsToRestore,
930 const std::set<Register> &AvailableCopyRegs,
931 bool IsVarArg, bool HasV5Ops) {
932 if (RegsToRestore.empty())
933 return;
934
935 MachineFunction &MF = *MBB.getParent();
937 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
938
939 std::set<Register> LowRegs, HighRegs;
940 splitLowAndHighRegs(RegsToRestore, LowRegs, HighRegs);
941
942 // Pop the high registers first
943 // There are no store instructions that can access high registers directly,
944 // so we have to pop into low registers and them move to the high registers.
945 // This might take multiple pops, as it is possible for there to
946 // be fewer low registers available than high registers which need restoring.
947
948 // Find the first register to restore.
949 auto HiRegToRestore = getNextOrderedReg(OrderedHighRegs.begin(),
950 OrderedHighRegs.end(),
951 HighRegs);
952
953 std::set<Register> CopyRegs = AvailableCopyRegs;
954 Register LowScratchReg;
955 if (!HighRegs.empty() && CopyRegs.empty()) {
956 // No copy regs are available to pop high regs. Let's make use of a return
957 // register and the scratch register (IP/R12) to copy things around.
958 LowScratchReg = ARM::R0;
959 BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
960 .addReg(ARM::R12, RegState::Define)
961 .addReg(LowScratchReg, RegState::Kill)
964 CopyRegs.insert(LowScratchReg);
965 }
966
967 while (HiRegToRestore != OrderedHighRegs.end()) {
968 assert(!CopyRegs.empty());
969 // Find the first low register to use.
970 auto CopyReg = getNextOrderedReg(OrderedCopyRegs.begin(),
971 OrderedCopyRegs.end(),
972 CopyRegs);
973
974 // Create the POP instruction.
975 MachineInstrBuilder PopMIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPOP))
978
979 while (HiRegToRestore != OrderedHighRegs.end() &&
980 CopyReg != OrderedCopyRegs.end()) {
981 // Add the low register to the POP.
982 PopMIB.addReg(*CopyReg, RegState::Define);
983
984 // Create the MOV from low to high register.
985 BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
986 .addReg(*HiRegToRestore, RegState::Define)
987 .addReg(*CopyReg, RegState::Kill)
990
991 CopyReg = getNextOrderedReg(std::next(CopyReg),
992 OrderedCopyRegs.end(),
993 CopyRegs);
994 HiRegToRestore = getNextOrderedReg(std::next(HiRegToRestore),
995 OrderedHighRegs.end(),
996 HighRegs);
997 }
998 }
999
1000 // Restore low register used as scratch if necessary
1001 if (LowScratchReg.isValid()) {
1002 BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
1003 .addReg(LowScratchReg, RegState::Define)
1004 .addReg(ARM::R12, RegState::Kill)
1007 }
1008
1009 // Now pop the low registers
1010 if (!LowRegs.empty()) {
1011 MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP))
1014
1015 bool NeedsPop = false;
1016 for (Register Reg : OrderedLowRegs) {
1017 if (!LowRegs.count(Reg))
1018 continue;
1019
1020 if (Reg == ARM::LR) {
1021 if (!MBB.succ_empty() || MI->getOpcode() == ARM::TCRETURNdi ||
1022 MI->getOpcode() == ARM::TCRETURNri ||
1023 MI->getOpcode() == ARM::TCRETURNrinotr12)
1024 // LR may only be popped into PC, as part of return sequence.
1025 // If this isn't the return sequence, we'll need emitPopSpecialFixUp
1026 // to restore LR the hard way.
1027 // FIXME: if we don't pass any stack arguments it would be actually
1028 // advantageous *and* correct to do the conversion to an ordinary call
1029 // instruction here.
1030 continue;
1031 // Special epilogue for vararg functions. See emitEpilogue
1032 if (IsVarArg)
1033 continue;
1034 // ARMv4T requires BX, see emitEpilogue
1035 if (!HasV5Ops)
1036 continue;
1037
1038 // CMSE entry functions must return via BXNS, see emitEpilogue.
1039 if (AFI->isCmseNSEntryFunction())
1040 continue;
1041
1042 // Pop LR into PC.
1043 Reg = ARM::PC;
1044 (*MIB).setDesc(TII.get(ARM::tPOP_RET));
1045 if (MI != MBB.end())
1046 MIB.copyImplicitOps(*MI);
1047 MI = MBB.erase(MI);
1048 }
1049 MIB.addReg(Reg, getDefRegState(true));
1050 NeedsPop = true;
1051 }
1052
1053 // It's illegal to emit pop instruction without operands.
1054 if (NeedsPop)
1055 MBB.insert(MI, &*MIB);
1056 else
1057 MF.deleteMachineInstr(MIB);
1058 }
1059}
1060
1064 if (CSI.empty())
1065 return false;
1066
1067 const TargetInstrInfo &TII = *STI.getInstrInfo();
1068 MachineFunction &MF = *MBB.getParent();
1069 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1070 MF.getSubtarget().getRegisterInfo());
1071 Register FPReg = RegInfo->getFrameRegister(MF);
1072
1073 // In case FP is a high reg, we need a separate push sequence to generate
1074 // a correct Frame Record
1075 bool NeedsFrameRecordPush = hasFP(MF) && ARM::hGPRRegClass.contains(FPReg);
1076 bool LRLiveIn = MF.getRegInfo().isLiveIn(ARM::LR);
1077 bool UsedLRAsTemp = false;
1078
1079 std::set<Register> FrameRecord;
1080 std::set<Register> SpilledGPRs;
1081 for (const CalleeSavedInfo &I : CSI) {
1082 MCRegister Reg = I.getReg();
1083 if (NeedsFrameRecordPush && (Reg == FPReg.asMCReg() || Reg == ARM::LR))
1084 FrameRecord.insert(Reg);
1085 else
1086 SpilledGPRs.insert(Reg);
1087 }
1088
1089 // Determine intermediate registers which can be used for pushing the frame
1090 // record:
1091 // - Unused argument registers
1092 // - LR: This is possible because the first PUSH will save it on the stack,
1093 // so it is free to be used as a temporary for the second. However, it
1094 // is possible for LR to be live-in to the function, in which case we
1095 // will need to restore it later in the prologue, so we only use this
1096 // if there are no free argument registers.
1097 std::set<Register> FrameRecordCopyRegs;
1098 for (unsigned ArgReg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3})
1099 if (!MF.getRegInfo().isLiveIn(ArgReg))
1100 FrameRecordCopyRegs.insert(ArgReg);
1101 if (FrameRecordCopyRegs.empty())
1102 FrameRecordCopyRegs.insert(ARM::LR);
1103
1104 pushRegsToStack(MBB, MI, TII, FrameRecord, FrameRecordCopyRegs, UsedLRAsTemp);
1105
1106 // Determine intermediate registers which can be used for pushing high regs:
1107 // - Spilled low regs
1108 // - Unused argument registers
1109 std::set<Register> CopyRegs;
1110 for (Register Reg : SpilledGPRs)
1111 if ((ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) &&
1112 !MF.getRegInfo().isLiveIn(Reg) && !(hasFP(MF) && Reg == FPReg))
1113 CopyRegs.insert(Reg);
1114 for (unsigned ArgReg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3})
1115 if (!MF.getRegInfo().isLiveIn(ArgReg))
1116 CopyRegs.insert(ArgReg);
1117
1118 pushRegsToStack(MBB, MI, TII, SpilledGPRs, CopyRegs, UsedLRAsTemp);
1119
1120 // If the push sequence used LR as a temporary, and LR is live-in (for
1121 // example because it is used by the llvm.returnaddress intrinsic), then we
1122 // need to reload it from the stack. Thumb1 does not have a load instruction
1123 // which can use LR, so we need to load into a temporary low register and
1124 // copy to LR.
1125 if (LRLiveIn && UsedLRAsTemp) {
1126 auto CopyRegIt = getNextOrderedReg(OrderedCopyRegs.rbegin(),
1127 OrderedCopyRegs.rend(), CopyRegs);
1128 assert(CopyRegIt != OrderedCopyRegs.rend());
1129 unsigned NumRegsPushed = FrameRecord.size() + SpilledGPRs.size();
1130 LLVM_DEBUG(
1131 dbgs() << "LR is live-in but clobbered in prologue, restoring via "
1132 << RegInfo->getName(*CopyRegIt) << "\n");
1133
1134 BuildMI(MBB, MI, DebugLoc(), TII.get(ARM::tLDRspi), *CopyRegIt)
1135 .addReg(ARM::SP)
1136 .addImm(NumRegsPushed - 1)
1139
1140 BuildMI(MBB, MI, DebugLoc(), TII.get(ARM::tMOVr), ARM::LR)
1141 .addReg(*CopyRegIt)
1144 }
1145
1146 return true;
1147}
1148
1152 if (CSI.empty())
1153 return false;
1154
1155 MachineFunction &MF = *MBB.getParent();
1157 const TargetInstrInfo &TII = *STI.getInstrInfo();
1158 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1159 MF.getSubtarget().getRegisterInfo());
1160 bool IsVarArg = AFI->getArgRegsSaveSize() > 0;
1161 Register FPReg = RegInfo->getFrameRegister(MF);
1162
1163 // In case FP is a high reg, we need a separate pop sequence to generate
1164 // a correct Frame Record
1165 bool NeedsFrameRecordPop = hasFP(MF) && ARM::hGPRRegClass.contains(FPReg);
1166
1167 std::set<Register> FrameRecord;
1168 std::set<Register> SpilledGPRs;
1169 for (CalleeSavedInfo &I : CSI) {
1170 MCRegister Reg = I.getReg();
1171 if (NeedsFrameRecordPop && (Reg == FPReg.asMCReg() || Reg == ARM::LR))
1172 FrameRecord.insert(Reg);
1173 else
1174 SpilledGPRs.insert(Reg);
1175
1176 if (Reg == ARM::LR)
1177 I.setRestored(false);
1178 }
1179
1180 // Determine intermediate registers which can be used for popping high regs:
1181 // - Spilled low regs
1182 // - Unused return registers
1183 std::set<Register> CopyRegs;
1184 std::set<Register> UnusedReturnRegs;
1185 for (Register Reg : SpilledGPRs)
1186 if ((ARM::tGPRRegClass.contains(Reg)) && !(hasFP(MF) && Reg == FPReg))
1187 CopyRegs.insert(Reg);
1188 auto Terminator = MBB.getFirstTerminator();
1189 if (Terminator != MBB.end() && Terminator->getOpcode() == ARM::tBX_RET) {
1190 UnusedReturnRegs.insert(ARM::R0);
1191 UnusedReturnRegs.insert(ARM::R1);
1192 UnusedReturnRegs.insert(ARM::R2);
1193 UnusedReturnRegs.insert(ARM::R3);
1194 for (auto Op : Terminator->implicit_operands()) {
1195 if (Op.isReg())
1196 UnusedReturnRegs.erase(Op.getReg());
1197 }
1198 }
1199 CopyRegs.insert(UnusedReturnRegs.begin(), UnusedReturnRegs.end());
1200
1201 // First pop regular spilled regs.
1202 popRegsFromStack(MBB, MI, TII, SpilledGPRs, CopyRegs, IsVarArg,
1203 STI.hasV5TOps());
1204
1205 // LR may only be popped into pc, as part of a return sequence.
1206 // Check that no other pop instructions are inserted after that.
1207 assert((!SpilledGPRs.count(ARM::LR) || FrameRecord.empty()) &&
1208 "Can't insert pop after return sequence");
1209
1210 // Now pop Frame Record regs.
1211 // Only unused return registers can be used as copy regs at this point.
1212 popRegsFromStack(MBB, MI, TII, FrameRecord, UnusedReturnRegs, IsVarArg,
1213 STI.hasV5TOps());
1214
1215 return true;
1216}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file implements the BitVector class.
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr MCPhysReg FPReg
MachineRegisterInfo & MRI
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void emitCallSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const TargetInstrInfo &TII, const DebugLoc &dl, const ThumbRegisterInfo &MRI, int NumBytes, unsigned MIFlags=MachineInstr::NoFlags)
static void emitPrologueEpilogueSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const TargetInstrInfo &TII, const DebugLoc &dl, const ThumbRegisterInfo &MRI, int NumBytes, Register ScratchReg, unsigned MIFlags)
static void pushRegsToStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const TargetInstrInfo &TII, const std::set< Register > &RegsToSave, const std::set< Register > &CopyRegs, bool &UsedLRAsTemp)
static void splitLowAndHighRegs(const std::set< Register > &Regs, std::set< Register > &LowRegs, std::set< Register > &HighRegs)
constexpr std::array< Register, 4 > OrderedHighRegs
It getNextOrderedReg(It OrderedStartIt, It OrderedEndIt, const std::set< Register > &RegSet)
constexpr std::array< Register, 9 > OrderedCopyRegs
constexpr std::array< Register, 5 > OrderedLowRegs
static void popRegsFromStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MI, const TargetInstrInfo &TII, const std::set< Register > &RegsToRestore, const std::set< Register > &AvailableCopyRegs, bool IsVarArg, bool HasV5Ops)
static void findTemporariesForLR(const BitVector &GPRsNoLRSP, const BitVector &PopFriendly, const LiveRegUnits &UsedRegs, unsigned &PopReg, unsigned &TmpReg, MachineRegisterInfo &MRI)
static const unsigned FramePtr
ARMFrameLowering(const ARMSubtarget &sti)
const ARMSubtarget & STI
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
unsigned getGPRCalleeSavedArea1Size() const
unsigned getDPRCalleeSavedArea1Size() const
void setDPRCalleeSavedArea1Offset(unsigned o)
void setGPRCalleeSavedArea2Size(unsigned s)
void setFramePtrSpillOffset(unsigned o)
unsigned getGPRCalleeSavedArea2Size() const
void setGPRCalleeSavedArea1Size(unsigned s)
unsigned getFramePtrSpillOffset() const
void setFrameRecordSavedAreaSize(unsigned s)
unsigned getArgRegsSaveSize() const
void setGPRCalleeSavedArea2Offset(unsigned o)
unsigned getFrameRecordSavedAreaSize() const
void setGPRCalleeSavedArea1Offset(unsigned o)
void setDPRCalleeSavedArea1Size(unsigned s)
@ SplitR7
R7 and LR must be adjacent, because R7 is the frame pointer, and must point to a frame record consist...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
bool any() const
Returns true if any bit is set.
Definition BitVector.h:190
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
Helper class for creating CFI instructions and inserting them into MIR.
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildDefCFARegister(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
void setInsertPoint(MachineBasicBlock::iterator IP)
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Align getMaxAlign() const
Return alignment of this function's frame.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool isLiveIn(Register Reg) const
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
Thumb1FrameLowering(const ARMSubtarget &sti)
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
@ Done
Definition Threading.h:60
static bool isARMLowRegister(MCRegister Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, MachineFunction &MF, MachineInstr *MI, unsigned NumBytes)
Tries to add registers to the reglist of a given base-updating push/pop instruction to adjust the sta...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr RegState getDefRegState(bool B)
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
void emitThumbRegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, Register DestReg, Register BaseReg, int NumBytes, const TargetInstrInfo &TII, const ARMBaseRegisterInfo &MRI, unsigned MIFlags=0)
emitThumbRegPlusImmediate - Emits a series of instructions to materialize a destreg = basereg + immed...
DWARFExpression::Operation Op
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202