Deleted Added
full compact
1//===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the ARM implementation of TargetFrameLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMFrameLowering.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMConstantPoolValue.h"
18#include "ARMMachineFunctionInfo.h"
19#include "MCTargetDesc/ARMAddressingModes.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/RegisterScavenging.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Function.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Target/TargetOptions.h"
31
32using namespace llvm;
33
34static cl::opt<bool>
35SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36 cl::desc("Align ARM NEON spills in prolog and epilog"));
37
38static MachineBasicBlock::iterator
39skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
41
42ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
44 STI(sti) {}
45
46/// hasFP - Return true if the specified function should have a dedicated frame
47/// pointer register. This is true if the function has variable sized allocas
48/// or if frame pointer elimination is disabled.
49bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
50 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
51
52 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
54 return true;
55
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
58 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
59 MFI->hasCalls()) ||
60 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
63}
64
65/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66/// not required, we reserve argument space for call sites in the function
67/// immediately on entry to the current function. This eliminates the need for
68/// add/sub sp brackets around call sites. Returns true if the call frame is
69/// included as part of the stack frame.
70bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
71 const MachineFrameInfo *FFI = MF.getFrameInfo();
72 unsigned CFSize = FFI->getMaxCallFrameSize();
73 // It's not always a good idea to include the call frame as part of the
74 // stack frame. ARM (especially Thumb) has small immediate offset to
75 // address the stack frame. So a large call frame can cause poor codegen
76 // and may even makes it impossible to scavenge a register.
77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
78 return false;
79
80 return !MF.getFrameInfo()->hasVarSizedObjects();
81}
82
83/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84/// call frame pseudos can be simplified. Unlike most targets, having a FP
85/// is not sufficient here since we still may reference some objects via SP
86/// even when FP is available in Thumb2 mode.
87bool
88ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
89 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
90}
91
92static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
94 const MCPhysReg *CSRegs) {
95 // Integer spill area is handled with "pop".
96 if (isPopOpcode(MI->getOpcode())) {
97 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
101 return false;
102 return true;
103 }
104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
109 return true;
110
111 return false;
112}
113
114static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
121 if (isARM)
122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123 Pred, PredReg, TII, MIFlags);
124 else
125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126 Pred, PredReg, TII, MIFlags);
127}
128
129static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
137}
138
139static int sizeOfSPAdjustment(const MachineInstr *MI) {
140 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
141 int count = 0;
142 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
143 // pred) so the list starts at 4.
144 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
145 count += 8;
146 return count;
147}
148
149static bool WindowsRequiresStackProbe(const MachineFunction &MF,
150 size_t StackSizeInBytes) {
151 const MachineFrameInfo *MFI = MF.getFrameInfo();
152 if (MFI->getStackProtectorIndex() > 0)
153 return StackSizeInBytes >= 4080;
154 return StackSizeInBytes >= 4096;
155}
156
157void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
158 MachineBasicBlock &MBB = MF.front();
159 MachineBasicBlock::iterator MBBI = MBB.begin();
160 MachineFrameInfo *MFI = MF.getFrameInfo();
161 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
162 MachineModuleInfo &MMI = MF.getMMI();
163 MCContext &Context = MMI.getContext();
164 const TargetMachine &TM = MF.getTarget();
165 const MCRegisterInfo *MRI = Context.getRegisterInfo();
166 const ARMBaseRegisterInfo *RegInfo =
167 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
168 const ARMBaseInstrInfo &TII =
169 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
170 assert(!AFI->isThumb1OnlyFunction() &&
171 "This emitPrologue does not support Thumb1!");
172 bool isARM = !AFI->isThumbFunction();
173 unsigned Align = TM.getFrameLowering()->getStackAlignment();
174 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
175 unsigned NumBytes = MFI->getStackSize();
176 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
177 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
178 unsigned FramePtr = RegInfo->getFrameRegister(MF);
179 int CFAOffset = 0;
180
181 // Determine the sizes of each callee-save spill areas and record which frame
182 // belongs to which callee-save spill areas.
183 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
184 int FramePtrSpillFI = 0;
185 int D8SpillFI = 0;
186
187 // All calls are tail calls in GHC calling conv, and functions have no
188 // prologue/epilogue.
189 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
190 return;
191
192 // Allocate the vararg register save area.
193 if (ArgRegsSaveSize) {
194 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
195 MachineInstr::FrameSetup);
196 CFAOffset -= ArgRegsSaveSize;
197 unsigned CFIIndex = MMI.addFrameInst(
198 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
199 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
200 .addCFIIndex(CFIIndex);
201 }
202
203 if (!AFI->hasStackFrame() &&
204 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
205 if (NumBytes - ArgRegsSaveSize != 0) {
206 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
207 MachineInstr::FrameSetup);
208 CFAOffset -= NumBytes - ArgRegsSaveSize;
209 unsigned CFIIndex = MMI.addFrameInst(
210 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
211 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
212 .addCFIIndex(CFIIndex);
213 }
214 return;
215 }
216
217 // Determine spill area sizes.
218 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
219 unsigned Reg = CSI[i].getReg();
220 int FI = CSI[i].getFrameIdx();
221 switch (Reg) {
222 case ARM::R8:
223 case ARM::R9:
224 case ARM::R10:
225 case ARM::R11:
226 case ARM::R12:
227 if (STI.isTargetDarwin()) {
228 GPRCS2Size += 4;
229 break;
230 }
231 // fallthrough
232 case ARM::R0:
233 case ARM::R1:
234 case ARM::R2:
235 case ARM::R3:
236 case ARM::R4:
237 case ARM::R5:
238 case ARM::R6:
239 case ARM::R7:
240 case ARM::LR:
241 if (Reg == FramePtr)
242 FramePtrSpillFI = FI;
243 GPRCS1Size += 4;
244 break;
245 default:
246 // This is a DPR. Exclude the aligned DPRCS2 spills.
247 if (Reg == ARM::D8)
248 D8SpillFI = FI;
249 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
250 DPRCSSize += 8;
251 }
252 }
253
254 // Move past area 1.
255 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
256 DPRCSPush;
257 if (GPRCS1Size > 0)
258 GPRCS1Push = LastPush = MBBI++;
259
260 // Determine starting offsets of spill areas.
261 bool HasFP = hasFP(MF);
262 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
263 + GPRCS2Size + DPRCSSize);
264 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
265 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
266 int FramePtrOffsetInPush = 0;
267 if (HasFP) {
268 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
269 + GPRCS1Size + ArgRegsSaveSize;
270 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
271 NumBytes);
272 }
273 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
274 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
275 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
276
277 // Move past area 2.
278 if (GPRCS2Size > 0)
279 GPRCS2Push = LastPush = MBBI++;
280
281 // Move past area 3.
282 if (DPRCSSize > 0) {
283 DPRCSPush = MBBI;
284 // Since vpush register list cannot have gaps, there may be multiple vpush
285 // instructions in the prologue.
286 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
287 LastPush = MBBI++;
288 }
289
290 // Move past the aligned DPRCS2 area.
291 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
292 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
293 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
294 // leaves the stack pointer pointing to the DPRCS2 area.
295 //
296 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
297 NumBytes += MFI->getObjectOffset(D8SpillFI);
298 } else
299 NumBytes = DPRCSOffset;
300
301 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
302 uint32_t NumWords = NumBytes >> 2;
303
304 if (NumWords < 65536)
305 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
306 .addImm(NumWords)
307 .setMIFlags(MachineInstr::FrameSetup));
308 else
309 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
310 .addImm(NumWords)
311 .setMIFlags(MachineInstr::FrameSetup);
312
313 switch (TM.getCodeModel()) {
314 case CodeModel::Small:
315 case CodeModel::Medium:
316 case CodeModel::Default:
317 case CodeModel::Kernel:
318 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
319 .addImm((unsigned)ARMCC::AL).addReg(0)
320 .addExternalSymbol("__chkstk")
321 .addReg(ARM::R4, RegState::Implicit)
322 .setMIFlags(MachineInstr::FrameSetup);
323 break;
324 case CodeModel::Large:
325 case CodeModel::JITDefault:
326 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
327 .addExternalSymbol("__chkstk")
328 .setMIFlags(MachineInstr::FrameSetup);
329
330 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
331 .addImm((unsigned)ARMCC::AL).addReg(0)
332 .addReg(ARM::R12, RegState::Kill)
333 .addReg(ARM::R4, RegState::Implicit)
334 .setMIFlags(MachineInstr::FrameSetup);
335 break;
336 }
337
338 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
339 ARM::SP)
340 .addReg(ARM::SP, RegState::Define)
341 .addReg(ARM::R4, RegState::Kill)
342 .setMIFlags(MachineInstr::FrameSetup)));
343 NumBytes = 0;
344 }
345
346 unsigned adjustedGPRCS1Size = GPRCS1Size;
347 if (NumBytes) {
348 // Adjust SP after all the callee-save spills.
349 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
350 if (LastPush == GPRCS1Push) {
351 FramePtrOffsetInPush += NumBytes;
352 adjustedGPRCS1Size += NumBytes;
353 NumBytes = 0;
354 }
355 } else
356 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
357 MachineInstr::FrameSetup);
358
359 if (HasFP && isARM)
360 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
361 // Note it's not safe to do this in Thumb2 mode because it would have
362 // taken two instructions:
363 // mov sp, r7
364 // sub sp, #24
365 // If an interrupt is taken between the two instructions, then sp is in
366 // an inconsistent state (pointing to the middle of callee-saved area).
367 // The interrupt handler can end up clobbering the registers.
368 AFI->setShouldRestoreSPFromFP(true);
369 }
370
371 if (adjustedGPRCS1Size > 0) {
372 CFAOffset -= adjustedGPRCS1Size;
373 unsigned CFIIndex = MMI.addFrameInst(
374 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
375 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
376 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
377 .addCFIIndex(CFIIndex);
378 for (const auto &Entry : CSI) {
379 unsigned Reg = Entry.getReg();
380 int FI = Entry.getFrameIdx();
381 switch (Reg) {
382 case ARM::R8:
383 case ARM::R9:
384 case ARM::R10:
385 case ARM::R11:
386 case ARM::R12:
387 if (STI.isTargetDarwin())
388 break;
389 // fallthrough
390 case ARM::R0:
391 case ARM::R1:
392 case ARM::R2:
393 case ARM::R3:
394 case ARM::R4:
395 case ARM::R5:
396 case ARM::R6:
397 case ARM::R7:
398 case ARM::LR:
399 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
400 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
401 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
402 .addCFIIndex(CFIIndex);
403 break;
404 }
405 }
406 }
407
408 // Set FP to point to the stack slot that contains the previous FP.
409 // For iOS, FP is R7, which has now been stored in spill area 1.
410 // Otherwise, if this is not iOS, all the callee-saved registers go
411 // into spill area 1, including the FP in R11. In either case, it
412 // is in area one and the adjustment needs to take place just after
413 // that push.
414 if (HasFP) {
415 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
416 FramePtr, ARM::SP, FramePtrOffsetInPush,
417 MachineInstr::FrameSetup);
418 if (FramePtrOffsetInPush) {
419 CFAOffset += FramePtrOffsetInPush;
420 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
421 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
422 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
423 .addCFIIndex(CFIIndex);
424
425 } else {
426 unsigned CFIIndex =
427 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
428 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
429 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
430 .addCFIIndex(CFIIndex);
431 }
432 }
433
434 if (GPRCS2Size > 0) {
435 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
436 if (!HasFP) {
437 CFAOffset -= GPRCS2Size;
438 unsigned CFIIndex = MMI.addFrameInst(
439 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
440 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
441 .addCFIIndex(CFIIndex);
442 }
443 for (const auto &Entry : CSI) {
444 unsigned Reg = Entry.getReg();
445 int FI = Entry.getFrameIdx();
446 switch (Reg) {
447 case ARM::R8:
448 case ARM::R9:
449 case ARM::R10:
450 case ARM::R11:
451 case ARM::R12:
452 if (STI.isTargetDarwin()) {
453 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
454 unsigned Offset = MFI->getObjectOffset(FI);
455 unsigned CFIIndex = MMI.addFrameInst(
456 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
457 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
458 .addCFIIndex(CFIIndex);
459 }
460 break;
461 }
462 }
463 }
464
465 if (DPRCSSize > 0) {
466 // Since vpush register list cannot have gaps, there may be multiple vpush
467 // instructions in the prologue.
468 do {
469 MachineBasicBlock::iterator Push = DPRCSPush++;
470 if (!HasFP) {
471 CFAOffset -= sizeOfSPAdjustment(Push);
472 unsigned CFIIndex = MMI.addFrameInst(
473 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
474 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
475 .addCFIIndex(CFIIndex);
476 }
477 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
478
479 for (const auto &Entry : CSI) {
480 unsigned Reg = Entry.getReg();
481 int FI = Entry.getFrameIdx();
482 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
483 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
484 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
485 unsigned Offset = MFI->getObjectOffset(FI);
486 unsigned CFIIndex = MMI.addFrameInst(
487 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
488 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
489 .addCFIIndex(CFIIndex);
490 }
491 }
492 }
493
494 if (NumBytes) {
495 if (!HasFP) {
496 CFAOffset -= NumBytes;
497 unsigned CFIIndex = MMI.addFrameInst(
498 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
499 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
500 .addCFIIndex(CFIIndex);
501 }
502 }
503
504 if (STI.isTargetELF() && hasFP(MF))
505 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
506 AFI->getFramePtrSpillOffset());
507
508 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
509 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
510 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
511
512 // If we need dynamic stack realignment, do it here. Be paranoid and make
513 // sure if we also have VLAs, we have a base pointer for frame access.
514 // If aligned NEON registers were spilled, the stack has already been
515 // realigned.
516 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
517 unsigned MaxAlign = MFI->getMaxAlignment();
518 assert (!AFI->isThumb1OnlyFunction());
519 if (!AFI->isThumbFunction()) {
520 // Emit bic sp, sp, MaxAlign
521 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
522 TII.get(ARM::BICri), ARM::SP)
523 .addReg(ARM::SP, RegState::Kill)
524 .addImm(MaxAlign-1)));
525 } else {
526 // We cannot use sp as source/dest register here, thus we're emitting the
527 // following sequence:
528 // mov r4, sp
529 // bic r4, r4, MaxAlign
530 // mov sp, r4
531 // FIXME: It will be better just to find spare register here.
532 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
533 .addReg(ARM::SP, RegState::Kill));
534 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
535 TII.get(ARM::t2BICri), ARM::R4)
536 .addReg(ARM::R4, RegState::Kill)
537 .addImm(MaxAlign-1)));
538 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
539 .addReg(ARM::R4, RegState::Kill));
540 }
541
542 AFI->setShouldRestoreSPFromFP(true);
543 }
544
545 // If we need a base pointer, set it up here. It's whatever the value
546 // of the stack pointer is at this point. Any variable size objects
547 // will be allocated after this, so we can still use the base pointer
548 // to reference locals.
549 // FIXME: Clarify FrameSetup flags here.
550 if (RegInfo->hasBasePointer(MF)) {
551 if (isARM)
552 BuildMI(MBB, MBBI, dl,
553 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
554 .addReg(ARM::SP)
555 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
556 else
557 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
558 RegInfo->getBaseRegister())
559 .addReg(ARM::SP));
560 }
561
562 // If the frame has variable sized objects then the epilogue must restore
563 // the sp from fp. We can assume there's an FP here since hasFP already
564 // checks for hasVarSizedObjects.
565 if (MFI->hasVarSizedObjects())
566 AFI->setShouldRestoreSPFromFP(true);
567}
568
569// Resolve TCReturn pseudo-instruction
570void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
571 MachineBasicBlock &MBB) const {
572 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
573 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
574 unsigned RetOpcode = MBBI->getOpcode();
575 DebugLoc dl = MBBI->getDebugLoc();
576 const ARMBaseInstrInfo &TII =
577 *MF.getTarget().getSubtarget<ARMSubtarget>().getInstrInfo();
578
579 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
580 return;
581
582 // Tail call return: adjust the stack pointer and jump to callee.
583 MBBI = MBB.getLastNonDebugInstr();
584 MachineOperand &JumpTarget = MBBI->getOperand(0);
585
586 // Jump to label or value in register.
587 if (RetOpcode == ARM::TCRETURNdi) {
588 unsigned TCOpcode = STI.isThumb() ?
589 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
590 ARM::TAILJMPd;
591 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
592 if (JumpTarget.isGlobal())
593 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
594 JumpTarget.getTargetFlags());
595 else {
596 assert(JumpTarget.isSymbol());
597 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
598 JumpTarget.getTargetFlags());
599 }
600
601 // Add the default predicate in Thumb mode.
602 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
603 } else if (RetOpcode == ARM::TCRETURNri) {
604 BuildMI(MBB, MBBI, dl,
605 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
606 addReg(JumpTarget.getReg(), RegState::Kill);
607 }
608
609 MachineInstr *NewMI = std::prev(MBBI);
610 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
611 NewMI->addOperand(MBBI->getOperand(i));
612
613 // Delete the pseudo instruction TCRETURN.
614 MBB.erase(MBBI);
615 MBBI = NewMI;
616}
617
618void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
619 MachineBasicBlock &MBB) const {
620 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
621 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
573 unsigned RetOpcode = MBBI->getOpcode();
622 DebugLoc dl = MBBI->getDebugLoc();
623 MachineFrameInfo *MFI = MF.getFrameInfo();
624 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
625 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
626 const ARMBaseInstrInfo &TII =
627 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
628 assert(!AFI->isThumb1OnlyFunction() &&
629 "This emitEpilogue does not support Thumb1!");
630 bool isARM = !AFI->isThumbFunction();
631
632 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
633 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
634 int NumBytes = (int)MFI->getStackSize();
635 unsigned FramePtr = RegInfo->getFrameRegister(MF);
636
637 // All calls are tail calls in GHC calling conv, and functions have no
638 // prologue/epilogue.
591 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
639 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
640 fixTCReturn(MF, MBB);
641 return;
642 }
643
644 if (!AFI->hasStackFrame()) {
645 if (NumBytes - ArgRegsSaveSize != 0)
646 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
647 } else {
648 // Unwind MBBI to point to first LDR / VLDRD.
649 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
650 if (MBBI != MBB.begin()) {
651 do {
652 --MBBI;
653 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
654 if (!isCSRestore(MBBI, TII, CSRegs))
655 ++MBBI;
656 }
657
658 // Move SP to start of FP callee save spill area.
659 NumBytes -= (ArgRegsSaveSize +
660 AFI->getGPRCalleeSavedArea1Size() +
661 AFI->getGPRCalleeSavedArea2Size() +
662 AFI->getDPRCalleeSavedAreaSize());
663
664 // Reset SP based on frame pointer only if the stack frame extends beyond
665 // frame pointer stack slot or target is ELF and the function has FP.
666 if (AFI->shouldRestoreSPFromFP()) {
667 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
668 if (NumBytes) {
669 if (isARM)
670 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
671 ARMCC::AL, 0, TII);
672 else {
673 // It's not possible to restore SP from FP in a single instruction.
674 // For iOS, this looks like:
675 // mov sp, r7
676 // sub sp, #24
677 // This is bad, if an interrupt is taken after the mov, sp is in an
678 // inconsistent state.
679 // Use the first callee-saved register as a scratch register.
680 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
681 "No scratch register to restore SP from FP!");
682 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
683 ARMCC::AL, 0, TII);
684 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
685 ARM::SP)
686 .addReg(ARM::R4));
687 }
688 } else {
689 // Thumb2 or ARM.
690 if (isARM)
691 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
692 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
693 else
694 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
695 ARM::SP)
696 .addReg(FramePtr));
697 }
698 } else if (NumBytes &&
699 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
700 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
701
702 // Increment past our save areas.
703 if (AFI->getDPRCalleeSavedAreaSize()) {
704 MBBI++;
705 // Since vpop register list cannot have gaps, there may be multiple vpop
706 // instructions in the epilogue.
707 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
708 MBBI++;
709 }
710 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
711 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
712 }
713
664 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
665 // Tail call return: adjust the stack pointer and jump to callee.
666 MBBI = MBB.getLastNonDebugInstr();
667 MachineOperand &JumpTarget = MBBI->getOperand(0);
714 fixTCReturn(MF, MBB);
715
669 // Jump to label or value in register.
670 if (RetOpcode == ARM::TCRETURNdi) {
671 unsigned TCOpcode = STI.isThumb() ?
672 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
673 ARM::TAILJMPd;
674 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
675 if (JumpTarget.isGlobal())
676 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
677 JumpTarget.getTargetFlags());
678 else {
679 assert(JumpTarget.isSymbol());
680 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
681 JumpTarget.getTargetFlags());
682 }
683
684 // Add the default predicate in Thumb mode.
685 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
686 } else if (RetOpcode == ARM::TCRETURNri) {
687 BuildMI(MBB, MBBI, dl,
688 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
689 addReg(JumpTarget.getReg(), RegState::Kill);
690 }
691
692 MachineInstr *NewMI = std::prev(MBBI);
693 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
694 NewMI->addOperand(MBBI->getOperand(i));
695
696 // Delete the pseudo instruction TCRETURN.
697 MBB.erase(MBBI);
698 MBBI = NewMI;
699 }
700
716 if (ArgRegsSaveSize)
717 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
718}
719
720/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
721/// debug info. It's the same as what we use for resolving the code-gen
722/// references for now. FIXME: This can go wrong when references are
723/// SP-relative and simple call frames aren't used.
724int
725ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
726 unsigned &FrameReg) const {
727 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
728}
729
730int
731ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
732 int FI, unsigned &FrameReg,
733 int SPAdj) const {
734 const MachineFrameInfo *MFI = MF.getFrameInfo();
735 const ARMBaseRegisterInfo *RegInfo =
736 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
737 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
738 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
739 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
740 bool isFixed = MFI->isFixedObjectIndex(FI);
741
742 FrameReg = ARM::SP;
743 Offset += SPAdj;
744
745 // SP can move around if there are allocas. We may also lose track of SP
746 // when emergency spilling inside a non-reserved call frame setup.
747 bool hasMovingSP = !hasReservedCallFrame(MF);
748
749 // When dynamically realigning the stack, use the frame pointer for
750 // parameters, and the stack/base pointer for locals.
751 if (RegInfo->needsStackRealignment(MF)) {
752 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
753 if (isFixed) {
754 FrameReg = RegInfo->getFrameRegister(MF);
755 Offset = FPOffset;
756 } else if (hasMovingSP) {
757 assert(RegInfo->hasBasePointer(MF) &&
758 "VLAs and dynamic stack alignment, but missing base pointer!");
759 FrameReg = RegInfo->getBaseRegister();
760 }
761 return Offset;
762 }
763
764 // If there is a frame pointer, use it when we can.
765 if (hasFP(MF) && AFI->hasStackFrame()) {
766 // Use frame pointer to reference fixed objects. Use it for locals if
767 // there are VLAs (and thus the SP isn't reliable as a base).
768 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
769 FrameReg = RegInfo->getFrameRegister(MF);
770 return FPOffset;
771 } else if (hasMovingSP) {
772 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
773 if (AFI->isThumb2Function()) {
774 // Try to use the frame pointer if we can, else use the base pointer
775 // since it's available. This is handy for the emergency spill slot, in
776 // particular.
777 if (FPOffset >= -255 && FPOffset < 0) {
778 FrameReg = RegInfo->getFrameRegister(MF);
779 return FPOffset;
780 }
781 }
782 } else if (AFI->isThumb2Function()) {
783 // Use add <rd>, sp, #<imm8>
784 // ldr <rd>, [sp, #<imm8>]
785 // if at all possible to save space.
786 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
787 return Offset;
788 // In Thumb2 mode, the negative offset is very limited. Try to avoid
789 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
790 if (FPOffset >= -255 && FPOffset < 0) {
791 FrameReg = RegInfo->getFrameRegister(MF);
792 return FPOffset;
793 }
794 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
795 // Otherwise, use SP or FP, whichever is closer to the stack slot.
796 FrameReg = RegInfo->getFrameRegister(MF);
797 return FPOffset;
798 }
799 }
800 // Use the base pointer if we have one.
801 if (RegInfo->hasBasePointer(MF))
802 FrameReg = RegInfo->getBaseRegister();
803 return Offset;
804}
805
806int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
807 int FI) const {
808 unsigned FrameReg;
809 return getFrameIndexReference(MF, FI, FrameReg);
810}
811
812void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
813 MachineBasicBlock::iterator MI,
814 const std::vector<CalleeSavedInfo> &CSI,
815 unsigned StmOpc, unsigned StrOpc,
816 bool NoGap,
817 bool(*Func)(unsigned, bool),
818 unsigned NumAlignedDPRCS2Regs,
819 unsigned MIFlags) const {
820 MachineFunction &MF = *MBB.getParent();
821 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
822
823 DebugLoc DL;
824 if (MI != MBB.end()) DL = MI->getDebugLoc();
825
826 SmallVector<std::pair<unsigned,bool>, 4> Regs;
827 unsigned i = CSI.size();
828 while (i != 0) {
829 unsigned LastReg = 0;
830 for (; i != 0; --i) {
831 unsigned Reg = CSI[i-1].getReg();
832 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
833
834 // D-registers in the aligned area DPRCS2 are NOT spilled here.
835 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
836 continue;
837
838 // Add the callee-saved register as live-in unless it's LR and
839 // @llvm.returnaddress is called. If LR is returned for
840 // @llvm.returnaddress then it's already added to the function and
841 // entry block live-in sets.
842 bool isKill = true;
843 if (Reg == ARM::LR) {
844 if (MF.getFrameInfo()->isReturnAddressTaken() &&
845 MF.getRegInfo().isLiveIn(Reg))
846 isKill = false;
847 }
848
849 if (isKill)
850 MBB.addLiveIn(Reg);
851
852 // If NoGap is true, push consecutive registers and then leave the rest
853 // for other instructions. e.g.
854 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
855 if (NoGap && LastReg && LastReg != Reg-1)
856 break;
857 LastReg = Reg;
858 Regs.push_back(std::make_pair(Reg, isKill));
859 }
860
861 if (Regs.empty())
862 continue;
863 if (Regs.size() > 1 || StrOpc== 0) {
864 MachineInstrBuilder MIB =
865 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
866 .addReg(ARM::SP).setMIFlags(MIFlags));
867 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
868 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
869 } else if (Regs.size() == 1) {
870 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
871 ARM::SP)
872 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
873 .addReg(ARM::SP).setMIFlags(MIFlags)
874 .addImm(-4);
875 AddDefaultPred(MIB);
876 }
877 Regs.clear();
878
879 // Put any subsequent vpush instructions before this one: they will refer to
880 // higher register numbers so need to be pushed first in order to preserve
881 // monotonicity.
882 --MI;
883 }
884}
885
886void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
887 MachineBasicBlock::iterator MI,
888 const std::vector<CalleeSavedInfo> &CSI,
889 unsigned LdmOpc, unsigned LdrOpc,
890 bool isVarArg, bool NoGap,
891 bool(*Func)(unsigned, bool),
892 unsigned NumAlignedDPRCS2Regs) const {
893 MachineFunction &MF = *MBB.getParent();
894 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
895 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
896 DebugLoc DL = MI->getDebugLoc();
897 unsigned RetOpcode = MI->getOpcode();
898 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
899 RetOpcode == ARM::TCRETURNri);
900 bool isInterrupt =
901 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
902
903 SmallVector<unsigned, 4> Regs;
904 unsigned i = CSI.size();
905 while (i != 0) {
906 unsigned LastReg = 0;
907 bool DeleteRet = false;
908 for (; i != 0; --i) {
909 unsigned Reg = CSI[i-1].getReg();
910 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
911
912 // The aligned reloads from area DPRCS2 are not inserted here.
913 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
914 continue;
915
916 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
917 STI.hasV5TOps()) {
918 Reg = ARM::PC;
919 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
920 // Fold the return instruction into the LDM.
921 DeleteRet = true;
922 }
923
924 // If NoGap is true, pop consecutive registers and then leave the rest
925 // for other instructions. e.g.
926 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
927 if (NoGap && LastReg && LastReg != Reg-1)
928 break;
929
930 LastReg = Reg;
931 Regs.push_back(Reg);
932 }
933
934 if (Regs.empty())
935 continue;
936 if (Regs.size() > 1 || LdrOpc == 0) {
937 MachineInstrBuilder MIB =
938 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
939 .addReg(ARM::SP));
940 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
941 MIB.addReg(Regs[i], getDefRegState(true));
942 if (DeleteRet) {
943 MIB.copyImplicitOps(&*MI);
944 MI->eraseFromParent();
945 }
946 MI = MIB;
947 } else if (Regs.size() == 1) {
948 // If we adjusted the reg to PC from LR above, switch it back here. We
949 // only do that for LDM.
950 if (Regs[0] == ARM::PC)
951 Regs[0] = ARM::LR;
952 MachineInstrBuilder MIB =
953 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
954 .addReg(ARM::SP, RegState::Define)
955 .addReg(ARM::SP);
956 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
957 // that refactoring is complete (eventually).
958 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
959 MIB.addReg(0);
960 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
961 } else
962 MIB.addImm(4);
963 AddDefaultPred(MIB);
964 }
965 Regs.clear();
966
967 // Put any subsequent vpop instructions after this one: they will refer to
968 // higher register numbers so need to be popped afterwards.
969 ++MI;
970 }
971}
972
973/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
974/// starting from d8. Also insert stack realignment code and leave the stack
975/// pointer pointing to the d8 spill slot.
976static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
977 MachineBasicBlock::iterator MI,
978 unsigned NumAlignedDPRCS2Regs,
979 const std::vector<CalleeSavedInfo> &CSI,
980 const TargetRegisterInfo *TRI) {
981 MachineFunction &MF = *MBB.getParent();
982 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
983 DebugLoc DL = MI->getDebugLoc();
984 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
985 MachineFrameInfo &MFI = *MF.getFrameInfo();
986
987 // Mark the D-register spill slots as properly aligned. Since MFI computes
988 // stack slot layout backwards, this can actually mean that the d-reg stack
989 // slot offsets can be wrong. The offset for d8 will always be correct.
990 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
991 unsigned DNum = CSI[i].getReg() - ARM::D8;
992 if (DNum >= 8)
993 continue;
994 int FI = CSI[i].getFrameIdx();
995 // The even-numbered registers will be 16-byte aligned, the odd-numbered
996 // registers will be 8-byte aligned.
997 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
998
999 // The stack slot for D8 needs to be maximally aligned because this is
1000 // actually the point where we align the stack pointer. MachineFrameInfo
1001 // computes all offsets relative to the incoming stack pointer which is a
1002 // bit weird when realigning the stack. Any extra padding for this
1003 // over-alignment is not realized because the code inserted below adjusts
1004 // the stack pointer by numregs * 8 before aligning the stack pointer.
1005 if (DNum == 0)
1006 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1007 }
1008
1009 // Move the stack pointer to the d8 spill slot, and align it at the same
1010 // time. Leave the stack slot address in the scratch register r4.
1011 //
1012 // sub r4, sp, #numregs * 8
1013 // bic r4, r4, #align - 1
1014 // mov sp, r4
1015 //
1016 bool isThumb = AFI->isThumbFunction();
1017 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1018 AFI->setShouldRestoreSPFromFP(true);
1019
1020 // sub r4, sp, #numregs * 8
1021 // The immediate is <= 64, so it doesn't need any special encoding.
1022 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1023 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1024 .addReg(ARM::SP)
1025 .addImm(8 * NumAlignedDPRCS2Regs)));
1026
1027 // bic r4, r4, #align-1
1028 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1029 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1030 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1031 .addReg(ARM::R4, RegState::Kill)
1032 .addImm(MaxAlign - 1)));
1033
1034 // mov sp, r4
1035 // The stack pointer must be adjusted before spilling anything, otherwise
1036 // the stack slots could be clobbered by an interrupt handler.
1037 // Leave r4 live, it is used below.
1038 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1039 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1040 .addReg(ARM::R4);
1041 MIB = AddDefaultPred(MIB);
1042 if (!isThumb)
1043 AddDefaultCC(MIB);
1044
1045 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1046 // r4 holds the stack slot address.
1047 unsigned NextReg = ARM::D8;
1048
1049 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1050 // The writeback is only needed when emitting two vst1.64 instructions.
1051 if (NumAlignedDPRCS2Regs >= 6) {
1052 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1053 &ARM::QQPRRegClass);
1054 MBB.addLiveIn(SupReg);
1055 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1056 ARM::R4)
1057 .addReg(ARM::R4, RegState::Kill).addImm(16)
1058 .addReg(NextReg)
1059 .addReg(SupReg, RegState::ImplicitKill));
1060 NextReg += 4;
1061 NumAlignedDPRCS2Regs -= 4;
1062 }
1063
1064 // We won't modify r4 beyond this point. It currently points to the next
1065 // register to be spilled.
1066 unsigned R4BaseReg = NextReg;
1067
1068 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1069 if (NumAlignedDPRCS2Regs >= 4) {
1070 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1071 &ARM::QQPRRegClass);
1072 MBB.addLiveIn(SupReg);
1073 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1074 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1075 .addReg(SupReg, RegState::ImplicitKill));
1076 NextReg += 4;
1077 NumAlignedDPRCS2Regs -= 4;
1078 }
1079
1080 // 16-byte aligned vst1.64 with 2 d-regs.
1081 if (NumAlignedDPRCS2Regs >= 2) {
1082 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1083 &ARM::QPRRegClass);
1084 MBB.addLiveIn(SupReg);
1085 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1086 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1087 NextReg += 2;
1088 NumAlignedDPRCS2Regs -= 2;
1089 }
1090
1091 // Finally, use a vanilla vstr.64 for the odd last register.
1092 if (NumAlignedDPRCS2Regs) {
1093 MBB.addLiveIn(NextReg);
1094 // vstr.64 uses addrmode5 which has an offset scale of 4.
1095 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1096 .addReg(NextReg)
1097 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1098 }
1099
1100 // The last spill instruction inserted should kill the scratch register r4.
1101 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1102}
1103
1104/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1105/// iterator to the following instruction.
1106static MachineBasicBlock::iterator
1107skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1108 unsigned NumAlignedDPRCS2Regs) {
1109 // sub r4, sp, #numregs * 8
1110 // bic r4, r4, #align - 1
1111 // mov sp, r4
1112 ++MI; ++MI; ++MI;
1113 assert(MI->mayStore() && "Expecting spill instruction");
1114
1115 // These switches all fall through.
1116 switch(NumAlignedDPRCS2Regs) {
1117 case 7:
1118 ++MI;
1119 assert(MI->mayStore() && "Expecting spill instruction");
1120 default:
1121 ++MI;
1122 assert(MI->mayStore() && "Expecting spill instruction");
1123 case 1:
1124 case 2:
1125 case 4:
1126 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1127 ++MI;
1128 }
1129 return MI;
1130}
1131
1132/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1133/// starting from d8. These instructions are assumed to execute while the
1134/// stack is still aligned, unlike the code inserted by emitPopInst.
1135static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1136 MachineBasicBlock::iterator MI,
1137 unsigned NumAlignedDPRCS2Regs,
1138 const std::vector<CalleeSavedInfo> &CSI,
1139 const TargetRegisterInfo *TRI) {
1140 MachineFunction &MF = *MBB.getParent();
1141 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1142 DebugLoc DL = MI->getDebugLoc();
1143 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1144
1145 // Find the frame index assigned to d8.
1146 int D8SpillFI = 0;
1147 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1148 if (CSI[i].getReg() == ARM::D8) {
1149 D8SpillFI = CSI[i].getFrameIdx();
1150 break;
1151 }
1152
1153 // Materialize the address of the d8 spill slot into the scratch register r4.
1154 // This can be fairly complicated if the stack frame is large, so just use
1155 // the normal frame index elimination mechanism to do it. This code runs as
1156 // the initial part of the epilog where the stack and base pointers haven't
1157 // been changed yet.
1158 bool isThumb = AFI->isThumbFunction();
1159 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1160
1161 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1162 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1163 .addFrameIndex(D8SpillFI).addImm(0)));
1164
1165 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1166 unsigned NextReg = ARM::D8;
1167
1168 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1169 if (NumAlignedDPRCS2Regs >= 6) {
1170 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1171 &ARM::QQPRRegClass);
1172 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1173 .addReg(ARM::R4, RegState::Define)
1174 .addReg(ARM::R4, RegState::Kill).addImm(16)
1175 .addReg(SupReg, RegState::ImplicitDefine));
1176 NextReg += 4;
1177 NumAlignedDPRCS2Regs -= 4;
1178 }
1179
1180 // We won't modify r4 beyond this point. It currently points to the next
1181 // register to be spilled.
1182 unsigned R4BaseReg = NextReg;
1183
1184 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1185 if (NumAlignedDPRCS2Regs >= 4) {
1186 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1187 &ARM::QQPRRegClass);
1188 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1189 .addReg(ARM::R4).addImm(16)
1190 .addReg(SupReg, RegState::ImplicitDefine));
1191 NextReg += 4;
1192 NumAlignedDPRCS2Regs -= 4;
1193 }
1194
1195 // 16-byte aligned vld1.64 with 2 d-regs.
1196 if (NumAlignedDPRCS2Regs >= 2) {
1197 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1198 &ARM::QPRRegClass);
1199 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1200 .addReg(ARM::R4).addImm(16));
1201 NextReg += 2;
1202 NumAlignedDPRCS2Regs -= 2;
1203 }
1204
1205 // Finally, use a vanilla vldr.64 for the remaining odd register.
1206 if (NumAlignedDPRCS2Regs)
1207 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1208 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1209
1210 // Last store kills r4.
1211 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1212}
1213
1214bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1215 MachineBasicBlock::iterator MI,
1216 const std::vector<CalleeSavedInfo> &CSI,
1217 const TargetRegisterInfo *TRI) const {
1218 if (CSI.empty())
1219 return false;
1220
1221 MachineFunction &MF = *MBB.getParent();
1222 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1223
1224 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1225 unsigned PushOneOpc = AFI->isThumbFunction() ?
1226 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1227 unsigned FltOpc = ARM::VSTMDDB_UPD;
1228 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1229 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1230 MachineInstr::FrameSetup);
1231 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1232 MachineInstr::FrameSetup);
1233 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1234 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1235
1236 // The code above does not insert spill code for the aligned DPRCS2 registers.
1237 // The stack realignment code will be inserted between the push instructions
1238 // and these spills.
1239 if (NumAlignedDPRCS2Regs)
1240 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1241
1242 return true;
1243}
1244
1245bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1246 MachineBasicBlock::iterator MI,
1247 const std::vector<CalleeSavedInfo> &CSI,
1248 const TargetRegisterInfo *TRI) const {
1249 if (CSI.empty())
1250 return false;
1251
1252 MachineFunction &MF = *MBB.getParent();
1253 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1254 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1255 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1256
1257 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1258 // registers. Do that here instead.
1259 if (NumAlignedDPRCS2Regs)
1260 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1261
1262 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1263 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1264 unsigned FltOpc = ARM::VLDMDIA_UPD;
1265 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1266 NumAlignedDPRCS2Regs);
1267 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1268 &isARMArea2Register, 0);
1269 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1270 &isARMArea1Register, 0);
1271
1272 return true;
1273}
1274
1275// FIXME: Make generic?
1276static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1277 const ARMBaseInstrInfo &TII) {
1278 unsigned FnSize = 0;
1279 for (auto &MBB : MF) {
1280 for (auto &MI : MBB)
1281 FnSize += TII.GetInstSizeInBytes(&MI);
1282 }
1283 return FnSize;
1284}
1285
1286/// estimateRSStackSizeLimit - Look at each instruction that references stack
1287/// frames and return the stack size limit beyond which some of these
1288/// instructions will require a scratch register during their expansion later.
1289// FIXME: Move to TII?
1290static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1291 const TargetFrameLowering *TFI) {
1292 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1293 unsigned Limit = (1 << 12) - 1;
1294 for (auto &MBB : MF) {
1295 for (auto &MI : MBB) {
1296 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1297 if (!MI.getOperand(i).isFI())
1298 continue;
1299
1300 // When using ADDri to get the address of a stack object, 255 is the
1301 // largest offset guaranteed to fit in the immediate offset.
1302 if (MI.getOpcode() == ARM::ADDri) {
1303 Limit = std::min(Limit, (1U << 8) - 1);
1304 break;
1305 }
1306
1307 // Otherwise check the addressing mode.
1308 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1309 case ARMII::AddrMode3:
1310 case ARMII::AddrModeT2_i8:
1311 Limit = std::min(Limit, (1U << 8) - 1);
1312 break;
1313 case ARMII::AddrMode5:
1314 case ARMII::AddrModeT2_i8s4:
1315 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1316 break;
1317 case ARMII::AddrModeT2_i12:
1318 // i12 supports only positive offset so these will be converted to
1319 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1320 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1321 Limit = std::min(Limit, (1U << 8) - 1);
1322 break;
1323 case ARMII::AddrMode4:
1324 case ARMII::AddrMode6:
1325 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1326 // immediate offset for stack references.
1327 return 0;
1328 default:
1329 break;
1330 }
1331 break; // At most one FI per instruction
1332 }
1333 }
1334 }
1335
1336 return Limit;
1337}
1338
1339// In functions that realign the stack, it can be an advantage to spill the
1340// callee-saved vector registers after realigning the stack. The vst1 and vld1
1341// instructions take alignment hints that can improve performance.
1342//
1343static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1344 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1345 if (!SpillAlignedNEONRegs)
1346 return;
1347
1348 // Naked functions don't spill callee-saved registers.
1349 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1350 Attribute::Naked))
1351 return;
1352
1353 // We are planning to use NEON instructions vst1 / vld1.
1354 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1355 return;
1356
1357 // Don't bother if the default stack alignment is sufficiently high.
1358 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1359 return;
1360
1361 // Aligned spills require stack realignment.
1362 const ARMBaseRegisterInfo *RegInfo =
1363 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1364 if (!RegInfo->canRealignStack(MF))
1365 return;
1366
1367 // We always spill contiguous d-registers starting from d8. Count how many
1368 // needs spilling. The register allocator will almost always use the
1369 // callee-saved registers in order, but it can happen that there are holes in
1370 // the range. Registers above the hole will be spilled to the standard DPRCS
1371 // area.
1372 MachineRegisterInfo &MRI = MF.getRegInfo();
1373 unsigned NumSpills = 0;
1374 for (; NumSpills < 8; ++NumSpills)
1375 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1376 break;
1377
1378 // Don't do this for just one d-register. It's not worth it.
1379 if (NumSpills < 2)
1380 return;
1381
1382 // Spill the first NumSpills D-registers after realigning the stack.
1383 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1384
1385 // A scratch register is required for the vst1 / vld1 instructions.
1386 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1387}
1388
1389void
1390ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1391 RegScavenger *RS) const {
1392 // This tells PEI to spill the FP as if it is any other callee-save register
1393 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1394 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1395 // to combine multiple loads / stores.
1396 bool CanEliminateFrame = true;
1397 bool CS1Spilled = false;
1398 bool LRSpilled = false;
1399 unsigned NumGPRSpills = 0;
1400 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1401 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1402 const ARMBaseRegisterInfo *RegInfo =
1403 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1404 const ARMBaseInstrInfo &TII =
1405 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1406 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1407 MachineFrameInfo *MFI = MF.getFrameInfo();
1408 MachineRegisterInfo &MRI = MF.getRegInfo();
1409 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1410
1411 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1412 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1413 // since it's not always possible to restore sp from fp in a single
1414 // instruction.
1415 // FIXME: It will be better just to find spare register here.
1416 if (AFI->isThumb2Function() &&
1417 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1418 MRI.setPhysRegUsed(ARM::R4);
1419
1420 if (AFI->isThumb1OnlyFunction()) {
1421 // Spill LR if Thumb1 function uses variable length argument lists.
1422 if (AFI->getArgRegsSaveSize() > 0)
1423 MRI.setPhysRegUsed(ARM::LR);
1424
1425 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1426 // for sure what the stack size will be, but for this, an estimate is good
1427 // enough. If there anything changes it, it'll be a spill, which implies
1428 // we've used all the registers and so R4 is already used, so not marking
1429 // it here will be OK.
1430 // FIXME: It will be better just to find spare register here.
1431 unsigned StackSize = MFI->estimateStackSize(MF);
1432 if (MFI->hasVarSizedObjects() || StackSize > 508)
1433 MRI.setPhysRegUsed(ARM::R4);
1434 }
1435
1436 // See if we can spill vector registers to aligned stack.
1437 checkNumAlignedDPRCS2Regs(MF);
1438
1439 // Spill the BasePtr if it's used.
1440 if (RegInfo->hasBasePointer(MF))
1441 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1442
1443 // Don't spill FP if the frame can be eliminated. This is determined
1444 // by scanning the callee-save registers to see if any is used.
1445 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1446 for (unsigned i = 0; CSRegs[i]; ++i) {
1447 unsigned Reg = CSRegs[i];
1448 bool Spilled = false;
1449 if (MRI.isPhysRegUsed(Reg)) {
1450 Spilled = true;
1451 CanEliminateFrame = false;
1452 }
1453
1454 if (!ARM::GPRRegClass.contains(Reg))
1455 continue;
1456
1457 if (Spilled) {
1458 NumGPRSpills++;
1459
1460 if (!STI.isTargetDarwin()) {
1461 if (Reg == ARM::LR)
1462 LRSpilled = true;
1463 CS1Spilled = true;
1464 continue;
1465 }
1466
1467 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1468 switch (Reg) {
1469 case ARM::LR:
1470 LRSpilled = true;
1471 // Fallthrough
1472 case ARM::R0: case ARM::R1:
1473 case ARM::R2: case ARM::R3:
1474 case ARM::R4: case ARM::R5:
1475 case ARM::R6: case ARM::R7:
1476 CS1Spilled = true;
1477 break;
1478 default:
1479 break;
1480 }
1481 } else {
1482 if (!STI.isTargetDarwin()) {
1483 UnspilledCS1GPRs.push_back(Reg);
1484 continue;
1485 }
1486
1487 switch (Reg) {
1488 case ARM::R0: case ARM::R1:
1489 case ARM::R2: case ARM::R3:
1490 case ARM::R4: case ARM::R5:
1491 case ARM::R6: case ARM::R7:
1492 case ARM::LR:
1493 UnspilledCS1GPRs.push_back(Reg);
1494 break;
1495 default:
1496 UnspilledCS2GPRs.push_back(Reg);
1497 break;
1498 }
1499 }
1500 }
1501
1502 bool ForceLRSpill = false;
1503 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1504 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1505 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1506 // use of BL to implement far jump. If it turns out that it's not needed
1507 // then the branch fix up path will undo it.
1508 if (FnSize >= (1 << 11)) {
1509 CanEliminateFrame = false;
1510 ForceLRSpill = true;
1511 }
1512 }
1513
1514 // If any of the stack slot references may be out of range of an immediate
1515 // offset, make sure a register (or a spill slot) is available for the
1516 // register scavenger. Note that if we're indexing off the frame pointer, the
1517 // effective stack size is 4 bytes larger since the FP points to the stack
1518 // slot of the previous FP. Also, if we have variable sized objects in the
1519 // function, stack slot references will often be negative, and some of
1520 // our instructions are positive-offset only, so conservatively consider
1521 // that case to want a spill slot (or register) as well. Similarly, if
1522 // the function adjusts the stack pointer during execution and the
1523 // adjustments aren't already part of our stack size estimate, our offset
1524 // calculations may be off, so be conservative.
1525 // FIXME: We could add logic to be more precise about negative offsets
1526 // and which instructions will need a scratch register for them. Is it
1527 // worth the effort and added fragility?
1528 bool BigStack =
1529 (RS &&
1530 (MFI->estimateStackSize(MF) +
1531 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1532 estimateRSStackSizeLimit(MF, this)))
1533 || MFI->hasVarSizedObjects()
1534 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1535
1536 bool ExtraCSSpill = false;
1537 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1538 AFI->setHasStackFrame(true);
1539
1540 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1541 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1542 if (!LRSpilled && CS1Spilled) {
1543 MRI.setPhysRegUsed(ARM::LR);
1544 NumGPRSpills++;
1545 SmallVectorImpl<unsigned>::iterator LRPos;
1546 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1547 (unsigned)ARM::LR);
1548 if (LRPos != UnspilledCS1GPRs.end())
1549 UnspilledCS1GPRs.erase(LRPos);
1550
1551 ForceLRSpill = false;
1552 ExtraCSSpill = true;
1553 }
1554
1555 if (hasFP(MF)) {
1556 MRI.setPhysRegUsed(FramePtr);
1557 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1558 FramePtr);
1559 if (FPPos != UnspilledCS1GPRs.end())
1560 UnspilledCS1GPRs.erase(FPPos);
1561 NumGPRSpills++;
1562 }
1563
1564 // If stack and double are 8-byte aligned and we are spilling an odd number
1565 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1566 // the integer and double callee save areas.
1567 unsigned TargetAlign = getStackAlignment();
1568 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1569 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1570 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1571 unsigned Reg = UnspilledCS1GPRs[i];
1572 // Don't spill high register if the function is thumb1
1573 if (!AFI->isThumb1OnlyFunction() ||
1574 isARMLowRegister(Reg) || Reg == ARM::LR) {
1575 MRI.setPhysRegUsed(Reg);
1576 if (!MRI.isReserved(Reg))
1577 ExtraCSSpill = true;
1578 break;
1579 }
1580 }
1581 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1582 unsigned Reg = UnspilledCS2GPRs.front();
1583 MRI.setPhysRegUsed(Reg);
1584 if (!MRI.isReserved(Reg))
1585 ExtraCSSpill = true;
1586 }
1587 }
1588
1589 // Estimate if we might need to scavenge a register at some point in order
1590 // to materialize a stack offset. If so, either spill one additional
1591 // callee-saved register or reserve a special spill slot to facilitate
1592 // register scavenging. Thumb1 needs a spill slot for stack pointer
1593 // adjustments also, even when the frame itself is small.
1594 if (BigStack && !ExtraCSSpill) {
1595 // If any non-reserved CS register isn't spilled, just spill one or two
1596 // extra. That should take care of it!
1597 unsigned NumExtras = TargetAlign / 4;
1598 SmallVector<unsigned, 2> Extras;
1599 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1600 unsigned Reg = UnspilledCS1GPRs.back();
1601 UnspilledCS1GPRs.pop_back();
1602 if (!MRI.isReserved(Reg) &&
1603 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1604 Reg == ARM::LR)) {
1605 Extras.push_back(Reg);
1606 NumExtras--;
1607 }
1608 }
1609 // For non-Thumb1 functions, also check for hi-reg CS registers
1610 if (!AFI->isThumb1OnlyFunction()) {
1611 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1612 unsigned Reg = UnspilledCS2GPRs.back();
1613 UnspilledCS2GPRs.pop_back();
1614 if (!MRI.isReserved(Reg)) {
1615 Extras.push_back(Reg);
1616 NumExtras--;
1617 }
1618 }
1619 }
1620 if (Extras.size() && NumExtras == 0) {
1621 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1622 MRI.setPhysRegUsed(Extras[i]);
1623 }
1624 } else if (!AFI->isThumb1OnlyFunction()) {
1625 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1626 // closest to SP or frame pointer.
1627 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1628 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1629 RC->getAlignment(),
1630 false));
1631 }
1632 }
1633 }
1634
1635 if (ForceLRSpill) {
1636 MRI.setPhysRegUsed(ARM::LR);
1637 AFI->setLRIsSpilledForFarJump(true);
1638 }
1639}
1640
1641
1642void ARMFrameLowering::
1643eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1644 MachineBasicBlock::iterator I) const {
1645 const ARMBaseInstrInfo &TII =
1646 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1647 if (!hasReservedCallFrame(MF)) {
1648 // If we have alloca, convert as follows:
1649 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1650 // ADJCALLSTACKUP -> add, sp, sp, amount
1651 MachineInstr *Old = I;
1652 DebugLoc dl = Old->getDebugLoc();
1653 unsigned Amount = Old->getOperand(0).getImm();
1654 if (Amount != 0) {
1655 // We need to keep the stack aligned properly. To do this, we round the
1656 // amount of space needed for the outgoing arguments up to the next
1657 // alignment boundary.
1658 unsigned Align = getStackAlignment();
1659 Amount = (Amount+Align-1)/Align*Align;
1660
1661 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1662 assert(!AFI->isThumb1OnlyFunction() &&
1663 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1664 bool isARM = !AFI->isThumbFunction();
1665
1666 // Replace the pseudo instruction with a new instruction...
1667 unsigned Opc = Old->getOpcode();
1668 int PIdx = Old->findFirstPredOperandIdx();
1669 ARMCC::CondCodes Pred = (PIdx == -1)
1670 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1671 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1672 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1673 unsigned PredReg = Old->getOperand(2).getReg();
1674 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1675 Pred, PredReg);
1676 } else {
1677 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1678 unsigned PredReg = Old->getOperand(3).getReg();
1679 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1680 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1681 Pred, PredReg);
1682 }
1683 }
1684 }
1685 MBB.erase(I);
1686}
1687
1688/// Get the minimum constant for ARM that is greater than or equal to the
1689/// argument. In ARM, constants can have any value that can be produced by
1690/// rotating an 8-bit value to the right by an even number of bits within a
1691/// 32-bit word.
1692static uint32_t alignToARMConstant(uint32_t Value) {
1693 unsigned Shifted = 0;
1694
1695 if (Value == 0)
1696 return 0;
1697
1698 while (!(Value & 0xC0000000)) {
1699 Value = Value << 2;
1700 Shifted += 2;
1701 }
1702
1703 bool Carry = (Value & 0x00FFFFFF);
1704 Value = ((Value & 0xFF000000) >> 24) + Carry;
1705
1706 if (Value & 0x0000100)
1707 Value = Value & 0x000001FC;
1708
1709 if (Shifted > 24)
1710 Value = Value >> (Shifted - 24);
1711 else
1712 Value = Value << (24 - Shifted);
1713
1714 return Value;
1715}
1716
1717// The stack limit in the TCB is set to this many bytes above the actual
1718// stack limit.
1719static const uint64_t kSplitStackAvailable = 256;
1720
1721// Adjust the function prologue to enable split stacks. This currently only
1722// supports android and linux.
1723//
1724// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1725// must be well defined in order to allow for consistent implementations of the
1726// __morestack helper function. The ABI is also not a normal ABI in that it
1727// doesn't follow the normal calling conventions because this allows the
1728// prologue of each function to be optimized further.
1729//
1730// Currently, the ABI looks like (when calling __morestack)
1731//
1732// * r4 holds the minimum stack size requested for this function call
1733// * r5 holds the stack size of the arguments to the function
1734// * the beginning of the function is 3 instructions after the call to
1735// __morestack
1736//
1737// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1738// place the arguments on to the new stack, and the 3-instruction knowledge to
1739// jump directly to the body of the function when working on the new stack.
1740//
1741// An old (and possibly no longer compatible) implementation of __morestack for
1742// ARM can be found at [1].
1743//
1744// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1745void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1746 unsigned Opcode;
1747 unsigned CFIIndex;
1748 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1749 bool Thumb = ST->isThumb();
1750
1751 // Sadly, this currently doesn't support varargs, platforms other than
1752 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1753 if (MF.getFunction()->isVarArg())
1754 report_fatal_error("Segmented stacks do not support vararg functions.");
1755 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1756 report_fatal_error("Segmented stacks not supported on this platform.");
1757
1758 MachineBasicBlock &prologueMBB = MF.front();
1759 MachineFrameInfo *MFI = MF.getFrameInfo();
1760 MachineModuleInfo &MMI = MF.getMMI();
1761 MCContext &Context = MMI.getContext();
1762 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1763 const ARMBaseInstrInfo &TII =
1764 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1765 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1766 DebugLoc DL;
1767
1768 uint64_t StackSize = MFI->getStackSize();
1769
1770 // Do not generate a prologue for functions with a stack of size zero
1771 if (StackSize == 0)
1772 return;
1773
1774 // Use R4 and R5 as scratch registers.
1775 // We save R4 and R5 before use and restore them before leaving the function.
1776 unsigned ScratchReg0 = ARM::R4;
1777 unsigned ScratchReg1 = ARM::R5;
1778 uint64_t AlignedStackSize;
1779
1780 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1781 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1782 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1783 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1784 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1785
1786 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1787 e = prologueMBB.livein_end();
1788 i != e; ++i) {
1789 AllocMBB->addLiveIn(*i);
1790 GetMBB->addLiveIn(*i);
1791 McrMBB->addLiveIn(*i);
1792 PrevStackMBB->addLiveIn(*i);
1793 PostStackMBB->addLiveIn(*i);
1794 }
1795
1796 MF.push_front(PostStackMBB);
1797 MF.push_front(AllocMBB);
1798 MF.push_front(GetMBB);
1799 MF.push_front(McrMBB);
1800 MF.push_front(PrevStackMBB);
1801
1802 // The required stack size that is aligned to ARM constant criterion.
1803 AlignedStackSize = alignToARMConstant(StackSize);
1804
1805 // When the frame size is less than 256 we just compare the stack
1806 // boundary directly to the value of the stack pointer, per gcc.
1807 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1808
1809 // We will use two of the callee save registers as scratch registers so we
1810 // need to save those registers onto the stack.
1811 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1812 // requested and arguments for __morestack().
1813 // SR0: Scratch Register #0
1814 // SR1: Scratch Register #1
1815 // push {SR0, SR1}
1816 if (Thumb) {
1817 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1818 .addReg(ScratchReg0).addReg(ScratchReg1);
1819 } else {
1820 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1821 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1822 .addReg(ScratchReg0).addReg(ScratchReg1);
1823 }
1824
1825 // Emit the relevant DWARF information about the change in stack pointer as
1826 // well as where to find both r4 and r5 (the callee-save registers)
1827 CFIIndex =
1828 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1829 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1830 .addCFIIndex(CFIIndex);
1831 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1832 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1833 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1834 .addCFIIndex(CFIIndex);
1835 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1836 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1837 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1838 .addCFIIndex(CFIIndex);
1839
1840 // mov SR1, sp
1841 if (Thumb) {
1842 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1843 .addReg(ARM::SP));
1844 } else if (CompareStackPointer) {
1845 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1846 .addReg(ARM::SP)).addReg(0);
1847 }
1848
1849 // sub SR1, sp, #StackSize
1850 if (!CompareStackPointer && Thumb) {
1851 AddDefaultPred(
1852 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1853 .addReg(ScratchReg1).addImm(AlignedStackSize));
1854 } else if (!CompareStackPointer) {
1855 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1856 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1857 }
1858
1859 if (Thumb && ST->isThumb1Only()) {
1860 unsigned PCLabelId = ARMFI->createPICLabelUId();
1861 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1862 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1863 MachineConstantPool *MCP = MF.getConstantPool();
1864 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1865
1866 // ldr SR0, [pc, offset(STACK_LIMIT)]
1867 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1868 .addConstantPoolIndex(CPI));
1869
1870 // ldr SR0, [SR0]
1871 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1872 .addReg(ScratchReg0).addImm(0));
1873 } else {
1874 // Get TLS base address from the coprocessor
1875 // mrc p15, #0, SR0, c13, c0, #3
1876 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1877 .addImm(15)
1878 .addImm(0)
1879 .addImm(13)
1880 .addImm(0)
1881 .addImm(3));
1882
1883 // Use the last tls slot on android and a private field of the TCP on linux.
1884 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1885 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1886
1887 // Get the stack limit from the right offset
1888 // ldr SR0, [sr0, #4 * TlsOffset]
1889 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1890 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1891 }
1892
1893 // Compare stack limit with stack size requested.
1894 // cmp SR0, SR1
1895 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1896 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1897 .addReg(ScratchReg0)
1898 .addReg(ScratchReg1));
1899
1900 // This jump is taken if StackLimit < SP - stack required.
1901 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1902 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1903 .addImm(ARMCC::LO)
1904 .addReg(ARM::CPSR);
1905
1906
1907 // Calling __morestack(StackSize, Size of stack arguments).
1908 // __morestack knows that the stack size requested is in SR0(r4)
1909 // and amount size of stack arguments is in SR1(r5).
1910
1911 // Pass first argument for the __morestack by Scratch Register #0.
1912 // The amount size of stack required
1913 if (Thumb) {
1914 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1915 ScratchReg0)).addImm(AlignedStackSize));
1916 } else {
1917 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1918 .addImm(AlignedStackSize)).addReg(0);
1919 }
1920 // Pass second argument for the __morestack by Scratch Register #1.
1921 // The amount size of stack consumed to save function arguments.
1922 if (Thumb) {
1923 AddDefaultPred(
1924 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1925 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1926 } else {
1927 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1928 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1929 .addReg(0);
1930 }
1931
1932 // push {lr} - Save return address of this function.
1933 if (Thumb) {
1934 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1935 .addReg(ARM::LR);
1936 } else {
1937 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1938 .addReg(ARM::SP, RegState::Define)
1939 .addReg(ARM::SP))
1940 .addReg(ARM::LR);
1941 }
1942
1943 // Emit the DWARF info about the change in stack as well as where to find the
1944 // previous link register
1945 CFIIndex =
1946 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1947 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1948 .addCFIIndex(CFIIndex);
1949 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1950 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1951 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1952 .addCFIIndex(CFIIndex);
1953
1954 // Call __morestack().
1955 if (Thumb) {
1956 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1957 .addExternalSymbol("__morestack");
1958 } else {
1959 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1960 .addExternalSymbol("__morestack");
1961 }
1962
1963 // pop {lr} - Restore return address of this original function.
1964 if (Thumb) {
1965 if (ST->isThumb1Only()) {
1966 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1967 .addReg(ScratchReg0);
1968 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1969 .addReg(ScratchReg0));
1970 } else {
1971 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1972 .addReg(ARM::LR, RegState::Define)
1973 .addReg(ARM::SP, RegState::Define)
1974 .addReg(ARM::SP)
1975 .addImm(4));
1976 }
1977 } else {
1978 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1979 .addReg(ARM::SP, RegState::Define)
1980 .addReg(ARM::SP))
1981 .addReg(ARM::LR);
1982 }
1983
1984 // Restore SR0 and SR1 in case of __morestack() was called.
1985 // __morestack() will skip PostStackMBB block so we need to restore
1986 // scratch registers from here.
1987 // pop {SR0, SR1}
1988 if (Thumb) {
1989 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1990 .addReg(ScratchReg0)
1991 .addReg(ScratchReg1);
1992 } else {
1993 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1994 .addReg(ARM::SP, RegState::Define)
1995 .addReg(ARM::SP))
1996 .addReg(ScratchReg0)
1997 .addReg(ScratchReg1);
1998 }
1999
2000 // Update the CFA offset now that we've popped
2001 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2002 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2003 .addCFIIndex(CFIIndex);
2004
2005 // bx lr - Return from this function.
2006 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2007 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2008
2009 // Restore SR0 and SR1 in case of __morestack() was not called.
2010 // pop {SR0, SR1}
2011 if (Thumb) {
2012 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2013 .addReg(ScratchReg0)
2014 .addReg(ScratchReg1);
2015 } else {
2016 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2017 .addReg(ARM::SP, RegState::Define)
2018 .addReg(ARM::SP))
2019 .addReg(ScratchReg0)
2020 .addReg(ScratchReg1);
2021 }
2022
2023 // Update the CFA offset now that we've popped
2024 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2025 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2026 .addCFIIndex(CFIIndex);
2027
2028 // Tell debuggers that r4 and r5 are now the same as they were in the
2029 // previous function, that they're the "Same Value".
2030 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2031 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2032 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2033 .addCFIIndex(CFIIndex);
2034 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2035 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2036 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2037 .addCFIIndex(CFIIndex);
2038
2039 // Organizing MBB lists
2040 PostStackMBB->addSuccessor(&prologueMBB);
2041
2042 AllocMBB->addSuccessor(PostStackMBB);
2043
2044 GetMBB->addSuccessor(PostStackMBB);
2045 GetMBB->addSuccessor(AllocMBB);
2046
2047 McrMBB->addSuccessor(GetMBB);
2048
2049 PrevStackMBB->addSuccessor(McrMBB);
2050
2051#ifdef XDEBUG
2052 MF.verify();
2053#endif
2054}