blob: 13e66f5d1d1fd9ca1ff883d847115738d477616e [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00002//
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//
Anton Korobeynikov2f931282011-01-10 12:39:04 +000010// This file contains the ARM implementation of TargetFrameLowering class.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov2f931282011-01-10 12:39:04 +000014#include "ARMFrameLowering.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000015#include "ARMBaseInstrInfo.h"
Evan Chenge45d6852011-01-11 21:46:47 +000016#include "ARMBaseRegisterInfo.h"
Oliver Stannardb14c6252014-04-02 16:10:33 +000017#include "ARMConstantPoolValue.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000020#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengeb56dca2010-11-22 18:12:04 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +000025#include "llvm/CodeGen/RegisterScavenging.h"
Tim Northovere0ccdc62015-10-28 22:46:43 +000026#include "llvm/MC/MCAsmInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/CallingConv.h"
28#include "llvm/IR/Function.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000029#include "llvm/MC/MCContext.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000030#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetOptions.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000032
Reid Klecknerbdfc05f2016-10-11 21:14:03 +000033#define DEBUG_TYPE "arm-frame-lowering"
34
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000035using namespace llvm;
36
Benjamin Kramer9fceb902012-02-24 22:09:25 +000037static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000038SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000039 cl::desc("Align ARM NEON spills in prolog and epilog"));
40
41static MachineBasicBlock::iterator
42skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
43 unsigned NumAlignedDPRCS2Regs);
44
Eric Christopher45fb7b62014-06-26 19:29:59 +000045ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
46 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
47 STI(sti) {}
48
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000049bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
50 // iOS always has a FP for backtracking, force other targets to keep their FP
51 // when doing FastISel. The emitted code is currently superior, and in cases
52 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
53 return TargetFrameLowering::noFramePointerElim(MF) ||
54 MF.getSubtarget<ARMSubtarget>().useFastISel();
55}
56
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000057/// hasFP - Return true if the specified function should have a dedicated frame
58/// pointer register. This is true if the function has variable sized allocas
59/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000060bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000061 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +000062 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000063
Oliver Stannard9aa6f012016-08-23 09:19:22 +000064 // ABI-required frame pointer.
65 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000066 return true;
67
Oliver Stannard9aa6f012016-08-23 09:19:22 +000068 // Frame pointer required for use within this function.
69 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +000070 MFI.hasVarSizedObjects() ||
71 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000072}
73
Bob Wilson657f2272011-01-13 21:10:12 +000074/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
75/// not required, we reserve argument space for call sites in the function
76/// immediately on entry to the current function. This eliminates the need for
77/// add/sub sp brackets around call sites. Returns true if the call frame is
78/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000079bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +000080 const MachineFrameInfo &MFI = MF.getFrameInfo();
81 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000082 // It's not always a good idea to include the call frame as part of the
83 // stack frame. ARM (especially Thumb) has small immediate offset to
84 // address the stack frame. So a large call frame can cause poor codegen
85 // and may even makes it impossible to scavenge a register.
86 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
87 return false;
88
Matthias Braun941a7052016-07-28 18:40:00 +000089 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000090}
91
Bob Wilson657f2272011-01-13 21:10:12 +000092/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
93/// call frame pseudos can be simplified. Unlike most targets, having a FP
94/// is not sufficient here since we still may reference some objects via SP
95/// even when FP is available in Thumb2 mode.
96bool
97ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +000098 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000099}
100
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000101static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000102 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000103 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000104 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000105 // The first two operands are predicates. The last two are
106 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000107 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
108 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000109 return false;
110 return true;
111 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000112 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
113 MI.getOpcode() == ARM::LDR_POST_REG ||
114 MI.getOpcode() == ARM::t2LDR_POST) &&
115 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
116 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000117 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000118
119 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000120}
121
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000122static void emitRegPlusImmediate(
123 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
124 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
125 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
126 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000127 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000128 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000129 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000130 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000131 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000132 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000133}
134
Tim Northoverc9432eb2013-11-04 23:04:15 +0000135static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000136 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000137 const ARMBaseInstrInfo &TII, int NumBytes,
138 unsigned MIFlags = MachineInstr::NoFlags,
139 ARMCC::CondCodes Pred = ARMCC::AL,
140 unsigned PredReg = 0) {
141 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
142 MIFlags, Pred, PredReg);
143}
144
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000145static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000146 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000147 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000148 case ARM::VSTMDDB_UPD:
149 RegSize = 8;
150 break;
151 case ARM::STMDB_UPD:
152 case ARM::t2STMDB_UPD:
153 RegSize = 4;
154 break;
155 case ARM::t2STR_PRE:
156 case ARM::STR_PRE_IMM:
157 return 4;
158 default:
159 llvm_unreachable("Unknown push or pop like instruction");
160 }
161
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000162 int count = 0;
163 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
164 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000165 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000166 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000167 return count;
168}
169
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000170static bool WindowsRequiresStackProbe(const MachineFunction &MF,
171 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000172 const MachineFrameInfo &MFI = MF.getFrameInfo();
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000173 const Function *F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000174 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000175 if (F->hasFnAttribute("stack-probe-size"))
176 F->getFnAttribute("stack-probe-size")
177 .getValueAsString()
178 .getAsInteger(0, StackProbeSize);
179 return StackSizeInBytes >= StackProbeSize;
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000180}
181
Tim Northover603d3162014-11-14 22:45:33 +0000182namespace {
183struct StackAdjustingInsts {
184 struct InstInfo {
185 MachineBasicBlock::iterator I;
186 unsigned SPAdjust;
187 bool BeforeFPSet;
188 };
189
190 SmallVector<InstInfo, 4> Insts;
191
192 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
193 bool BeforeFPSet = false) {
194 InstInfo Info = {I, SPAdjust, BeforeFPSet};
195 Insts.push_back(Info);
196 }
197
198 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
David Majnemer562e8292016-08-12 00:18:03 +0000199 auto Info = find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000200 assert(Info != Insts.end() && "invalid sp adjusting instruction");
201 Info->SPAdjust += ExtraBytes;
202 }
203
204 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000205 const DebugLoc &dl, const ARMBaseInstrInfo &TII,
206 bool HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000207 unsigned CFAOffset = 0;
208 for (auto &Info : Insts) {
209 if (HasFP && !Info.BeforeFPSet)
210 return;
211
212 CFAOffset -= Info.SPAdjust;
213 unsigned CFIIndex = MMI.addFrameInst(
214 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
215 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000216 TII.get(TargetOpcode::CFI_INSTRUCTION))
217 .addCFIIndex(CFIIndex)
218 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000219 }
220 }
221};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Tim Northover603d3162014-11-14 22:45:33 +0000223
Kristof Beyls933de7a2015-01-08 15:09:14 +0000224/// Emit an instruction sequence that will align the address in
225/// register Reg by zero-ing out the lower bits. For versions of the
226/// architecture that support Neon, this must be done in a single
227/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
228/// single instruction. That function only gets called when optimizing
229/// spilling of D registers on a core with the Neon instruction set
230/// present.
231static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
232 const TargetInstrInfo &TII,
233 MachineBasicBlock &MBB,
234 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000235 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000236 const unsigned Alignment,
237 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000238 const ARMSubtarget &AST =
239 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000240 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
241 const unsigned AlignMask = Alignment - 1;
242 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
243 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
244 if (!AFI->isThumbFunction()) {
245 // if the BFC instruction is available, use that to zero the lower
246 // bits:
247 // bfc Reg, #0, log2(Alignment)
248 // otherwise use BIC, if the mask to zero the required number of bits
249 // can be encoded in the bic immediate field
250 // bic Reg, Reg, Alignment-1
251 // otherwise, emit
252 // lsr Reg, Reg, log2(Alignment)
253 // lsl Reg, Reg, log2(Alignment)
254 if (CanUseBFC) {
255 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
256 .addReg(Reg, RegState::Kill)
257 .addImm(~AlignMask));
258 } else if (AlignMask <= 255) {
259 AddDefaultCC(
260 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
261 .addReg(Reg, RegState::Kill)
262 .addImm(AlignMask)));
263 } else {
264 assert(!MustBeSingleInstruction &&
265 "Shouldn't call emitAligningInstructions demanding a single "
266 "instruction to be emitted for large stack alignment for a target "
267 "without BFC.");
268 AddDefaultCC(AddDefaultPred(
269 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
270 .addReg(Reg, RegState::Kill)
271 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
272 AddDefaultCC(AddDefaultPred(
273 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
274 .addReg(Reg, RegState::Kill)
275 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
276 }
277 } else {
278 // Since this is only reached for Thumb-2 targets, the BFC instruction
279 // should always be available.
280 assert(CanUseBFC);
281 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
282 .addReg(Reg, RegState::Kill)
283 .addImm(~AlignMask));
284 }
285}
286
Quentin Colombet61b305e2015-05-05 17:38:16 +0000287void ARMFrameLowering::emitPrologue(MachineFunction &MF,
288 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000289 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000290 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000291 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000292 MachineModuleInfo &MMI = MF.getMMI();
293 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000294 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000295 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000296 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
297 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000298 assert(!AFI->isThumb1OnlyFunction() &&
299 "This emitPrologue does not support Thumb1!");
300 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000301 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000302 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000303 unsigned NumBytes = MFI.getStackSize();
304 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000305
306 // Debug location must be unknown since the first debug location is used
307 // to determine the end of the prologue.
308 DebugLoc dl;
309
310 unsigned FramePtr = RegInfo->getFrameRegister(MF);
311
312 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000313 // belongs to which callee-save spill areas.
314 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
315 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000316 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000317
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000318 // All calls are tail calls in GHC calling conv, and functions have no
319 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000320 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
321 return;
322
Tim Northover603d3162014-11-14 22:45:33 +0000323 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000324 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000325
Oliver Stannardd55e1152014-03-05 15:25:27 +0000326 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000327 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000328 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000329 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000330 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000331 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000332
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000333 if (!AFI->hasStackFrame() &&
334 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000335 if (NumBytes - ArgRegsSaveSize != 0) {
336 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000337 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000338 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
339 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000340 }
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000341 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000342 return;
343 }
344
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000345 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000346 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
347 unsigned Reg = CSI[i].getReg();
348 int FI = CSI[i].getFrameIdx();
349 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000350 case ARM::R8:
351 case ARM::R9:
352 case ARM::R10:
353 case ARM::R11:
354 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000355 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000356 GPRCS2Size += 4;
357 break;
358 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000359 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000360 case ARM::R0:
361 case ARM::R1:
362 case ARM::R2:
363 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000364 case ARM::R4:
365 case ARM::R5:
366 case ARM::R6:
367 case ARM::R7:
368 case ARM::LR:
369 if (Reg == FramePtr)
370 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000371 GPRCS1Size += 4;
372 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000373 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000374 // This is a DPR. Exclude the aligned DPRCS2 spills.
375 if (Reg == ARM::D8)
376 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000377 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000378 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000379 }
380 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000381
Eric Christopherb006fc92010-11-18 19:40:05 +0000382 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000383 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
384 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000385 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000386 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
387 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000388
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000389 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000390 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
391 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
392 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
393 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
394 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000395 int FramePtrOffsetInPush = 0;
396 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000397 FramePtrOffsetInPush =
Matthias Braun941a7052016-07-28 18:40:00 +0000398 MFI.getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
399 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000400 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000401 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000402 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
403 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
404 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
405
Tim Northoverc9432eb2013-11-04 23:04:15 +0000406 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000407 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000408 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000409 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
410 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000411
Tim Northover228c9432014-11-05 00:27:13 +0000412 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
413 // .cfi_offset operations will reflect that.
414 if (DPRGapSize) {
415 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000416 if (LastPush != MBB.end() &&
417 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000418 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
419 else {
Tim Northover228c9432014-11-05 00:27:13 +0000420 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
421 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000422 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
423 }
Tim Northover228c9432014-11-05 00:27:13 +0000424 }
425
Eric Christopherb006fc92010-11-18 19:40:05 +0000426 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000427 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000428 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000429 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000430 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000431 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000432 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000433 }
Evan Cheng70d29632011-02-25 00:24:46 +0000434 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000435
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000436 // Move past the aligned DPRCS2 area.
437 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
438 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
439 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
440 // leaves the stack pointer pointing to the DPRCS2 area.
441 //
442 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000443 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000444 } else
445 NumBytes = DPRCSOffset;
446
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000447 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
448 uint32_t NumWords = NumBytes >> 2;
449
450 if (NumWords < 65536)
451 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000452 .addImm(NumWords)
453 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000454 else
455 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000456 .addImm(NumWords)
457 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000458
459 switch (TM.getCodeModel()) {
460 case CodeModel::Small:
461 case CodeModel::Medium:
462 case CodeModel::Default:
463 case CodeModel::Kernel:
464 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
465 .addImm((unsigned)ARMCC::AL).addReg(0)
466 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000467 .addReg(ARM::R4, RegState::Implicit)
468 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000469 break;
470 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000471 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000472 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000473 .addExternalSymbol("__chkstk")
474 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000475
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000476 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
477 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000478 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000479 .addReg(ARM::R4, RegState::Implicit)
480 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000481 break;
482 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000483
484 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
485 ARM::SP)
Saleem Abdulrasool96115182016-04-24 20:12:48 +0000486 .addReg(ARM::SP, RegState::Kill)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000487 .addReg(ARM::R4, RegState::Kill)
488 .setMIFlags(MachineInstr::FrameSetup)));
489 NumBytes = 0;
490 }
491
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000492 if (NumBytes) {
493 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000494 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000495 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000496 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
497 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000498 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
499 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000500 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
501 }
Tim Northover93bcc662013-11-08 17:18:07 +0000502
Evan Chengeb56dca2010-11-22 18:12:04 +0000503 if (HasFP && isARM)
504 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
505 // Note it's not safe to do this in Thumb2 mode because it would have
506 // taken two instructions:
507 // mov sp, r7
508 // sub sp, #24
509 // If an interrupt is taken between the two instructions, then sp is in
510 // an inconsistent state (pointing to the middle of callee-saved area).
511 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000512 AFI->setShouldRestoreSPFromFP(true);
513 }
514
Tim Northover603d3162014-11-14 22:45:33 +0000515 // Set FP to point to the stack slot that contains the previous FP.
516 // For iOS, FP is R7, which has now been stored in spill area 1.
517 // Otherwise, if this is not iOS, all the callee-saved registers go
518 // into spill area 1, including the FP in R11. In either case, it
519 // is in area one and the adjustment needs to take place just after
520 // that push.
521 if (HasFP) {
522 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000523 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000524 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
525 dl, TII, FramePtr, ARM::SP,
526 PushSize + FramePtrOffsetInPush,
527 MachineInstr::FrameSetup);
528 if (FramePtrOffsetInPush + PushSize != 0) {
529 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
530 nullptr, MRI->getDwarfRegNum(FramePtr, true),
531 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
532 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000533 .addCFIIndex(CFIIndex)
534 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000535 } else {
536 unsigned CFIIndex =
537 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
538 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
539 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000540 .addCFIIndex(CFIIndex)
541 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000542 }
543 }
544
545 // Now that the prologue's actual instructions are finalised, we can insert
546 // the necessary DWARF cf instructions to describe the situation. Start by
547 // recording where each register ended up:
548 if (GPRCS1Size > 0) {
549 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
550 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000551 for (const auto &Entry : CSI) {
552 unsigned Reg = Entry.getReg();
553 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000554 switch (Reg) {
555 case ARM::R8:
556 case ARM::R9:
557 case ARM::R10:
558 case ARM::R11:
559 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000560 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000561 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000562 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000563 case ARM::R0:
564 case ARM::R1:
565 case ARM::R2:
566 case ARM::R3:
567 case ARM::R4:
568 case ARM::R5:
569 case ARM::R6:
570 case ARM::R7:
571 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000572 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000573 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000574 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000575 .addCFIIndex(CFIIndex)
576 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000577 break;
578 }
579 }
580 }
581
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000582 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000583 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000584 for (const auto &Entry : CSI) {
585 unsigned Reg = Entry.getReg();
586 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000587 switch (Reg) {
588 case ARM::R8:
589 case ARM::R9:
590 case ARM::R10:
591 case ARM::R11:
592 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000593 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000594 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000595 unsigned Offset = MFI.getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000596 unsigned CFIIndex = MMI.addFrameInst(
597 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
598 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000599 .addCFIIndex(CFIIndex)
600 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000601 }
602 break;
603 }
604 }
605 }
606
607 if (DPRCSSize > 0) {
608 // Since vpush register list cannot have gaps, there may be multiple vpush
609 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000610 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000611 for (const auto &Entry : CSI) {
612 unsigned Reg = Entry.getReg();
613 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000614 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
615 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
616 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000617 unsigned Offset = MFI.getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000618 unsigned CFIIndex = MMI.addFrameInst(
619 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000620 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000621 .addCFIIndex(CFIIndex)
622 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000623 }
624 }
625 }
626
Tim Northover603d3162014-11-14 22:45:33 +0000627 // Now we can emit descriptions of where the canonical frame address was
628 // throughout the process. If we have a frame pointer, it takes over the job
629 // half-way through, so only the first few .cfi_def_cfa_offset instructions
630 // actually get emitted.
631 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000632
Evan Chengeb56dca2010-11-22 18:12:04 +0000633 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000634 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
635 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000636
637 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
638 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000639 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000640 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
641
642 // If we need dynamic stack realignment, do it here. Be paranoid and make
643 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000644 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000645 // realigned.
646 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000647 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000648 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000649 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000650 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
651 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000652 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000653 // We cannot use sp as source/dest register here, thus we're using r4 to
654 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000655 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000656 // -- use emitAligningInstructions to produce best sequence to zero
657 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000658 // mov sp, r4
659 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000660 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000661 .addReg(ARM::SP, RegState::Kill));
662 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
663 false);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000664 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000665 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000666 }
667
668 AFI->setShouldRestoreSPFromFP(true);
669 }
670
671 // If we need a base pointer, set it up here. It's whatever the value
672 // of the stack pointer is at this point. Any variable size objects
673 // will be allocated after this, so we can still use the base pointer
674 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000675 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000676 if (RegInfo->hasBasePointer(MF)) {
677 if (isARM)
678 BuildMI(MBB, MBBI, dl,
679 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
680 .addReg(ARM::SP)
681 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
682 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000683 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000684 RegInfo->getBaseRegister())
685 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000686 }
687
688 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000689 // the sp from fp. We can assume there's an FP here since hasFP already
690 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000691 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000692 AFI->setShouldRestoreSPFromFP(true);
693}
694
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000695void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000696 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000697 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000698 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000699 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000700 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000701 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000702 assert(!AFI->isThumb1OnlyFunction() &&
703 "This emitEpilogue does not support Thumb1!");
704 bool isARM = !AFI->isThumbFunction();
705
Tim Northover8cda34f2015-03-11 18:54:22 +0000706 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000707 int NumBytes = (int)MFI.getStackSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000708 unsigned FramePtr = RegInfo->getFrameRegister(MF);
709
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000710 // All calls are tail calls in GHC calling conv, and functions have no
711 // prologue/epilogue.
Quentin Colombet71a71482015-07-20 21:42:14 +0000712 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000713 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000714
715 // First put ourselves on the first (from top) terminator instructions.
716 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
717 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000718
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000719 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000720 if (NumBytes - ArgRegsSaveSize != 0)
721 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000722 } else {
723 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000724 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000725 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000726 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000727 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000728 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
729 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000730 ++MBBI;
731 }
732
733 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000734 NumBytes -= (ArgRegsSaveSize +
735 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000736 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000737 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000738 AFI->getDPRCalleeSavedAreaSize());
739
740 // Reset SP based on frame pointer only if the stack frame extends beyond
741 // frame pointer stack slot or target is ELF and the function has FP.
742 if (AFI->shouldRestoreSPFromFP()) {
743 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
744 if (NumBytes) {
745 if (isARM)
746 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
747 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000748 else {
749 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000750 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000751 // mov sp, r7
752 // sub sp, #24
753 // This is bad, if an interrupt is taken after the mov, sp is in an
754 // inconsistent state.
755 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000756 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000757 "No scratch register to restore SP from FP!");
758 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000759 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000760 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000761 ARM::SP)
762 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000763 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000764 } else {
765 // Thumb2 or ARM.
766 if (isARM)
767 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
768 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
769 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000770 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000771 ARM::SP)
772 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000773 }
Tim Northoverdee86042013-12-02 14:46:26 +0000774 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000775 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
776 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000777
Eric Christopherb006fc92010-11-18 19:40:05 +0000778 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000779 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000780 MBBI++;
781 // Since vpop register list cannot have gaps, there may be multiple vpop
782 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000783 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000784 MBBI++;
785 }
Tim Northover228c9432014-11-05 00:27:13 +0000786 if (AFI->getDPRCalleeSavedGapSize()) {
787 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
788 "unexpected DPR alignment gap");
789 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
790 }
791
Eric Christopherb006fc92010-11-18 19:40:05 +0000792 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
793 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000794 }
795
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000796 if (ArgRegsSaveSize)
797 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000798}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000799
Bob Wilson657f2272011-01-13 21:10:12 +0000800/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
801/// debug info. It's the same as what we use for resolving the code-gen
802/// references for now. FIXME: This can go wrong when references are
803/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000804int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000805ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000806 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000807 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
808}
809
810int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000811ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000812 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000813 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000814 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000815 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000816 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000817 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000818 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000819 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000820 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000821
822 FrameReg = ARM::SP;
823 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000824
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000825 // SP can move around if there are allocas. We may also lose track of SP
826 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000827 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000828
Anton Korobeynikov46877782010-11-20 15:59:32 +0000829 // When dynamically realigning the stack, use the frame pointer for
830 // parameters, and the stack/base pointer for locals.
831 if (RegInfo->needsStackRealignment(MF)) {
832 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
833 if (isFixed) {
834 FrameReg = RegInfo->getFrameRegister(MF);
835 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000836 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000837 assert(RegInfo->hasBasePointer(MF) &&
838 "VLAs and dynamic stack alignment, but missing base pointer!");
839 FrameReg = RegInfo->getBaseRegister();
840 }
841 return Offset;
842 }
843
844 // If there is a frame pointer, use it when we can.
845 if (hasFP(MF) && AFI->hasStackFrame()) {
846 // Use frame pointer to reference fixed objects. Use it for locals if
847 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000848 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000849 FrameReg = RegInfo->getFrameRegister(MF);
850 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000851 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000852 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000853 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000854 // Try to use the frame pointer if we can, else use the base pointer
855 // since it's available. This is handy for the emergency spill slot, in
856 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000857 if (FPOffset >= -255 && FPOffset < 0) {
858 FrameReg = RegInfo->getFrameRegister(MF);
859 return FPOffset;
860 }
Evan Chengc0d20042011-04-22 01:42:52 +0000861 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000862 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000863 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000864 // ldr <rd>, [sp, #<imm8>]
865 // if at all possible to save space.
866 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
867 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000868 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000869 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000870 if (FPOffset >= -255 && FPOffset < 0) {
871 FrameReg = RegInfo->getFrameRegister(MF);
872 return FPOffset;
873 }
874 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
875 // Otherwise, use SP or FP, whichever is closer to the stack slot.
876 FrameReg = RegInfo->getFrameRegister(MF);
877 return FPOffset;
878 }
879 }
880 // Use the base pointer if we have one.
881 if (RegInfo->hasBasePointer(MF))
882 FrameReg = RegInfo->getBaseRegister();
883 return Offset;
884}
885
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000886void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000887 MachineBasicBlock::iterator MI,
888 const std::vector<CalleeSavedInfo> &CSI,
889 unsigned StmOpc, unsigned StrOpc,
890 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000891 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000892 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000893 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000894 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000895 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000896 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000897
898 DebugLoc DL;
899
Tim Northover46a6f0f2016-11-14 20:28:24 +0000900 typedef std::pair<unsigned, bool> RegAndKill;
901 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000902 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000903 while (i != 0) {
904 unsigned LastReg = 0;
905 for (; i != 0; --i) {
906 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000907 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000908
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000909 // D-registers in the aligned area DPRCS2 are NOT spilled here.
910 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
911 continue;
912
Matthias Braun707e02c2016-04-13 21:43:25 +0000913 bool isLiveIn = MF.getRegInfo().isLiveIn(Reg);
914 if (!isLiveIn)
Evan Cheng775ead32010-12-07 23:08:38 +0000915 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000916 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000917 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000918 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000919 if (NoGap && LastReg && LastReg != Reg-1)
920 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000921 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +0000922 // Do not set a kill flag on values that are also marked as live-in. This
923 // happens with the @llvm-returnaddress intrinsic and with arguments
924 // passed in callee saved registers.
925 // Omitting the kill flags is conservatively correct even if the live-in
926 // is not used after all.
927 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000928 }
929
Jim Grosbach5fccad82010-12-09 18:31:13 +0000930 if (Regs.empty())
931 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +0000932
933 std::sort(Regs.begin(), Regs.end(), [&](RegAndKill &LHS, RegAndKill &RHS) {
934 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
935 });
936
Jim Grosbach5fccad82010-12-09 18:31:13 +0000937 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000938 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000939 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000940 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000941 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
942 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000943 } else if (Regs.size() == 1) {
944 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
945 ARM::SP)
946 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000947 .addReg(ARM::SP).setMIFlags(MIFlags)
948 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000949 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000950 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000951 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000952
953 // Put any subsequent vpush instructions before this one: they will refer to
954 // higher register numbers so need to be pushed first in order to preserve
955 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +0000956 if (MI != MBB.begin())
957 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000958 }
Evan Cheng775ead32010-12-07 23:08:38 +0000959}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000960
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000961void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000962 MachineBasicBlock::iterator MI,
963 const std::vector<CalleeSavedInfo> &CSI,
964 unsigned LdmOpc, unsigned LdrOpc,
965 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000966 bool(*Func)(unsigned, bool),
967 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000968 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000969 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000970 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +0000971 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +0000972 DebugLoc DL;
973 bool isTailCall = false;
974 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +0000975 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +0000976 if (MBB.end() != MI) {
977 DL = MI->getDebugLoc();
978 unsigned RetOpcode = MI->getOpcode();
979 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
980 isInterrupt =
981 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +0000982 isTrap =
983 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
984 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +0000985 }
Evan Cheng775ead32010-12-07 23:08:38 +0000986
987 SmallVector<unsigned, 4> Regs;
988 unsigned i = CSI.size();
989 while (i != 0) {
990 unsigned LastReg = 0;
991 bool DeleteRet = false;
992 for (; i != 0; --i) {
993 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000994 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000995
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000996 // The aligned reloads from area DPRCS2 are not inserted here.
997 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
998 continue;
999
Tim Northoverd8407452013-10-01 14:33:28 +00001000 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001001 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001002 if (MBB.succ_empty()) {
1003 Reg = ARM::PC;
1004 DeleteRet = true;
1005 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1006 } else
1007 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001008 // Fold the return instruction into the LDM.
Evan Cheng775ead32010-12-07 23:08:38 +00001009 }
1010
Evan Cheng9d54ae62010-12-08 06:29:02 +00001011 // If NoGap is true, pop consecutive registers and then leave the rest
1012 // for other instructions. e.g.
1013 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1014 if (NoGap && LastReg && LastReg != Reg-1)
1015 break;
1016
Evan Cheng775ead32010-12-07 23:08:38 +00001017 LastReg = Reg;
1018 Regs.push_back(Reg);
1019 }
1020
Jim Grosbach5fccad82010-12-09 18:31:13 +00001021 if (Regs.empty())
1022 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001023
1024 std::sort(Regs.begin(), Regs.end(), [&](unsigned LHS, unsigned RHS) {
1025 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1026 });
1027
Jim Grosbach5fccad82010-12-09 18:31:13 +00001028 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +00001029 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +00001030 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +00001031 .addReg(ARM::SP));
1032 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1033 MIB.addReg(Regs[i], getDefRegState(true));
Quentin Colombet71a71482015-07-20 21:42:14 +00001034 if (DeleteRet && MI != MBB.end()) {
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001035 MIB.copyImplicitOps(*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001036 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001037 }
Evan Cheng775ead32010-12-07 23:08:38 +00001038 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001039 } else if (Regs.size() == 1) {
1040 // If we adjusted the reg to PC from LR above, switch it back here. We
1041 // only do that for LDM.
1042 if (Regs[0] == ARM::PC)
1043 Regs[0] = ARM::LR;
1044 MachineInstrBuilder MIB =
1045 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1046 .addReg(ARM::SP, RegState::Define)
1047 .addReg(ARM::SP);
1048 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1049 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001050 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001051 MIB.addReg(0);
1052 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1053 } else
1054 MIB.addImm(4);
1055 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +00001056 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001057 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001058
1059 // Put any subsequent vpop instructions after this one: they will refer to
1060 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001061 if (MI != MBB.end())
1062 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001063 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001064}
1065
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001066/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001067/// starting from d8. Also insert stack realignment code and leave the stack
1068/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001069static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1070 MachineBasicBlock::iterator MI,
1071 unsigned NumAlignedDPRCS2Regs,
1072 const std::vector<CalleeSavedInfo> &CSI,
1073 const TargetRegisterInfo *TRI) {
1074 MachineFunction &MF = *MBB.getParent();
1075 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001076 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001077 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001078 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001079
1080 // Mark the D-register spill slots as properly aligned. Since MFI computes
1081 // stack slot layout backwards, this can actually mean that the d-reg stack
1082 // slot offsets can be wrong. The offset for d8 will always be correct.
1083 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1084 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001085 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001086 continue;
1087 int FI = CSI[i].getFrameIdx();
1088 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1089 // registers will be 8-byte aligned.
1090 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1091
1092 // The stack slot for D8 needs to be maximally aligned because this is
1093 // actually the point where we align the stack pointer. MachineFrameInfo
1094 // computes all offsets relative to the incoming stack pointer which is a
1095 // bit weird when realigning the stack. Any extra padding for this
1096 // over-alignment is not realized because the code inserted below adjusts
1097 // the stack pointer by numregs * 8 before aligning the stack pointer.
1098 if (DNum == 0)
1099 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1100 }
1101
1102 // Move the stack pointer to the d8 spill slot, and align it at the same
1103 // time. Leave the stack slot address in the scratch register r4.
1104 //
1105 // sub r4, sp, #numregs * 8
1106 // bic r4, r4, #align - 1
1107 // mov sp, r4
1108 //
1109 bool isThumb = AFI->isThumbFunction();
1110 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1111 AFI->setShouldRestoreSPFromFP(true);
1112
1113 // sub r4, sp, #numregs * 8
1114 // The immediate is <= 64, so it doesn't need any special encoding.
1115 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1116 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +00001117 .addReg(ARM::SP)
1118 .addImm(8 * NumAlignedDPRCS2Regs)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001119
Matthias Braun941a7052016-07-28 18:40:00 +00001120 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001121 // We must set parameter MustBeSingleInstruction to true, since
1122 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1123 // stack alignment. Luckily, this can always be done since all ARM
1124 // architecture versions that support Neon also support the BFC
1125 // instruction.
1126 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001127
1128 // mov sp, r4
1129 // The stack pointer must be adjusted before spilling anything, otherwise
1130 // the stack slots could be clobbered by an interrupt handler.
1131 // Leave r4 live, it is used below.
1132 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1133 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1134 .addReg(ARM::R4);
1135 MIB = AddDefaultPred(MIB);
1136 if (!isThumb)
1137 AddDefaultCC(MIB);
1138
1139 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1140 // r4 holds the stack slot address.
1141 unsigned NextReg = ARM::D8;
1142
1143 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1144 // The writeback is only needed when emitting two vst1.64 instructions.
1145 if (NumAlignedDPRCS2Regs >= 6) {
1146 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001147 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001148 MBB.addLiveIn(SupReg);
1149 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1150 ARM::R4)
1151 .addReg(ARM::R4, RegState::Kill).addImm(16)
1152 .addReg(NextReg)
1153 .addReg(SupReg, RegState::ImplicitKill));
1154 NextReg += 4;
1155 NumAlignedDPRCS2Regs -= 4;
1156 }
1157
1158 // We won't modify r4 beyond this point. It currently points to the next
1159 // register to be spilled.
1160 unsigned R4BaseReg = NextReg;
1161
1162 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1163 if (NumAlignedDPRCS2Regs >= 4) {
1164 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001165 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001166 MBB.addLiveIn(SupReg);
1167 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1168 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1169 .addReg(SupReg, RegState::ImplicitKill));
1170 NextReg += 4;
1171 NumAlignedDPRCS2Regs -= 4;
1172 }
1173
1174 // 16-byte aligned vst1.64 with 2 d-regs.
1175 if (NumAlignedDPRCS2Regs >= 2) {
1176 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001177 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001178 MBB.addLiveIn(SupReg);
1179 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001180 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001181 NextReg += 2;
1182 NumAlignedDPRCS2Regs -= 2;
1183 }
1184
1185 // Finally, use a vanilla vstr.64 for the odd last register.
1186 if (NumAlignedDPRCS2Regs) {
1187 MBB.addLiveIn(NextReg);
1188 // vstr.64 uses addrmode5 which has an offset scale of 4.
1189 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1190 .addReg(NextReg)
1191 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1192 }
1193
1194 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001195 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001196}
1197
1198/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1199/// iterator to the following instruction.
1200static MachineBasicBlock::iterator
1201skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1202 unsigned NumAlignedDPRCS2Regs) {
1203 // sub r4, sp, #numregs * 8
1204 // bic r4, r4, #align - 1
1205 // mov sp, r4
1206 ++MI; ++MI; ++MI;
1207 assert(MI->mayStore() && "Expecting spill instruction");
1208
1209 // These switches all fall through.
1210 switch(NumAlignedDPRCS2Regs) {
1211 case 7:
1212 ++MI;
1213 assert(MI->mayStore() && "Expecting spill instruction");
1214 default:
1215 ++MI;
1216 assert(MI->mayStore() && "Expecting spill instruction");
1217 case 1:
1218 case 2:
1219 case 4:
1220 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1221 ++MI;
1222 }
1223 return MI;
1224}
1225
1226/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1227/// starting from d8. These instructions are assumed to execute while the
1228/// stack is still aligned, unlike the code inserted by emitPopInst.
1229static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1230 MachineBasicBlock::iterator MI,
1231 unsigned NumAlignedDPRCS2Regs,
1232 const std::vector<CalleeSavedInfo> &CSI,
1233 const TargetRegisterInfo *TRI) {
1234 MachineFunction &MF = *MBB.getParent();
1235 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001236 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001237 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001238
1239 // Find the frame index assigned to d8.
1240 int D8SpillFI = 0;
1241 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1242 if (CSI[i].getReg() == ARM::D8) {
1243 D8SpillFI = CSI[i].getFrameIdx();
1244 break;
1245 }
1246
1247 // Materialize the address of the d8 spill slot into the scratch register r4.
1248 // This can be fairly complicated if the stack frame is large, so just use
1249 // the normal frame index elimination mechanism to do it. This code runs as
1250 // the initial part of the epilog where the stack and base pointers haven't
1251 // been changed yet.
1252 bool isThumb = AFI->isThumbFunction();
1253 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1254
1255 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1256 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1257 .addFrameIndex(D8SpillFI).addImm(0)));
1258
1259 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1260 unsigned NextReg = ARM::D8;
1261
1262 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1263 if (NumAlignedDPRCS2Regs >= 6) {
1264 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001265 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001266 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1267 .addReg(ARM::R4, RegState::Define)
1268 .addReg(ARM::R4, RegState::Kill).addImm(16)
1269 .addReg(SupReg, RegState::ImplicitDefine));
1270 NextReg += 4;
1271 NumAlignedDPRCS2Regs -= 4;
1272 }
1273
1274 // We won't modify r4 beyond this point. It currently points to the next
1275 // register to be spilled.
1276 unsigned R4BaseReg = NextReg;
1277
1278 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1279 if (NumAlignedDPRCS2Regs >= 4) {
1280 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001281 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001282 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1283 .addReg(ARM::R4).addImm(16)
1284 .addReg(SupReg, RegState::ImplicitDefine));
1285 NextReg += 4;
1286 NumAlignedDPRCS2Regs -= 4;
1287 }
1288
1289 // 16-byte aligned vld1.64 with 2 d-regs.
1290 if (NumAlignedDPRCS2Regs >= 2) {
1291 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001292 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001293 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1294 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001295 NextReg += 2;
1296 NumAlignedDPRCS2Regs -= 2;
1297 }
1298
1299 // Finally, use a vanilla vldr.64 for the remaining odd register.
1300 if (NumAlignedDPRCS2Regs)
1301 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1302 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1303
1304 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001305 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001306}
1307
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001308bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001309 MachineBasicBlock::iterator MI,
1310 const std::vector<CalleeSavedInfo> &CSI,
1311 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001312 if (CSI.empty())
1313 return false;
1314
1315 MachineFunction &MF = *MBB.getParent();
1316 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001317
1318 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001319 unsigned PushOneOpc = AFI->isThumbFunction() ?
1320 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001321 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001322 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1323 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001324 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001325 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001326 MachineInstr::FrameSetup);
1327 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001328 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1329
1330 // The code above does not insert spill code for the aligned DPRCS2 registers.
1331 // The stack realignment code will be inserted between the push instructions
1332 // and these spills.
1333 if (NumAlignedDPRCS2Regs)
1334 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001335
1336 return true;
1337}
1338
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001339bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001340 MachineBasicBlock::iterator MI,
1341 const std::vector<CalleeSavedInfo> &CSI,
1342 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001343 if (CSI.empty())
1344 return false;
1345
1346 MachineFunction &MF = *MBB.getParent();
1347 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001348 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001349 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1350
1351 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1352 // registers. Do that here instead.
1353 if (NumAlignedDPRCS2Regs)
1354 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001355
1356 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001357 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001358 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001359 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1360 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001361 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001362 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001363 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001364 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001365
1366 return true;
1367}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001368
1369// FIXME: Make generic?
1370static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1371 const ARMBaseInstrInfo &TII) {
1372 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001373 for (auto &MBB : MF) {
1374 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001375 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001376 }
1377 return FnSize;
1378}
1379
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001380/// estimateRSStackSizeLimit - Look at each instruction that references stack
1381/// frames and return the stack size limit beyond which some of these
1382/// instructions will require a scratch register during their expansion later.
1383// FIXME: Move to TII?
1384static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001385 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001386 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1387 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001388 for (auto &MBB : MF) {
1389 for (auto &MI : MBB) {
1390 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1391 if (!MI.getOperand(i).isFI())
1392 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001393
1394 // When using ADDri to get the address of a stack object, 255 is the
1395 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001396 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001397 Limit = std::min(Limit, (1U << 8) - 1);
1398 break;
1399 }
1400
1401 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001402 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001403 case ARMII::AddrMode3:
1404 case ARMII::AddrModeT2_i8:
1405 Limit = std::min(Limit, (1U << 8) - 1);
1406 break;
1407 case ARMII::AddrMode5:
1408 case ARMII::AddrModeT2_i8s4:
1409 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1410 break;
1411 case ARMII::AddrModeT2_i12:
1412 // i12 supports only positive offset so these will be converted to
1413 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1414 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1415 Limit = std::min(Limit, (1U << 8) - 1);
1416 break;
1417 case ARMII::AddrMode4:
1418 case ARMII::AddrMode6:
1419 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1420 // immediate offset for stack references.
1421 return 0;
1422 default:
1423 break;
1424 }
1425 break; // At most one FI per instruction
1426 }
1427 }
1428 }
1429
1430 return Limit;
1431}
1432
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001433// In functions that realign the stack, it can be an advantage to spill the
1434// callee-saved vector registers after realigning the stack. The vst1 and vld1
1435// instructions take alignment hints that can improve performance.
1436//
Matthias Braun02564862015-07-14 17:17:13 +00001437static void
1438checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001439 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1440 if (!SpillAlignedNEONRegs)
1441 return;
1442
1443 // Naked functions don't spill callee-saved registers.
Duncan P. N. Exon Smith2cff9e12015-02-14 02:24:44 +00001444 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001445 return;
1446
1447 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001448 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001449 return;
1450
1451 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001452 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001453 return;
1454
1455 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001456 if (!static_cast<const ARMBaseRegisterInfo *>(
1457 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001458 return;
1459
1460 // We always spill contiguous d-registers starting from d8. Count how many
1461 // needs spilling. The register allocator will almost always use the
1462 // callee-saved registers in order, but it can happen that there are holes in
1463 // the range. Registers above the hole will be spilled to the standard DPRCS
1464 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001465 unsigned NumSpills = 0;
1466 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001467 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001468 break;
1469
1470 // Don't do this for just one d-register. It's not worth it.
1471 if (NumSpills < 2)
1472 return;
1473
1474 // Spill the first NumSpills D-registers after realigning the stack.
1475 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1476
1477 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001478 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001479}
1480
Matthias Braun02564862015-07-14 17:17:13 +00001481void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1482 BitVector &SavedRegs,
1483 RegScavenger *RS) const {
1484 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001485 // This tells PEI to spill the FP as if it is any other callee-save register
1486 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1487 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1488 // to combine multiple loads / stores.
1489 bool CanEliminateFrame = true;
1490 bool CS1Spilled = false;
1491 bool LRSpilled = false;
1492 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001493 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001494 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1495 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001496 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001497 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001498 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001499 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001500 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001501 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001502 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001503 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1504 (void)TRI; // Silence unused warning in non-assert builds.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001505 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1506
1507 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1508 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001509 // since it's not always possible to restore sp from fp in a single
1510 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001511 // FIXME: It will be better just to find spare register here.
1512 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001513 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001514 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001515
Evan Cheng572756a2011-01-16 05:14:33 +00001516 if (AFI->isThumb1OnlyFunction()) {
1517 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001518 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001519 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001520
Jim Grosbachdca85312011-06-13 21:18:25 +00001521 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1522 // for sure what the stack size will be, but for this, an estimate is good
1523 // enough. If there anything changes it, it'll be a spill, which implies
1524 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001525 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001526 // FIXME: It will be better just to find spare register here.
Matthias Braun941a7052016-07-28 18:40:00 +00001527 unsigned StackSize = MFI.estimateStackSize(MF);
1528 if (MFI.hasVarSizedObjects() || StackSize > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001529 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001530 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001531
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001532 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001533 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001534
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001535 // Spill the BasePtr if it's used.
1536 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001537 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001538
1539 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001540 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001541 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001542 for (unsigned i = 0; CSRegs[i]; ++i) {
1543 unsigned Reg = CSRegs[i];
1544 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001545 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001546 Spilled = true;
1547 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001548 }
1549
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001550 if (!ARM::GPRRegClass.contains(Reg)) {
1551 if (Spilled) {
1552 if (ARM::SPRRegClass.contains(Reg))
1553 NumFPRSpills++;
1554 else if (ARM::DPRRegClass.contains(Reg))
1555 NumFPRSpills += 2;
1556 else if (ARM::QPRRegClass.contains(Reg))
1557 NumFPRSpills += 4;
1558 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001559 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001560 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001561
1562 if (Spilled) {
1563 NumGPRSpills++;
1564
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001565 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001566 if (Reg == ARM::LR)
1567 LRSpilled = true;
1568 CS1Spilled = true;
1569 continue;
1570 }
1571
1572 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1573 switch (Reg) {
1574 case ARM::LR:
1575 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001576 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001577 case ARM::R0: case ARM::R1:
1578 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001579 case ARM::R4: case ARM::R5:
1580 case ARM::R6: case ARM::R7:
1581 CS1Spilled = true;
1582 break;
1583 default:
1584 break;
1585 }
1586 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001587 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001588 UnspilledCS1GPRs.push_back(Reg);
1589 continue;
1590 }
1591
1592 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001593 case ARM::R0: case ARM::R1:
1594 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001595 case ARM::R4: case ARM::R5:
1596 case ARM::R6: case ARM::R7:
1597 case ARM::LR:
1598 UnspilledCS1GPRs.push_back(Reg);
1599 break;
1600 default:
1601 UnspilledCS2GPRs.push_back(Reg);
1602 break;
1603 }
1604 }
1605 }
1606
1607 bool ForceLRSpill = false;
1608 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1609 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1610 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1611 // use of BL to implement far jump. If it turns out that it's not needed
1612 // then the branch fix up path will undo it.
1613 if (FnSize >= (1 << 11)) {
1614 CanEliminateFrame = false;
1615 ForceLRSpill = true;
1616 }
1617 }
1618
1619 // If any of the stack slot references may be out of range of an immediate
1620 // offset, make sure a register (or a spill slot) is available for the
1621 // register scavenger. Note that if we're indexing off the frame pointer, the
1622 // effective stack size is 4 bytes larger since the FP points to the stack
1623 // slot of the previous FP. Also, if we have variable sized objects in the
1624 // function, stack slot references will often be negative, and some of
1625 // our instructions are positive-offset only, so conservatively consider
1626 // that case to want a spill slot (or register) as well. Similarly, if
1627 // the function adjusts the stack pointer during execution and the
1628 // adjustments aren't already part of our stack size estimate, our offset
1629 // calculations may be off, so be conservative.
1630 // FIXME: We could add logic to be more precise about negative offsets
1631 // and which instructions will need a scratch register for them. Is it
1632 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001633 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001634 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001635 if (hasFP(MF)) {
1636 if (AFI->hasStackFrame())
1637 EstimatedStackSize += 4;
1638 } else {
1639 // If FP is not used, SP will be used to access arguments, so count the
1640 // size of arguments into the estimation.
1641 EstimatedStackSize += MF.getInfo<ARMFunctionInfo>()->getArgumentStackSize();
1642 }
1643 EstimatedStackSize += 16; // For possible paddings.
1644
1645 bool BigStack = EstimatedStackSize >= estimateRSStackSizeLimit(MF, this) ||
Matthias Braun941a7052016-07-28 18:40:00 +00001646 MFI.hasVarSizedObjects() ||
1647 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001648 bool ExtraCSSpill = false;
1649 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1650 AFI->setHasStackFrame(true);
1651
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001652 if (hasFP(MF)) {
1653 SavedRegs.set(FramePtr);
1654 // If the frame pointer is required by the ABI, also spill LR so that we
1655 // emit a complete frame record.
1656 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1657 SavedRegs.set(ARM::LR);
1658 LRSpilled = true;
1659 NumGPRSpills++;
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001660 auto LRPos = find(UnspilledCS1GPRs, ARM::LR);
1661 if (LRPos != UnspilledCS1GPRs.end())
1662 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001663 }
1664 auto FPPos = find(UnspilledCS1GPRs, FramePtr);
1665 if (FPPos != UnspilledCS1GPRs.end())
1666 UnspilledCS1GPRs.erase(FPPos);
1667 NumGPRSpills++;
1668 if (FramePtr == ARM::R7)
1669 CS1Spilled = true;
1670 }
1671
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001672 if (AFI->isThumb1OnlyFunction()) {
1673 // For Thumb1-only targets, we need some low registers when we save and
1674 // restore the high registers (which aren't allocatable, but could be
1675 // used by inline assembly) because the push/pop instructions can not
1676 // access high registers. If necessary, we might need to push more low
1677 // registers to ensure that there is at least one free that can be used
1678 // for the saving & restoring, and preferably we should ensure that as
1679 // many as are needed are available so that fewer push/pop instructions
1680 // are required.
1681
1682 // Low registers which are not currently pushed, but could be (r4-r7).
1683 SmallVector<unsigned, 4> AvailableRegs;
1684
1685 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1686 // free.
1687 int EntryRegDeficit = 0;
1688 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1689 if (!MF.getRegInfo().isLiveIn(Reg)) {
1690 --EntryRegDeficit;
1691 DEBUG(dbgs() << PrintReg(Reg, TRI)
1692 << " is unused argument register, EntryRegDeficit = "
1693 << EntryRegDeficit << "\n");
1694 }
1695 }
1696
1697 // Unused return registers can be clobbered in the epilogue for free.
1698 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1699 DEBUG(dbgs() << AFI->getReturnRegsCount()
1700 << " return regs used, ExitRegDeficit = " << ExitRegDeficit
1701 << "\n");
1702
1703 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1704 DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1705
1706 // r4-r6 can be used in the prologue if they are pushed by the first push
1707 // instruction.
1708 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1709 if (SavedRegs.test(Reg)) {
1710 --RegDeficit;
1711 DEBUG(dbgs() << PrintReg(Reg, TRI)
1712 << " is saved low register, RegDeficit = " << RegDeficit
1713 << "\n");
1714 } else {
1715 AvailableRegs.push_back(Reg);
1716 DEBUG(dbgs()
1717 << PrintReg(Reg, TRI)
1718 << " is non-saved low register, adding to AvailableRegs\n");
1719 }
1720 }
1721
1722 // r7 can be used if it is not being used as the frame pointer.
1723 if (!hasFP(MF)) {
1724 if (SavedRegs.test(ARM::R7)) {
1725 --RegDeficit;
1726 DEBUG(dbgs() << "%R7 is saved low register, RegDeficit = "
1727 << RegDeficit << "\n");
1728 } else {
1729 AvailableRegs.push_back(ARM::R7);
1730 DEBUG(dbgs()
1731 << "%R7 is non-saved low register, adding to AvailableRegs\n");
1732 }
1733 }
1734
1735 // Each of r8-r11 needs to be copied to a low register, then pushed.
1736 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1737 if (SavedRegs.test(Reg)) {
1738 ++RegDeficit;
1739 DEBUG(dbgs() << PrintReg(Reg, TRI)
1740 << " is saved high register, RegDeficit = " << RegDeficit
1741 << "\n");
1742 }
1743 }
1744
1745 // LR can only be used by PUSH, not POP, and can't be used at all if the
1746 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1747 // are more limited at function entry than exit.
1748 if ((EntryRegDeficit > ExitRegDeficit) &&
1749 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1750 MF.getFrameInfo().isReturnAddressTaken())) {
1751 if (SavedRegs.test(ARM::LR)) {
1752 --RegDeficit;
1753 DEBUG(dbgs() << "%LR is saved register, RegDeficit = " << RegDeficit
1754 << "\n");
1755 } else {
1756 AvailableRegs.push_back(ARM::LR);
1757 DEBUG(dbgs() << "%LR is not saved, adding to AvailableRegs\n");
1758 }
1759 }
1760
1761 // If there are more high registers that need pushing than low registers
1762 // available, push some more low registers so that we can use fewer push
1763 // instructions. This might not reduce RegDeficit all the way to zero,
1764 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1765 // need saving.
1766 DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
1767 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1768 unsigned Reg = AvailableRegs.pop_back_val();
1769 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1770 << " to make up reg deficit\n");
1771 SavedRegs.set(Reg);
1772 NumGPRSpills++;
1773 CS1Spilled = true;
1774 ExtraCSSpill = true;
1775 UnspilledCS1GPRs.erase(find(UnspilledCS1GPRs, Reg));
1776 if (Reg == ARM::LR)
1777 LRSpilled = true;
1778 }
1779 DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit << "\n");
1780 }
1781
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001782 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1783 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1784 if (!LRSpilled && CS1Spilled) {
Matthias Braun02564862015-07-14 17:17:13 +00001785 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001786 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001787 SmallVectorImpl<unsigned>::iterator LRPos;
David Majnemer0d955d02016-08-11 22:21:41 +00001788 LRPos = find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00001789 if (LRPos != UnspilledCS1GPRs.end())
1790 UnspilledCS1GPRs.erase(LRPos);
1791
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001792 ForceLRSpill = false;
1793 ExtraCSSpill = true;
1794 }
1795
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001796 // If stack and double are 8-byte aligned and we are spilling an odd number
1797 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1798 // the integer and double callee save areas.
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001799 DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001800 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001801 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001802 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1803 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1804 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001805 // Don't spill high register if the function is thumb. In the case of
1806 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001807 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001808 (STI.isTargetWindows() && Reg == ARM::R11) ||
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001809 isARMLowRegister(Reg) || Reg == ARM::LR) {
Matthias Braun02564862015-07-14 17:17:13 +00001810 SavedRegs.set(Reg);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001811 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1812 << " to make up alignment\n");
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001813 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001814 ExtraCSSpill = true;
1815 break;
1816 }
1817 }
1818 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1819 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001820 SavedRegs.set(Reg);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001821 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1822 << " to make up alignment\n");
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001823 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001824 ExtraCSSpill = true;
1825 }
1826 }
1827
1828 // Estimate if we might need to scavenge a register at some point in order
1829 // to materialize a stack offset. If so, either spill one additional
1830 // callee-saved register or reserve a special spill slot to facilitate
1831 // register scavenging. Thumb1 needs a spill slot for stack pointer
1832 // adjustments also, even when the frame itself is small.
1833 if (BigStack && !ExtraCSSpill) {
1834 // If any non-reserved CS register isn't spilled, just spill one or two
1835 // extra. That should take care of it!
1836 unsigned NumExtras = TargetAlign / 4;
1837 SmallVector<unsigned, 2> Extras;
1838 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1839 unsigned Reg = UnspilledCS1GPRs.back();
1840 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001841 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001842 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1843 Reg == ARM::LR)) {
1844 Extras.push_back(Reg);
1845 NumExtras--;
1846 }
1847 }
1848 // For non-Thumb1 functions, also check for hi-reg CS registers
1849 if (!AFI->isThumb1OnlyFunction()) {
1850 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1851 unsigned Reg = UnspilledCS2GPRs.back();
1852 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001853 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001854 Extras.push_back(Reg);
1855 NumExtras--;
1856 }
1857 }
1858 }
1859 if (Extras.size() && NumExtras == 0) {
1860 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Matthias Braun02564862015-07-14 17:17:13 +00001861 SavedRegs.set(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001862 }
1863 } else if (!AFI->isThumb1OnlyFunction()) {
1864 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1865 // closest to SP or frame pointer.
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001866 assert(RS && "Register scavenging not provided");
Craig Topperc7242e02012-04-20 07:30:17 +00001867 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Matthias Braun941a7052016-07-28 18:40:00 +00001868 RS->addScavengingFrameIndex(MFI.CreateStackObject(RC->getSize(),
1869 RC->getAlignment(),
1870 false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001871 }
1872 }
1873 }
1874
1875 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00001876 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001877 AFI->setLRIsSpilledForFarJump(true);
1878 }
1879}
Eli Bendersky8da87162013-02-21 20:05:00 +00001880
Hans Wennborge1a2e902016-03-31 18:33:38 +00001881MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
1882 MachineFunction &MF, MachineBasicBlock &MBB,
1883 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001884 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001885 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001886 if (!hasReservedCallFrame(MF)) {
1887 // If we have alloca, convert as follows:
1888 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1889 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001890 MachineInstr &Old = *I;
1891 DebugLoc dl = Old.getDebugLoc();
1892 unsigned Amount = Old.getOperand(0).getImm();
Eli Bendersky8da87162013-02-21 20:05:00 +00001893 if (Amount != 0) {
1894 // We need to keep the stack aligned properly. To do this, we round the
1895 // amount of space needed for the outgoing arguments up to the next
1896 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00001897 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00001898
1899 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1900 assert(!AFI->isThumb1OnlyFunction() &&
1901 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1902 bool isARM = !AFI->isThumbFunction();
1903
1904 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001905 unsigned Opc = Old.getOpcode();
1906 int PIdx = Old.findFirstPredOperandIdx();
1907 ARMCC::CondCodes Pred =
1908 (PIdx == -1) ? ARMCC::AL
1909 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Eli Bendersky8da87162013-02-21 20:05:00 +00001910 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1911 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001912 unsigned PredReg = Old.getOperand(2).getReg();
Eli Bendersky8da87162013-02-21 20:05:00 +00001913 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1914 Pred, PredReg);
1915 } else {
1916 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001917 unsigned PredReg = Old.getOperand(3).getReg();
Eli Bendersky8da87162013-02-21 20:05:00 +00001918 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1919 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1920 Pred, PredReg);
1921 }
1922 }
1923 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00001924 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001925}
1926
Oliver Stannardb14c6252014-04-02 16:10:33 +00001927/// Get the minimum constant for ARM that is greater than or equal to the
1928/// argument. In ARM, constants can have any value that can be produced by
1929/// rotating an 8-bit value to the right by an even number of bits within a
1930/// 32-bit word.
1931static uint32_t alignToARMConstant(uint32_t Value) {
1932 unsigned Shifted = 0;
1933
1934 if (Value == 0)
1935 return 0;
1936
1937 while (!(Value & 0xC0000000)) {
1938 Value = Value << 2;
1939 Shifted += 2;
1940 }
1941
1942 bool Carry = (Value & 0x00FFFFFF);
1943 Value = ((Value & 0xFF000000) >> 24) + Carry;
1944
1945 if (Value & 0x0000100)
1946 Value = Value & 0x000001FC;
1947
1948 if (Shifted > 24)
1949 Value = Value >> (Shifted - 24);
1950 else
1951 Value = Value << (24 - Shifted);
1952
1953 return Value;
1954}
1955
1956// The stack limit in the TCB is set to this many bytes above the actual
1957// stack limit.
1958static const uint64_t kSplitStackAvailable = 256;
1959
1960// Adjust the function prologue to enable split stacks. This currently only
1961// supports android and linux.
1962//
1963// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1964// must be well defined in order to allow for consistent implementations of the
1965// __morestack helper function. The ABI is also not a normal ABI in that it
1966// doesn't follow the normal calling conventions because this allows the
1967// prologue of each function to be optimized further.
1968//
1969// Currently, the ABI looks like (when calling __morestack)
1970//
1971// * r4 holds the minimum stack size requested for this function call
1972// * r5 holds the stack size of the arguments to the function
1973// * the beginning of the function is 3 instructions after the call to
1974// __morestack
1975//
1976// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1977// place the arguments on to the new stack, and the 3-instruction knowledge to
1978// jump directly to the body of the function when working on the new stack.
1979//
1980// An old (and possibly no longer compatible) implementation of __morestack for
1981// ARM can be found at [1].
1982//
1983// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00001984void ARMFrameLowering::adjustForSegmentedStacks(
1985 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00001986 unsigned Opcode;
1987 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00001988 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00001989 bool Thumb = ST->isThumb();
1990
1991 // Sadly, this currently doesn't support varargs, platforms other than
1992 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1993 if (MF.getFunction()->isVarArg())
1994 report_fatal_error("Segmented stacks do not support vararg functions.");
1995 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001996 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001997
Matthias Braun941a7052016-07-28 18:40:00 +00001998 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00001999 MachineModuleInfo &MMI = MF.getMMI();
2000 MCContext &Context = MMI.getContext();
2001 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2002 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002003 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002004 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2005 DebugLoc DL;
2006
Matthias Braun941a7052016-07-28 18:40:00 +00002007 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002008
2009 // Do not generate a prologue for functions with a stack of size zero
2010 if (StackSize == 0)
2011 return;
2012
Oliver Stannardb14c6252014-04-02 16:10:33 +00002013 // Use R4 and R5 as scratch registers.
2014 // We save R4 and R5 before use and restore them before leaving the function.
2015 unsigned ScratchReg0 = ARM::R4;
2016 unsigned ScratchReg1 = ARM::R5;
2017 uint64_t AlignedStackSize;
2018
2019 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2020 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2021 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2022 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2023 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2024
Quentin Colombet71a71482015-07-20 21:42:14 +00002025 // Grab everything that reaches PrologueMBB to update there liveness as well.
2026 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2027 SmallVector<MachineBasicBlock *, 2> WalkList;
2028 WalkList.push_back(&PrologueMBB);
2029
2030 do {
2031 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2032 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2033 if (BeforePrologueRegion.insert(PredBB).second)
2034 WalkList.push_back(PredBB);
2035 }
2036 } while (!WalkList.empty());
2037
2038 // The order in that list is important.
2039 // The blocks will all be inserted before PrologueMBB using that order.
2040 // Therefore the block that should appear first in the CFG should appear
2041 // first in the list.
2042 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2043 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002044
Craig Topper80720812015-12-01 06:13:01 +00002045 for (MachineBasicBlock *B : AddedBlocks)
2046 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002047
Matthias Braund9da1622015-09-09 18:08:03 +00002048 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002049 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002050 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002051 }
2052
Quentin Colombet71a71482015-07-20 21:42:14 +00002053 // Remove the newly added blocks from the list, since we know
2054 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002055 for (MachineBasicBlock *B : AddedBlocks) {
2056 BeforePrologueRegion.erase(B);
2057 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002058 }
2059
2060 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2061 // Make sure the LiveIns are still sorted and unique.
2062 MBB->sortUniqueLiveIns();
2063 // Replace the edges to PrologueMBB by edges to the sequences
2064 // we are about to add.
2065 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2066 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002067
2068 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002069 AlignedStackSize = alignToARMConstant(StackSize);
2070
2071 // When the frame size is less than 256 we just compare the stack
2072 // boundary directly to the value of the stack pointer, per gcc.
2073 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2074
2075 // We will use two of the callee save registers as scratch registers so we
2076 // need to save those registers onto the stack.
2077 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2078 // requested and arguments for __morestack().
2079 // SR0: Scratch Register #0
2080 // SR1: Scratch Register #1
2081 // push {SR0, SR1}
2082 if (Thumb) {
2083 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
2084 .addReg(ScratchReg0).addReg(ScratchReg1);
2085 } else {
2086 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2087 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
2088 .addReg(ScratchReg0).addReg(ScratchReg1);
2089 }
2090
2091 // Emit the relevant DWARF information about the change in stack pointer as
2092 // well as where to find both r4 and r5 (the callee-save registers)
2093 CFIIndex =
2094 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
2095 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2096 .addCFIIndex(CFIIndex);
2097 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2098 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2099 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2100 .addCFIIndex(CFIIndex);
2101 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2102 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2103 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2104 .addCFIIndex(CFIIndex);
2105
2106 // mov SR1, sp
2107 if (Thumb) {
2108 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2109 .addReg(ARM::SP));
2110 } else if (CompareStackPointer) {
2111 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2112 .addReg(ARM::SP)).addReg(0);
2113 }
2114
2115 // sub SR1, sp, #StackSize
2116 if (!CompareStackPointer && Thumb) {
2117 AddDefaultPred(
2118 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
2119 .addReg(ScratchReg1).addImm(AlignedStackSize));
2120 } else if (!CompareStackPointer) {
2121 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2122 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
2123 }
2124
2125 if (Thumb && ST->isThumb1Only()) {
2126 unsigned PCLabelId = ARMFI->createPICLabelUId();
2127 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00002128 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002129 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002130 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002131
2132 // ldr SR0, [pc, offset(STACK_LIMIT)]
2133 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2134 .addConstantPoolIndex(CPI));
2135
2136 // ldr SR0, [SR0]
2137 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2138 .addReg(ScratchReg0).addImm(0));
2139 } else {
2140 // Get TLS base address from the coprocessor
2141 // mrc p15, #0, SR0, c13, c0, #3
2142 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2143 .addImm(15)
2144 .addImm(0)
2145 .addImm(13)
2146 .addImm(0)
2147 .addImm(3));
2148
2149 // Use the last tls slot on android and a private field of the TCP on linux.
2150 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2151 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2152
2153 // Get the stack limit from the right offset
2154 // ldr SR0, [sr0, #4 * TlsOffset]
2155 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2156 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2157 }
2158
2159 // Compare stack limit with stack size requested.
2160 // cmp SR0, SR1
2161 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2162 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2163 .addReg(ScratchReg0)
2164 .addReg(ScratchReg1));
2165
2166 // This jump is taken if StackLimit < SP - stack required.
2167 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2168 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2169 .addImm(ARMCC::LO)
2170 .addReg(ARM::CPSR);
2171
2172
2173 // Calling __morestack(StackSize, Size of stack arguments).
2174 // __morestack knows that the stack size requested is in SR0(r4)
2175 // and amount size of stack arguments is in SR1(r5).
2176
2177 // Pass first argument for the __morestack by Scratch Register #0.
2178 // The amount size of stack required
2179 if (Thumb) {
2180 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2181 ScratchReg0)).addImm(AlignedStackSize));
2182 } else {
2183 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2184 .addImm(AlignedStackSize)).addReg(0);
2185 }
2186 // Pass second argument for the __morestack by Scratch Register #1.
2187 // The amount size of stack consumed to save function arguments.
2188 if (Thumb) {
2189 AddDefaultPred(
2190 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2191 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2192 } else {
2193 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2194 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2195 .addReg(0);
2196 }
2197
2198 // push {lr} - Save return address of this function.
2199 if (Thumb) {
2200 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2201 .addReg(ARM::LR);
2202 } else {
2203 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2204 .addReg(ARM::SP, RegState::Define)
2205 .addReg(ARM::SP))
2206 .addReg(ARM::LR);
2207 }
2208
2209 // Emit the DWARF info about the change in stack as well as where to find the
2210 // previous link register
2211 CFIIndex =
2212 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2213 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2214 .addCFIIndex(CFIIndex);
2215 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2216 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2217 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2218 .addCFIIndex(CFIIndex);
2219
2220 // Call __morestack().
2221 if (Thumb) {
2222 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2223 .addExternalSymbol("__morestack");
2224 } else {
2225 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2226 .addExternalSymbol("__morestack");
2227 }
2228
2229 // pop {lr} - Restore return address of this original function.
2230 if (Thumb) {
2231 if (ST->isThumb1Only()) {
2232 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2233 .addReg(ScratchReg0);
2234 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2235 .addReg(ScratchReg0));
2236 } else {
2237 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2238 .addReg(ARM::LR, RegState::Define)
2239 .addReg(ARM::SP, RegState::Define)
2240 .addReg(ARM::SP)
2241 .addImm(4));
2242 }
2243 } else {
2244 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2245 .addReg(ARM::SP, RegState::Define)
2246 .addReg(ARM::SP))
2247 .addReg(ARM::LR);
2248 }
2249
2250 // Restore SR0 and SR1 in case of __morestack() was called.
2251 // __morestack() will skip PostStackMBB block so we need to restore
2252 // scratch registers from here.
2253 // pop {SR0, SR1}
2254 if (Thumb) {
2255 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2256 .addReg(ScratchReg0)
2257 .addReg(ScratchReg1);
2258 } else {
2259 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2260 .addReg(ARM::SP, RegState::Define)
2261 .addReg(ARM::SP))
2262 .addReg(ScratchReg0)
2263 .addReg(ScratchReg1);
2264 }
2265
2266 // Update the CFA offset now that we've popped
2267 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2268 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2269 .addCFIIndex(CFIIndex);
2270
2271 // bx lr - Return from this function.
2272 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2273 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2274
2275 // Restore SR0 and SR1 in case of __morestack() was not called.
2276 // pop {SR0, SR1}
2277 if (Thumb) {
2278 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2279 .addReg(ScratchReg0)
2280 .addReg(ScratchReg1);
2281 } else {
2282 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2283 .addReg(ARM::SP, RegState::Define)
2284 .addReg(ARM::SP))
2285 .addReg(ScratchReg0)
2286 .addReg(ScratchReg1);
2287 }
2288
2289 // Update the CFA offset now that we've popped
2290 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2291 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2292 .addCFIIndex(CFIIndex);
2293
2294 // Tell debuggers that r4 and r5 are now the same as they were in the
2295 // previous function, that they're the "Same Value".
2296 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2297 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2298 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2299 .addCFIIndex(CFIIndex);
2300 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2301 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2302 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2303 .addCFIIndex(CFIIndex);
2304
2305 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002306 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002307
2308 AllocMBB->addSuccessor(PostStackMBB);
2309
2310 GetMBB->addSuccessor(PostStackMBB);
2311 GetMBB->addSuccessor(AllocMBB);
2312
2313 McrMBB->addSuccessor(GetMBB);
2314
2315 PrevStackMBB->addSuccessor(McrMBB);
2316
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002317#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002318 MF.verify();
2319#endif
2320}