blob: 92fe8fe5fbcedafba84a51212f268f8425c473b5 [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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Function.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000028#include "llvm/MC/MCContext.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000029#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetOptions.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000031
32using namespace llvm;
33
Benjamin Kramer9fceb902012-02-24 22:09:25 +000034static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000035SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000036 cl::desc("Align ARM NEON spills in prolog and epilog"));
37
38static MachineBasicBlock::iterator
39skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
41
Eric Christopher45fb7b62014-06-26 19:29:59 +000042ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
44 STI(sti) {}
45
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000046/// hasFP - Return true if the specified function should have a dedicated frame
47/// pointer register. This is true if the function has variable sized allocas
48/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000049bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000050 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000051
Evan Cheng801d98b2012-01-04 01:55:04 +000052 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000054 return true;
55
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000058 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
59 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000060 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
63}
64
Bob Wilson657f2272011-01-13 21:10:12 +000065/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66/// not required, we reserve argument space for call sites in the function
67/// immediately on entry to the current function. This eliminates the need for
68/// add/sub sp brackets around call sites. Returns true if the call frame is
69/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000070bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000071 const MachineFrameInfo *FFI = MF.getFrameInfo();
72 unsigned CFSize = FFI->getMaxCallFrameSize();
73 // It's not always a good idea to include the call frame as part of the
74 // stack frame. ARM (especially Thumb) has small immediate offset to
75 // address the stack frame. So a large call frame can cause poor codegen
76 // and may even makes it impossible to scavenge a register.
77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
78 return false;
79
80 return !MF.getFrameInfo()->hasVarSizedObjects();
81}
82
Bob Wilson657f2272011-01-13 21:10:12 +000083/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84/// call frame pseudos can be simplified. Unlike most targets, having a FP
85/// is not sufficient here since we still may reference some objects via SP
86/// even when FP is available in Thumb2 mode.
87bool
88ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000089 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
90}
91
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000092static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +000094 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +000095 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +000096 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +000097 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
101 return false;
102 return true;
103 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
109 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000110
111 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000112}
113
Tim Northoverc9432eb2013-11-04 23:04:15 +0000114static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000121 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000123 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000124 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000126 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000127}
128
Tim Northoverc9432eb2013-11-04 23:04:15 +0000129static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
137}
138
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000139static int sizeOfSPAdjustment(const MachineInstr *MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000140 int RegSize;
141 switch (MI->getOpcode()) {
142 case ARM::VSTMDDB_UPD:
143 RegSize = 8;
144 break;
145 case ARM::STMDB_UPD:
146 case ARM::t2STMDB_UPD:
147 RegSize = 4;
148 break;
149 case ARM::t2STR_PRE:
150 case ARM::STR_PRE_IMM:
151 return 4;
152 default:
153 llvm_unreachable("Unknown push or pop like instruction");
154 }
155
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000156 int count = 0;
157 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
158 // pred) so the list starts at 4.
159 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000160 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000161 return count;
162}
163
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000164static bool WindowsRequiresStackProbe(const MachineFunction &MF,
165 size_t StackSizeInBytes) {
166 const MachineFrameInfo *MFI = MF.getFrameInfo();
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000167 const Function *F = MF.getFunction();
168 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
169 if (F->hasFnAttribute("stack-probe-size"))
170 F->getFnAttribute("stack-probe-size")
171 .getValueAsString()
172 .getAsInteger(0, StackProbeSize);
173 return StackSizeInBytes >= StackProbeSize;
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000174}
175
Tim Northover603d3162014-11-14 22:45:33 +0000176namespace {
177struct StackAdjustingInsts {
178 struct InstInfo {
179 MachineBasicBlock::iterator I;
180 unsigned SPAdjust;
181 bool BeforeFPSet;
182 };
183
184 SmallVector<InstInfo, 4> Insts;
185
186 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
187 bool BeforeFPSet = false) {
188 InstInfo Info = {I, SPAdjust, BeforeFPSet};
189 Insts.push_back(Info);
190 }
191
192 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
193 auto Info = std::find_if(Insts.begin(), Insts.end(),
194 [&](InstInfo &Info) { return Info.I == I; });
195 assert(Info != Insts.end() && "invalid sp adjusting instruction");
196 Info->SPAdjust += ExtraBytes;
197 }
198
199 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
200 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
201 unsigned CFAOffset = 0;
202 for (auto &Info : Insts) {
203 if (HasFP && !Info.BeforeFPSet)
204 return;
205
206 CFAOffset -= Info.SPAdjust;
207 unsigned CFIIndex = MMI.addFrameInst(
208 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
209 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000210 TII.get(TargetOpcode::CFI_INSTRUCTION))
211 .addCFIIndex(CFIIndex)
212 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000213 }
214 }
215};
216}
217
Kristof Beyls933de7a2015-01-08 15:09:14 +0000218/// Emit an instruction sequence that will align the address in
219/// register Reg by zero-ing out the lower bits. For versions of the
220/// architecture that support Neon, this must be done in a single
221/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
222/// single instruction. That function only gets called when optimizing
223/// spilling of D registers on a core with the Neon instruction set
224/// present.
225static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
226 const TargetInstrInfo &TII,
227 MachineBasicBlock &MBB,
228 MachineBasicBlock::iterator MBBI,
229 DebugLoc DL, const unsigned Reg,
230 const unsigned Alignment,
231 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000232 const ARMSubtarget &AST =
233 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000234 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
235 const unsigned AlignMask = Alignment - 1;
236 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
237 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
238 if (!AFI->isThumbFunction()) {
239 // if the BFC instruction is available, use that to zero the lower
240 // bits:
241 // bfc Reg, #0, log2(Alignment)
242 // otherwise use BIC, if the mask to zero the required number of bits
243 // can be encoded in the bic immediate field
244 // bic Reg, Reg, Alignment-1
245 // otherwise, emit
246 // lsr Reg, Reg, log2(Alignment)
247 // lsl Reg, Reg, log2(Alignment)
248 if (CanUseBFC) {
249 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
250 .addReg(Reg, RegState::Kill)
251 .addImm(~AlignMask));
252 } else if (AlignMask <= 255) {
253 AddDefaultCC(
254 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
255 .addReg(Reg, RegState::Kill)
256 .addImm(AlignMask)));
257 } else {
258 assert(!MustBeSingleInstruction &&
259 "Shouldn't call emitAligningInstructions demanding a single "
260 "instruction to be emitted for large stack alignment for a target "
261 "without BFC.");
262 AddDefaultCC(AddDefaultPred(
263 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
264 .addReg(Reg, RegState::Kill)
265 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
266 AddDefaultCC(AddDefaultPred(
267 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
268 .addReg(Reg, RegState::Kill)
269 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
270 }
271 } else {
272 // Since this is only reached for Thumb-2 targets, the BFC instruction
273 // should always be available.
274 assert(CanUseBFC);
275 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
276 .addReg(Reg, RegState::Kill)
277 .addImm(~AlignMask));
278 }
279}
280
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000281void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000282 MachineBasicBlock &MBB = MF.front();
283 MachineBasicBlock::iterator MBBI = MBB.begin();
284 MachineFrameInfo *MFI = MF.getFrameInfo();
285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000286 MachineModuleInfo &MMI = MF.getMMI();
287 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000288 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000289 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000290 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
291 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000292 assert(!AFI->isThumb1OnlyFunction() &&
293 "This emitPrologue does not support Thumb1!");
294 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000295 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover8cda34f2015-03-11 18:54:22 +0000296 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000297 unsigned NumBytes = MFI->getStackSize();
298 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
299 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
300 unsigned FramePtr = RegInfo->getFrameRegister(MF);
301
302 // Determine the sizes of each callee-save spill areas and record which frame
303 // belongs to which callee-save spill areas.
304 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
305 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000306 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000307
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000308 // All calls are tail calls in GHC calling conv, and functions have no
309 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000310 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
311 return;
312
Tim Northover603d3162014-11-14 22:45:33 +0000313 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000314 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000315
Oliver Stannardd55e1152014-03-05 15:25:27 +0000316 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000317 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000318 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000319 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000320 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000321 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000322
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000323 if (!AFI->hasStackFrame() &&
324 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000325 if (NumBytes - ArgRegsSaveSize != 0) {
326 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000327 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000328 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
329 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000330 }
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000331 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000332 return;
333 }
334
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000335 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000336 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
337 unsigned Reg = CSI[i].getReg();
338 int FI = CSI[i].getFrameIdx();
339 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000340 case ARM::R8:
341 case ARM::R9:
342 case ARM::R10:
343 case ARM::R11:
344 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000345 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000346 GPRCS2Size += 4;
347 break;
348 }
349 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000350 case ARM::R0:
351 case ARM::R1:
352 case ARM::R2:
353 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000354 case ARM::R4:
355 case ARM::R5:
356 case ARM::R6:
357 case ARM::R7:
358 case ARM::LR:
359 if (Reg == FramePtr)
360 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000361 GPRCS1Size += 4;
362 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000363 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000364 // This is a DPR. Exclude the aligned DPRCS2 spills.
365 if (Reg == ARM::D8)
366 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000367 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000368 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000369 }
370 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000371
Eric Christopherb006fc92010-11-18 19:40:05 +0000372 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000373 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
374 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000375 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000376 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
377 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000378
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000379 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000380 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
381 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
382 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
383 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
384 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000385 int FramePtrOffsetInPush = 0;
386 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000387 FramePtrOffsetInPush =
388 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000389 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
390 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000391 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000392 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
393 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
394 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
395
Tim Northoverc9432eb2013-11-04 23:04:15 +0000396 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000397 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000398 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000399 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
400 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000401
Tim Northover228c9432014-11-05 00:27:13 +0000402 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
403 // .cfi_offset operations will reflect that.
404 if (DPRGapSize) {
405 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Tim Northover603d3162014-11-14 22:45:33 +0000406 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
407 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
408 else {
Tim Northover228c9432014-11-05 00:27:13 +0000409 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
410 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000411 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
412 }
Tim Northover228c9432014-11-05 00:27:13 +0000413 }
414
Eric Christopherb006fc92010-11-18 19:40:05 +0000415 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000416 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000417 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000418 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000419 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
420 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000421 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000422 }
Evan Cheng70d29632011-02-25 00:24:46 +0000423 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000424
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000425 // Move past the aligned DPRCS2 area.
426 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
427 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
428 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
429 // leaves the stack pointer pointing to the DPRCS2 area.
430 //
431 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
432 NumBytes += MFI->getObjectOffset(D8SpillFI);
433 } else
434 NumBytes = DPRCSOffset;
435
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000436 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
437 uint32_t NumWords = NumBytes >> 2;
438
439 if (NumWords < 65536)
440 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000441 .addImm(NumWords)
442 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000443 else
444 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000445 .addImm(NumWords)
446 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000447
448 switch (TM.getCodeModel()) {
449 case CodeModel::Small:
450 case CodeModel::Medium:
451 case CodeModel::Default:
452 case CodeModel::Kernel:
453 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
454 .addImm((unsigned)ARMCC::AL).addReg(0)
455 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000456 .addReg(ARM::R4, RegState::Implicit)
457 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000458 break;
459 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000460 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000461 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000462 .addExternalSymbol("__chkstk")
463 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000464
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000465 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
466 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000467 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000468 .addReg(ARM::R4, RegState::Implicit)
469 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000470 break;
471 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000472
473 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
474 ARM::SP)
475 .addReg(ARM::SP, RegState::Define)
476 .addReg(ARM::R4, RegState::Kill)
477 .setMIFlags(MachineInstr::FrameSetup)));
478 NumBytes = 0;
479 }
480
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000481 if (NumBytes) {
482 // Adjust SP after all the callee-save spills.
Tim Northover603d3162014-11-14 22:45:33 +0000483 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
484 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
485 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000486 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
487 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000488 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
489 }
Tim Northover93bcc662013-11-08 17:18:07 +0000490
Evan Chengeb56dca2010-11-22 18:12:04 +0000491 if (HasFP && isARM)
492 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
493 // Note it's not safe to do this in Thumb2 mode because it would have
494 // taken two instructions:
495 // mov sp, r7
496 // sub sp, #24
497 // If an interrupt is taken between the two instructions, then sp is in
498 // an inconsistent state (pointing to the middle of callee-saved area).
499 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000500 AFI->setShouldRestoreSPFromFP(true);
501 }
502
Tim Northover603d3162014-11-14 22:45:33 +0000503 // Set FP to point to the stack slot that contains the previous FP.
504 // For iOS, FP is R7, which has now been stored in spill area 1.
505 // Otherwise, if this is not iOS, all the callee-saved registers go
506 // into spill area 1, including the FP in R11. In either case, it
507 // is in area one and the adjustment needs to take place just after
508 // that push.
509 if (HasFP) {
510 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
511 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
512 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
513 dl, TII, FramePtr, ARM::SP,
514 PushSize + FramePtrOffsetInPush,
515 MachineInstr::FrameSetup);
516 if (FramePtrOffsetInPush + PushSize != 0) {
517 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
518 nullptr, MRI->getDwarfRegNum(FramePtr, true),
519 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
520 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000521 .addCFIIndex(CFIIndex)
522 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000523 } else {
524 unsigned CFIIndex =
525 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
526 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
527 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000528 .addCFIIndex(CFIIndex)
529 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000530 }
531 }
532
533 // Now that the prologue's actual instructions are finalised, we can insert
534 // the necessary DWARF cf instructions to describe the situation. Start by
535 // recording where each register ended up:
536 if (GPRCS1Size > 0) {
537 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
538 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000539 for (const auto &Entry : CSI) {
540 unsigned Reg = Entry.getReg();
541 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000542 switch (Reg) {
543 case ARM::R8:
544 case ARM::R9:
545 case ARM::R10:
546 case ARM::R11:
547 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000548 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000549 break;
550 // fallthrough
551 case ARM::R0:
552 case ARM::R1:
553 case ARM::R2:
554 case ARM::R3:
555 case ARM::R4:
556 case ARM::R5:
557 case ARM::R6:
558 case ARM::R7:
559 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000560 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
561 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
562 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000563 .addCFIIndex(CFIIndex)
564 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000565 break;
566 }
567 }
568 }
569
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000570 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000571 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000572 for (const auto &Entry : CSI) {
573 unsigned Reg = Entry.getReg();
574 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000575 switch (Reg) {
576 case ARM::R8:
577 case ARM::R9:
578 case ARM::R10:
579 case ARM::R11:
580 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000581 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000582 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000583 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000584 unsigned CFIIndex = MMI.addFrameInst(
585 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
586 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000587 .addCFIIndex(CFIIndex)
588 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000589 }
590 break;
591 }
592 }
593 }
594
595 if (DPRCSSize > 0) {
596 // Since vpush register list cannot have gaps, there may be multiple vpush
597 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000598 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000599 for (const auto &Entry : CSI) {
600 unsigned Reg = Entry.getReg();
601 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000602 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
603 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
604 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
605 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000606 unsigned CFIIndex = MMI.addFrameInst(
607 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000608 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000609 .addCFIIndex(CFIIndex)
610 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000611 }
612 }
613 }
614
Tim Northover603d3162014-11-14 22:45:33 +0000615 // Now we can emit descriptions of where the canonical frame address was
616 // throughout the process. If we have a frame pointer, it takes over the job
617 // half-way through, so only the first few .cfi_def_cfa_offset instructions
618 // actually get emitted.
619 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000620
Evan Chengeb56dca2010-11-22 18:12:04 +0000621 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000622 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
623 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000624
625 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
626 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000627 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000628 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
629
630 // If we need dynamic stack realignment, do it here. Be paranoid and make
631 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000632 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000633 // realigned.
634 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000635 unsigned MaxAlign = MFI->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000636 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000637 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000638 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
639 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000640 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000641 // We cannot use sp as source/dest register here, thus we're using r4 to
642 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000643 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000644 // -- use emitAligningInstructions to produce best sequence to zero
645 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000646 // mov sp, r4
647 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000648 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000649 .addReg(ARM::SP, RegState::Kill));
650 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
651 false);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000652 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000653 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000654 }
655
656 AFI->setShouldRestoreSPFromFP(true);
657 }
658
659 // If we need a base pointer, set it up here. It's whatever the value
660 // of the stack pointer is at this point. Any variable size objects
661 // will be allocated after this, so we can still use the base pointer
662 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000663 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000664 if (RegInfo->hasBasePointer(MF)) {
665 if (isARM)
666 BuildMI(MBB, MBBI, dl,
667 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
668 .addReg(ARM::SP)
669 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
670 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000671 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000672 RegInfo->getBaseRegister())
673 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000674 }
675
676 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000677 // the sp from fp. We can assume there's an FP here since hasFP already
678 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000679 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000680 AFI->setShouldRestoreSPFromFP(true);
681}
682
Tim Northover3024b552014-12-01 17:46:39 +0000683// Resolve TCReturn pseudo-instruction
684void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
685 MachineBasicBlock &MBB) const {
686 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
687 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
688 unsigned RetOpcode = MBBI->getOpcode();
689 DebugLoc dl = MBBI->getDebugLoc();
690 const ARMBaseInstrInfo &TII =
691 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
692
693 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
694 return;
695
696 // Tail call return: adjust the stack pointer and jump to callee.
697 MBBI = MBB.getLastNonDebugInstr();
698 MachineOperand &JumpTarget = MBBI->getOperand(0);
699
700 // Jump to label or value in register.
701 if (RetOpcode == ARM::TCRETURNdi) {
702 unsigned TCOpcode = STI.isThumb() ?
703 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
704 ARM::TAILJMPd;
705 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
706 if (JumpTarget.isGlobal())
707 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
708 JumpTarget.getTargetFlags());
709 else {
710 assert(JumpTarget.isSymbol());
711 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
712 JumpTarget.getTargetFlags());
713 }
714
715 // Add the default predicate in Thumb mode.
716 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
717 } else if (RetOpcode == ARM::TCRETURNri) {
718 BuildMI(MBB, MBBI, dl,
719 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
720 addReg(JumpTarget.getReg(), RegState::Kill);
721 }
722
723 MachineInstr *NewMI = std::prev(MBBI);
724 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
725 NewMI->addOperand(MBBI->getOperand(i));
726
727 // Delete the pseudo instruction TCRETURN.
728 MBB.erase(MBBI);
729 MBBI = NewMI;
730}
731
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000732void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000733 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000734 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000735 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000736 DebugLoc dl = MBBI->getDebugLoc();
737 MachineFrameInfo *MFI = MF.getFrameInfo();
738 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000739 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000740 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000741 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000742 assert(!AFI->isThumb1OnlyFunction() &&
743 "This emitEpilogue does not support Thumb1!");
744 bool isARM = !AFI->isThumbFunction();
745
Tim Northover8cda34f2015-03-11 18:54:22 +0000746 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000747 int NumBytes = (int)MFI->getStackSize();
748 unsigned FramePtr = RegInfo->getFrameRegister(MF);
749
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000750 // All calls are tail calls in GHC calling conv, and functions have no
751 // prologue/epilogue.
Tim Northover3024b552014-12-01 17:46:39 +0000752 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
753 fixTCReturn(MF, MBB);
Eric Christopherb3322362012-08-03 00:05:53 +0000754 return;
Tim Northover3024b552014-12-01 17:46:39 +0000755 }
Eric Christopherb3322362012-08-03 00:05:53 +0000756
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000757 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000758 if (NumBytes - ArgRegsSaveSize != 0)
759 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000760 } else {
761 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000762 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000763 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000764 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000765 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000766 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000767 if (!isCSRestore(MBBI, TII, CSRegs))
768 ++MBBI;
769 }
770
771 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000772 NumBytes -= (ArgRegsSaveSize +
773 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000774 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000775 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000776 AFI->getDPRCalleeSavedAreaSize());
777
778 // Reset SP based on frame pointer only if the stack frame extends beyond
779 // frame pointer stack slot or target is ELF and the function has FP.
780 if (AFI->shouldRestoreSPFromFP()) {
781 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
782 if (NumBytes) {
783 if (isARM)
784 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
785 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000786 else {
787 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000788 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000789 // mov sp, r7
790 // sub sp, #24
791 // This is bad, if an interrupt is taken after the mov, sp is in an
792 // inconsistent state.
793 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000794 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000795 "No scratch register to restore SP from FP!");
796 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000797 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000798 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000799 ARM::SP)
800 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000801 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000802 } else {
803 // Thumb2 or ARM.
804 if (isARM)
805 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
806 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
807 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000808 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000809 ARM::SP)
810 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000811 }
Tim Northoverdee86042013-12-02 14:46:26 +0000812 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000813 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000814 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000815
Eric Christopherb006fc92010-11-18 19:40:05 +0000816 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000817 if (AFI->getDPRCalleeSavedAreaSize()) {
818 MBBI++;
819 // Since vpop register list cannot have gaps, there may be multiple vpop
820 // instructions in the epilogue.
821 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
822 MBBI++;
823 }
Tim Northover228c9432014-11-05 00:27:13 +0000824 if (AFI->getDPRCalleeSavedGapSize()) {
825 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
826 "unexpected DPR alignment gap");
827 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
828 }
829
Eric Christopherb006fc92010-11-18 19:40:05 +0000830 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
831 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000832 }
833
Tim Northover3024b552014-12-01 17:46:39 +0000834 fixTCReturn(MF, MBB);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000835
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000836 if (ArgRegsSaveSize)
837 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000838}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000839
Bob Wilson657f2272011-01-13 21:10:12 +0000840/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
841/// debug info. It's the same as what we use for resolving the code-gen
842/// references for now. FIXME: This can go wrong when references are
843/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000844int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000845ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000846 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000847 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
848}
849
850int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000851ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000852 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000853 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000854 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000855 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000856 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000857 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
858 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
859 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
860 bool isFixed = MFI->isFixedObjectIndex(FI);
861
862 FrameReg = ARM::SP;
863 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000864
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000865 // SP can move around if there are allocas. We may also lose track of SP
866 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000867 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000868
Anton Korobeynikov46877782010-11-20 15:59:32 +0000869 // When dynamically realigning the stack, use the frame pointer for
870 // parameters, and the stack/base pointer for locals.
871 if (RegInfo->needsStackRealignment(MF)) {
872 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
873 if (isFixed) {
874 FrameReg = RegInfo->getFrameRegister(MF);
875 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000876 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000877 assert(RegInfo->hasBasePointer(MF) &&
878 "VLAs and dynamic stack alignment, but missing base pointer!");
879 FrameReg = RegInfo->getBaseRegister();
880 }
881 return Offset;
882 }
883
884 // If there is a frame pointer, use it when we can.
885 if (hasFP(MF) && AFI->hasStackFrame()) {
886 // Use frame pointer to reference fixed objects. Use it for locals if
887 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000888 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000889 FrameReg = RegInfo->getFrameRegister(MF);
890 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000891 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000892 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000893 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000894 // Try to use the frame pointer if we can, else use the base pointer
895 // since it's available. This is handy for the emergency spill slot, in
896 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000897 if (FPOffset >= -255 && FPOffset < 0) {
898 FrameReg = RegInfo->getFrameRegister(MF);
899 return FPOffset;
900 }
Evan Chengc0d20042011-04-22 01:42:52 +0000901 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000902 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000903 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000904 // ldr <rd>, [sp, #<imm8>]
905 // if at all possible to save space.
906 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
907 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000908 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000909 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000910 if (FPOffset >= -255 && FPOffset < 0) {
911 FrameReg = RegInfo->getFrameRegister(MF);
912 return FPOffset;
913 }
914 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
915 // Otherwise, use SP or FP, whichever is closer to the stack slot.
916 FrameReg = RegInfo->getFrameRegister(MF);
917 return FPOffset;
918 }
919 }
920 // Use the base pointer if we have one.
921 if (RegInfo->hasBasePointer(MF))
922 FrameReg = RegInfo->getBaseRegister();
923 return Offset;
924}
925
Bob Wilson657f2272011-01-13 21:10:12 +0000926int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
927 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000928 unsigned FrameReg;
929 return getFrameIndexReference(MF, FI, FrameReg);
930}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000931
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000932void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000933 MachineBasicBlock::iterator MI,
934 const std::vector<CalleeSavedInfo> &CSI,
935 unsigned StmOpc, unsigned StrOpc,
936 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000937 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000938 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000939 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000940 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000941 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000942
943 DebugLoc DL;
944 if (MI != MBB.end()) DL = MI->getDebugLoc();
945
Evan Chengc27c9562010-12-07 19:59:34 +0000946 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000947 unsigned i = CSI.size();
948 while (i != 0) {
949 unsigned LastReg = 0;
950 for (; i != 0; --i) {
951 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000952 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000953
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000954 // D-registers in the aligned area DPRCS2 are NOT spilled here.
955 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
956 continue;
957
Evan Cheng775ead32010-12-07 23:08:38 +0000958 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000959 // @llvm.returnaddress is called. If LR is returned for
960 // @llvm.returnaddress then it's already added to the function and
961 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000962 bool isKill = true;
963 if (Reg == ARM::LR) {
964 if (MF.getFrameInfo()->isReturnAddressTaken() &&
965 MF.getRegInfo().isLiveIn(Reg))
966 isKill = false;
967 }
968
969 if (isKill)
970 MBB.addLiveIn(Reg);
971
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000972 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000973 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000974 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000975 if (NoGap && LastReg && LastReg != Reg-1)
976 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000977 LastReg = Reg;
978 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000979 }
980
Jim Grosbach5fccad82010-12-09 18:31:13 +0000981 if (Regs.empty())
982 continue;
983 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000984 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000985 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000986 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000987 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
988 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000989 } else if (Regs.size() == 1) {
990 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
991 ARM::SP)
992 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000993 .addReg(ARM::SP).setMIFlags(MIFlags)
994 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000995 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000996 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000997 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000998
999 // Put any subsequent vpush instructions before this one: they will refer to
1000 // higher register numbers so need to be pushed first in order to preserve
1001 // monotonicity.
1002 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001003 }
Evan Cheng775ead32010-12-07 23:08:38 +00001004}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001005
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001006void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001007 MachineBasicBlock::iterator MI,
1008 const std::vector<CalleeSavedInfo> &CSI,
1009 unsigned LdmOpc, unsigned LdrOpc,
1010 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001011 bool(*Func)(unsigned, bool),
1012 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001013 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001014 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001015 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1016 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +00001017 unsigned RetOpcode = MI->getOpcode();
1018 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +00001019 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +00001020 bool isInterrupt =
1021 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +00001022
1023 SmallVector<unsigned, 4> Regs;
1024 unsigned i = CSI.size();
1025 while (i != 0) {
1026 unsigned LastReg = 0;
1027 bool DeleteRet = false;
1028 for (; i != 0; --i) {
1029 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +00001030 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001031
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001032 // The aligned reloads from area DPRCS2 are not inserted here.
1033 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1034 continue;
1035
Tim Northoverd8407452013-10-01 14:33:28 +00001036 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1037 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +00001038 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001039 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +00001040 // Fold the return instruction into the LDM.
1041 DeleteRet = true;
1042 }
1043
Evan Cheng9d54ae62010-12-08 06:29:02 +00001044 // If NoGap is true, pop consecutive registers and then leave the rest
1045 // for other instructions. e.g.
1046 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1047 if (NoGap && LastReg && LastReg != Reg-1)
1048 break;
1049
Evan Cheng775ead32010-12-07 23:08:38 +00001050 LastReg = Reg;
1051 Regs.push_back(Reg);
1052 }
1053
Jim Grosbach5fccad82010-12-09 18:31:13 +00001054 if (Regs.empty())
1055 continue;
1056 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +00001057 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +00001058 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +00001059 .addReg(ARM::SP));
1060 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1061 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +00001062 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001063 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001064 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001065 }
Evan Cheng775ead32010-12-07 23:08:38 +00001066 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001067 } else if (Regs.size() == 1) {
1068 // If we adjusted the reg to PC from LR above, switch it back here. We
1069 // only do that for LDM.
1070 if (Regs[0] == ARM::PC)
1071 Regs[0] = ARM::LR;
1072 MachineInstrBuilder MIB =
1073 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1074 .addReg(ARM::SP, RegState::Define)
1075 .addReg(ARM::SP);
1076 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1077 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001078 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001079 MIB.addReg(0);
1080 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1081 } else
1082 MIB.addImm(4);
1083 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +00001084 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001085 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001086
1087 // Put any subsequent vpop instructions after this one: they will refer to
1088 // higher register numbers so need to be popped afterwards.
1089 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001090 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001091}
1092
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001093/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001094/// starting from d8. Also insert stack realignment code and leave the stack
1095/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001096static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1097 MachineBasicBlock::iterator MI,
1098 unsigned NumAlignedDPRCS2Regs,
1099 const std::vector<CalleeSavedInfo> &CSI,
1100 const TargetRegisterInfo *TRI) {
1101 MachineFunction &MF = *MBB.getParent();
1102 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1103 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001104 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001105 MachineFrameInfo &MFI = *MF.getFrameInfo();
1106
1107 // Mark the D-register spill slots as properly aligned. Since MFI computes
1108 // stack slot layout backwards, this can actually mean that the d-reg stack
1109 // slot offsets can be wrong. The offset for d8 will always be correct.
1110 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1111 unsigned DNum = CSI[i].getReg() - ARM::D8;
1112 if (DNum >= 8)
1113 continue;
1114 int FI = CSI[i].getFrameIdx();
1115 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1116 // registers will be 8-byte aligned.
1117 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1118
1119 // The stack slot for D8 needs to be maximally aligned because this is
1120 // actually the point where we align the stack pointer. MachineFrameInfo
1121 // computes all offsets relative to the incoming stack pointer which is a
1122 // bit weird when realigning the stack. Any extra padding for this
1123 // over-alignment is not realized because the code inserted below adjusts
1124 // the stack pointer by numregs * 8 before aligning the stack pointer.
1125 if (DNum == 0)
1126 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1127 }
1128
1129 // Move the stack pointer to the d8 spill slot, and align it at the same
1130 // time. Leave the stack slot address in the scratch register r4.
1131 //
1132 // sub r4, sp, #numregs * 8
1133 // bic r4, r4, #align - 1
1134 // mov sp, r4
1135 //
1136 bool isThumb = AFI->isThumbFunction();
1137 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1138 AFI->setShouldRestoreSPFromFP(true);
1139
1140 // sub r4, sp, #numregs * 8
1141 // The immediate is <= 64, so it doesn't need any special encoding.
1142 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1143 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +00001144 .addReg(ARM::SP)
1145 .addImm(8 * NumAlignedDPRCS2Regs)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001146
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001147 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001148 // We must set parameter MustBeSingleInstruction to true, since
1149 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1150 // stack alignment. Luckily, this can always be done since all ARM
1151 // architecture versions that support Neon also support the BFC
1152 // instruction.
1153 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001154
1155 // mov sp, r4
1156 // The stack pointer must be adjusted before spilling anything, otherwise
1157 // the stack slots could be clobbered by an interrupt handler.
1158 // Leave r4 live, it is used below.
1159 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1160 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1161 .addReg(ARM::R4);
1162 MIB = AddDefaultPred(MIB);
1163 if (!isThumb)
1164 AddDefaultCC(MIB);
1165
1166 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1167 // r4 holds the stack slot address.
1168 unsigned NextReg = ARM::D8;
1169
1170 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1171 // The writeback is only needed when emitting two vst1.64 instructions.
1172 if (NumAlignedDPRCS2Regs >= 6) {
1173 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001174 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001175 MBB.addLiveIn(SupReg);
1176 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1177 ARM::R4)
1178 .addReg(ARM::R4, RegState::Kill).addImm(16)
1179 .addReg(NextReg)
1180 .addReg(SupReg, RegState::ImplicitKill));
1181 NextReg += 4;
1182 NumAlignedDPRCS2Regs -= 4;
1183 }
1184
1185 // We won't modify r4 beyond this point. It currently points to the next
1186 // register to be spilled.
1187 unsigned R4BaseReg = NextReg;
1188
1189 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1190 if (NumAlignedDPRCS2Regs >= 4) {
1191 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001192 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001193 MBB.addLiveIn(SupReg);
1194 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1195 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1196 .addReg(SupReg, RegState::ImplicitKill));
1197 NextReg += 4;
1198 NumAlignedDPRCS2Regs -= 4;
1199 }
1200
1201 // 16-byte aligned vst1.64 with 2 d-regs.
1202 if (NumAlignedDPRCS2Regs >= 2) {
1203 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001204 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001205 MBB.addLiveIn(SupReg);
1206 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001207 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001208 NextReg += 2;
1209 NumAlignedDPRCS2Regs -= 2;
1210 }
1211
1212 // Finally, use a vanilla vstr.64 for the odd last register.
1213 if (NumAlignedDPRCS2Regs) {
1214 MBB.addLiveIn(NextReg);
1215 // vstr.64 uses addrmode5 which has an offset scale of 4.
1216 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1217 .addReg(NextReg)
1218 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1219 }
1220
1221 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001222 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001223}
1224
1225/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1226/// iterator to the following instruction.
1227static MachineBasicBlock::iterator
1228skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1229 unsigned NumAlignedDPRCS2Regs) {
1230 // sub r4, sp, #numregs * 8
1231 // bic r4, r4, #align - 1
1232 // mov sp, r4
1233 ++MI; ++MI; ++MI;
1234 assert(MI->mayStore() && "Expecting spill instruction");
1235
1236 // These switches all fall through.
1237 switch(NumAlignedDPRCS2Regs) {
1238 case 7:
1239 ++MI;
1240 assert(MI->mayStore() && "Expecting spill instruction");
1241 default:
1242 ++MI;
1243 assert(MI->mayStore() && "Expecting spill instruction");
1244 case 1:
1245 case 2:
1246 case 4:
1247 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1248 ++MI;
1249 }
1250 return MI;
1251}
1252
1253/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1254/// starting from d8. These instructions are assumed to execute while the
1255/// stack is still aligned, unlike the code inserted by emitPopInst.
1256static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1257 MachineBasicBlock::iterator MI,
1258 unsigned NumAlignedDPRCS2Regs,
1259 const std::vector<CalleeSavedInfo> &CSI,
1260 const TargetRegisterInfo *TRI) {
1261 MachineFunction &MF = *MBB.getParent();
1262 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1263 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001264 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001265
1266 // Find the frame index assigned to d8.
1267 int D8SpillFI = 0;
1268 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1269 if (CSI[i].getReg() == ARM::D8) {
1270 D8SpillFI = CSI[i].getFrameIdx();
1271 break;
1272 }
1273
1274 // Materialize the address of the d8 spill slot into the scratch register r4.
1275 // This can be fairly complicated if the stack frame is large, so just use
1276 // the normal frame index elimination mechanism to do it. This code runs as
1277 // the initial part of the epilog where the stack and base pointers haven't
1278 // been changed yet.
1279 bool isThumb = AFI->isThumbFunction();
1280 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1281
1282 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1283 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1284 .addFrameIndex(D8SpillFI).addImm(0)));
1285
1286 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1287 unsigned NextReg = ARM::D8;
1288
1289 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1290 if (NumAlignedDPRCS2Regs >= 6) {
1291 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001292 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001293 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1294 .addReg(ARM::R4, RegState::Define)
1295 .addReg(ARM::R4, RegState::Kill).addImm(16)
1296 .addReg(SupReg, RegState::ImplicitDefine));
1297 NextReg += 4;
1298 NumAlignedDPRCS2Regs -= 4;
1299 }
1300
1301 // We won't modify r4 beyond this point. It currently points to the next
1302 // register to be spilled.
1303 unsigned R4BaseReg = NextReg;
1304
1305 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1306 if (NumAlignedDPRCS2Regs >= 4) {
1307 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001308 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001309 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1310 .addReg(ARM::R4).addImm(16)
1311 .addReg(SupReg, RegState::ImplicitDefine));
1312 NextReg += 4;
1313 NumAlignedDPRCS2Regs -= 4;
1314 }
1315
1316 // 16-byte aligned vld1.64 with 2 d-regs.
1317 if (NumAlignedDPRCS2Regs >= 2) {
1318 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001319 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001320 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1321 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001322 NextReg += 2;
1323 NumAlignedDPRCS2Regs -= 2;
1324 }
1325
1326 // Finally, use a vanilla vldr.64 for the remaining odd register.
1327 if (NumAlignedDPRCS2Regs)
1328 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1329 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1330
1331 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001332 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001333}
1334
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001335bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001336 MachineBasicBlock::iterator MI,
1337 const std::vector<CalleeSavedInfo> &CSI,
1338 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001339 if (CSI.empty())
1340 return false;
1341
1342 MachineFunction &MF = *MBB.getParent();
1343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001344
1345 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001346 unsigned PushOneOpc = AFI->isThumbFunction() ?
1347 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001348 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001349 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1350 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001351 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001352 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001353 MachineInstr::FrameSetup);
1354 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001355 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1356
1357 // The code above does not insert spill code for the aligned DPRCS2 registers.
1358 // The stack realignment code will be inserted between the push instructions
1359 // and these spills.
1360 if (NumAlignedDPRCS2Regs)
1361 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001362
1363 return true;
1364}
1365
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001366bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001367 MachineBasicBlock::iterator MI,
1368 const std::vector<CalleeSavedInfo> &CSI,
1369 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001370 if (CSI.empty())
1371 return false;
1372
1373 MachineFunction &MF = *MBB.getParent();
1374 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001375 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001376 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1377
1378 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1379 // registers. Do that here instead.
1380 if (NumAlignedDPRCS2Regs)
1381 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001382
1383 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001384 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001385 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001386 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1387 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001388 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001389 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001390 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001391 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001392
1393 return true;
1394}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001395
1396// FIXME: Make generic?
1397static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1398 const ARMBaseInstrInfo &TII) {
1399 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001400 for (auto &MBB : MF) {
1401 for (auto &MI : MBB)
1402 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001403 }
1404 return FnSize;
1405}
1406
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001407/// estimateRSStackSizeLimit - Look at each instruction that references stack
1408/// frames and return the stack size limit beyond which some of these
1409/// instructions will require a scratch register during their expansion later.
1410// FIXME: Move to TII?
1411static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001412 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001413 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1414 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001415 for (auto &MBB : MF) {
1416 for (auto &MI : MBB) {
1417 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1418 if (!MI.getOperand(i).isFI())
1419 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001420
1421 // When using ADDri to get the address of a stack object, 255 is the
1422 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001423 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001424 Limit = std::min(Limit, (1U << 8) - 1);
1425 break;
1426 }
1427
1428 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001429 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001430 case ARMII::AddrMode3:
1431 case ARMII::AddrModeT2_i8:
1432 Limit = std::min(Limit, (1U << 8) - 1);
1433 break;
1434 case ARMII::AddrMode5:
1435 case ARMII::AddrModeT2_i8s4:
1436 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1437 break;
1438 case ARMII::AddrModeT2_i12:
1439 // i12 supports only positive offset so these will be converted to
1440 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1441 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1442 Limit = std::min(Limit, (1U << 8) - 1);
1443 break;
1444 case ARMII::AddrMode4:
1445 case ARMII::AddrMode6:
1446 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1447 // immediate offset for stack references.
1448 return 0;
1449 default:
1450 break;
1451 }
1452 break; // At most one FI per instruction
1453 }
1454 }
1455 }
1456
1457 return Limit;
1458}
1459
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001460// In functions that realign the stack, it can be an advantage to spill the
1461// callee-saved vector registers after realigning the stack. The vst1 and vld1
1462// instructions take alignment hints that can improve performance.
1463//
1464static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1465 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1466 if (!SpillAlignedNEONRegs)
1467 return;
1468
1469 // Naked functions don't spill callee-saved registers.
Duncan P. N. Exon Smith2cff9e12015-02-14 02:24:44 +00001470 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001471 return;
1472
1473 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001474 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001475 return;
1476
1477 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001478 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001479 return;
1480
1481 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001482 if (!static_cast<const ARMBaseRegisterInfo *>(
1483 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001484 return;
1485
1486 // We always spill contiguous d-registers starting from d8. Count how many
1487 // needs spilling. The register allocator will almost always use the
1488 // callee-saved registers in order, but it can happen that there are holes in
1489 // the range. Registers above the hole will be spilled to the standard DPRCS
1490 // area.
1491 MachineRegisterInfo &MRI = MF.getRegInfo();
1492 unsigned NumSpills = 0;
1493 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001494 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001495 break;
1496
1497 // Don't do this for just one d-register. It's not worth it.
1498 if (NumSpills < 2)
1499 return;
1500
1501 // Spill the first NumSpills D-registers after realigning the stack.
1502 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1503
1504 // A scratch register is required for the vst1 / vld1 instructions.
1505 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1506}
1507
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001508void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001509ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001510 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001511 // This tells PEI to spill the FP as if it is any other callee-save register
1512 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1513 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1514 // to combine multiple loads / stores.
1515 bool CanEliminateFrame = true;
1516 bool CS1Spilled = false;
1517 bool LRSpilled = false;
1518 unsigned NumGPRSpills = 0;
1519 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1520 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001521 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001522 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001523 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001524 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001525 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1526 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001527 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001528 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1529
1530 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1531 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001532 // since it's not always possible to restore sp from fp in a single
1533 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001534 // FIXME: It will be better just to find spare register here.
1535 if (AFI->isThumb2Function() &&
1536 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001537 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001538
Evan Cheng572756a2011-01-16 05:14:33 +00001539 if (AFI->isThumb1OnlyFunction()) {
1540 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001541 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001542 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001543
Jim Grosbachdca85312011-06-13 21:18:25 +00001544 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1545 // for sure what the stack size will be, but for this, an estimate is good
1546 // enough. If there anything changes it, it'll be a spill, which implies
1547 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001548 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001549 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001550 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001551 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001552 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001553 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001554
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001555 // See if we can spill vector registers to aligned stack.
1556 checkNumAlignedDPRCS2Regs(MF);
1557
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001558 // Spill the BasePtr if it's used.
1559 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001560 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001561
1562 // Don't spill FP if the frame can be eliminated. This is determined
1563 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001564 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001565 for (unsigned i = 0; CSRegs[i]; ++i) {
1566 unsigned Reg = CSRegs[i];
1567 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001568 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001569 Spilled = true;
1570 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001571 }
1572
Craig Topperc7242e02012-04-20 07:30:17 +00001573 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001574 continue;
1575
1576 if (Spilled) {
1577 NumGPRSpills++;
1578
Tim Northover86f60b72014-05-30 13:23:06 +00001579 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001580 if (Reg == ARM::LR)
1581 LRSpilled = true;
1582 CS1Spilled = true;
1583 continue;
1584 }
1585
1586 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1587 switch (Reg) {
1588 case ARM::LR:
1589 LRSpilled = true;
1590 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001591 case ARM::R0: case ARM::R1:
1592 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001593 case ARM::R4: case ARM::R5:
1594 case ARM::R6: case ARM::R7:
1595 CS1Spilled = true;
1596 break;
1597 default:
1598 break;
1599 }
1600 } else {
Tim Northover86f60b72014-05-30 13:23:06 +00001601 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001602 UnspilledCS1GPRs.push_back(Reg);
1603 continue;
1604 }
1605
1606 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001607 case ARM::R0: case ARM::R1:
1608 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001609 case ARM::R4: case ARM::R5:
1610 case ARM::R6: case ARM::R7:
1611 case ARM::LR:
1612 UnspilledCS1GPRs.push_back(Reg);
1613 break;
1614 default:
1615 UnspilledCS2GPRs.push_back(Reg);
1616 break;
1617 }
1618 }
1619 }
1620
1621 bool ForceLRSpill = false;
1622 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1623 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1624 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1625 // use of BL to implement far jump. If it turns out that it's not needed
1626 // then the branch fix up path will undo it.
1627 if (FnSize >= (1 << 11)) {
1628 CanEliminateFrame = false;
1629 ForceLRSpill = true;
1630 }
1631 }
1632
1633 // If any of the stack slot references may be out of range of an immediate
1634 // offset, make sure a register (or a spill slot) is available for the
1635 // register scavenger. Note that if we're indexing off the frame pointer, the
1636 // effective stack size is 4 bytes larger since the FP points to the stack
1637 // slot of the previous FP. Also, if we have variable sized objects in the
1638 // function, stack slot references will often be negative, and some of
1639 // our instructions are positive-offset only, so conservatively consider
1640 // that case to want a spill slot (or register) as well. Similarly, if
1641 // the function adjusts the stack pointer during execution and the
1642 // adjustments aren't already part of our stack size estimate, our offset
1643 // calculations may be off, so be conservative.
1644 // FIXME: We could add logic to be more precise about negative offsets
1645 // and which instructions will need a scratch register for them. Is it
1646 // worth the effort and added fragility?
1647 bool BigStack =
1648 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001649 (MFI->estimateStackSize(MF) +
1650 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001651 estimateRSStackSizeLimit(MF, this)))
1652 || MFI->hasVarSizedObjects()
1653 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1654
1655 bool ExtraCSSpill = false;
1656 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1657 AFI->setHasStackFrame(true);
1658
1659 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1660 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1661 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001662 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001663 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001664 SmallVectorImpl<unsigned>::iterator LRPos;
1665 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1666 (unsigned)ARM::LR);
1667 if (LRPos != UnspilledCS1GPRs.end())
1668 UnspilledCS1GPRs.erase(LRPos);
1669
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001670 ForceLRSpill = false;
1671 ExtraCSSpill = true;
1672 }
1673
1674 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001675 MRI.setPhysRegUsed(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001676 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1677 FramePtr);
1678 if (FPPos != UnspilledCS1GPRs.end())
1679 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001680 NumGPRSpills++;
1681 }
1682
1683 // If stack and double are 8-byte aligned and we are spilling an odd number
1684 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1685 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001686 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001687 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001688 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1689 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1690 unsigned Reg = UnspilledCS1GPRs[i];
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001691 // Don't spill high register if the function is thumb
1692 if (!AFI->isThumbFunction() ||
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001693 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001694 MRI.setPhysRegUsed(Reg);
1695 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001696 ExtraCSSpill = true;
1697 break;
1698 }
1699 }
1700 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1701 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001702 MRI.setPhysRegUsed(Reg);
1703 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001704 ExtraCSSpill = true;
1705 }
1706 }
1707
1708 // Estimate if we might need to scavenge a register at some point in order
1709 // to materialize a stack offset. If so, either spill one additional
1710 // callee-saved register or reserve a special spill slot to facilitate
1711 // register scavenging. Thumb1 needs a spill slot for stack pointer
1712 // adjustments also, even when the frame itself is small.
1713 if (BigStack && !ExtraCSSpill) {
1714 // If any non-reserved CS register isn't spilled, just spill one or two
1715 // extra. That should take care of it!
1716 unsigned NumExtras = TargetAlign / 4;
1717 SmallVector<unsigned, 2> Extras;
1718 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1719 unsigned Reg = UnspilledCS1GPRs.back();
1720 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001721 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001722 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1723 Reg == ARM::LR)) {
1724 Extras.push_back(Reg);
1725 NumExtras--;
1726 }
1727 }
1728 // For non-Thumb1 functions, also check for hi-reg CS registers
1729 if (!AFI->isThumb1OnlyFunction()) {
1730 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1731 unsigned Reg = UnspilledCS2GPRs.back();
1732 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001733 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001734 Extras.push_back(Reg);
1735 NumExtras--;
1736 }
1737 }
1738 }
1739 if (Extras.size() && NumExtras == 0) {
1740 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001741 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001742 }
1743 } else if (!AFI->isThumb1OnlyFunction()) {
1744 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1745 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001746 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001747 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001748 RC->getAlignment(),
1749 false));
1750 }
1751 }
1752 }
1753
1754 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001755 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001756 AFI->setLRIsSpilledForFarJump(true);
1757 }
1758}
Eli Bendersky8da87162013-02-21 20:05:00 +00001759
1760
1761void ARMFrameLowering::
1762eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1763 MachineBasicBlock::iterator I) const {
1764 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001765 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001766 if (!hasReservedCallFrame(MF)) {
1767 // If we have alloca, convert as follows:
1768 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1769 // ADJCALLSTACKUP -> add, sp, sp, amount
1770 MachineInstr *Old = I;
1771 DebugLoc dl = Old->getDebugLoc();
1772 unsigned Amount = Old->getOperand(0).getImm();
1773 if (Amount != 0) {
1774 // We need to keep the stack aligned properly. To do this, we round the
1775 // amount of space needed for the outgoing arguments up to the next
1776 // alignment boundary.
1777 unsigned Align = getStackAlignment();
1778 Amount = (Amount+Align-1)/Align*Align;
1779
1780 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1781 assert(!AFI->isThumb1OnlyFunction() &&
1782 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1783 bool isARM = !AFI->isThumbFunction();
1784
1785 // Replace the pseudo instruction with a new instruction...
1786 unsigned Opc = Old->getOpcode();
1787 int PIdx = Old->findFirstPredOperandIdx();
1788 ARMCC::CondCodes Pred = (PIdx == -1)
1789 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1790 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1791 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1792 unsigned PredReg = Old->getOperand(2).getReg();
1793 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1794 Pred, PredReg);
1795 } else {
1796 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1797 unsigned PredReg = Old->getOperand(3).getReg();
1798 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1799 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1800 Pred, PredReg);
1801 }
1802 }
1803 }
1804 MBB.erase(I);
1805}
1806
Oliver Stannardb14c6252014-04-02 16:10:33 +00001807/// Get the minimum constant for ARM that is greater than or equal to the
1808/// argument. In ARM, constants can have any value that can be produced by
1809/// rotating an 8-bit value to the right by an even number of bits within a
1810/// 32-bit word.
1811static uint32_t alignToARMConstant(uint32_t Value) {
1812 unsigned Shifted = 0;
1813
1814 if (Value == 0)
1815 return 0;
1816
1817 while (!(Value & 0xC0000000)) {
1818 Value = Value << 2;
1819 Shifted += 2;
1820 }
1821
1822 bool Carry = (Value & 0x00FFFFFF);
1823 Value = ((Value & 0xFF000000) >> 24) + Carry;
1824
1825 if (Value & 0x0000100)
1826 Value = Value & 0x000001FC;
1827
1828 if (Shifted > 24)
1829 Value = Value >> (Shifted - 24);
1830 else
1831 Value = Value << (24 - Shifted);
1832
1833 return Value;
1834}
1835
1836// The stack limit in the TCB is set to this many bytes above the actual
1837// stack limit.
1838static const uint64_t kSplitStackAvailable = 256;
1839
1840// Adjust the function prologue to enable split stacks. This currently only
1841// supports android and linux.
1842//
1843// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1844// must be well defined in order to allow for consistent implementations of the
1845// __morestack helper function. The ABI is also not a normal ABI in that it
1846// doesn't follow the normal calling conventions because this allows the
1847// prologue of each function to be optimized further.
1848//
1849// Currently, the ABI looks like (when calling __morestack)
1850//
1851// * r4 holds the minimum stack size requested for this function call
1852// * r5 holds the stack size of the arguments to the function
1853// * the beginning of the function is 3 instructions after the call to
1854// __morestack
1855//
1856// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1857// place the arguments on to the new stack, and the 3-instruction knowledge to
1858// jump directly to the body of the function when working on the new stack.
1859//
1860// An old (and possibly no longer compatible) implementation of __morestack for
1861// ARM can be found at [1].
1862//
1863// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1864void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1865 unsigned Opcode;
1866 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00001867 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00001868 bool Thumb = ST->isThumb();
1869
1870 // Sadly, this currently doesn't support varargs, platforms other than
1871 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1872 if (MF.getFunction()->isVarArg())
1873 report_fatal_error("Segmented stacks do not support vararg functions.");
1874 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001875 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001876
1877 MachineBasicBlock &prologueMBB = MF.front();
1878 MachineFrameInfo *MFI = MF.getFrameInfo();
1879 MachineModuleInfo &MMI = MF.getMMI();
1880 MCContext &Context = MMI.getContext();
1881 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1882 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001883 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00001884 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1885 DebugLoc DL;
1886
Tim Northoverf9e798b2014-05-22 13:03:43 +00001887 uint64_t StackSize = MFI->getStackSize();
1888
1889 // Do not generate a prologue for functions with a stack of size zero
1890 if (StackSize == 0)
1891 return;
1892
Oliver Stannardb14c6252014-04-02 16:10:33 +00001893 // Use R4 and R5 as scratch registers.
1894 // We save R4 and R5 before use and restore them before leaving the function.
1895 unsigned ScratchReg0 = ARM::R4;
1896 unsigned ScratchReg1 = ARM::R5;
1897 uint64_t AlignedStackSize;
1898
1899 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1900 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1901 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1902 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1903 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1904
1905 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1906 e = prologueMBB.livein_end();
1907 i != e; ++i) {
1908 AllocMBB->addLiveIn(*i);
1909 GetMBB->addLiveIn(*i);
1910 McrMBB->addLiveIn(*i);
1911 PrevStackMBB->addLiveIn(*i);
1912 PostStackMBB->addLiveIn(*i);
1913 }
1914
1915 MF.push_front(PostStackMBB);
1916 MF.push_front(AllocMBB);
1917 MF.push_front(GetMBB);
1918 MF.push_front(McrMBB);
1919 MF.push_front(PrevStackMBB);
1920
1921 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001922 AlignedStackSize = alignToARMConstant(StackSize);
1923
1924 // When the frame size is less than 256 we just compare the stack
1925 // boundary directly to the value of the stack pointer, per gcc.
1926 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1927
1928 // We will use two of the callee save registers as scratch registers so we
1929 // need to save those registers onto the stack.
1930 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1931 // requested and arguments for __morestack().
1932 // SR0: Scratch Register #0
1933 // SR1: Scratch Register #1
1934 // push {SR0, SR1}
1935 if (Thumb) {
1936 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1937 .addReg(ScratchReg0).addReg(ScratchReg1);
1938 } else {
1939 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1940 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1941 .addReg(ScratchReg0).addReg(ScratchReg1);
1942 }
1943
1944 // Emit the relevant DWARF information about the change in stack pointer as
1945 // well as where to find both r4 and r5 (the callee-save registers)
1946 CFIIndex =
1947 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1948 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1949 .addCFIIndex(CFIIndex);
1950 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1951 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1952 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1953 .addCFIIndex(CFIIndex);
1954 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1955 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1956 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1957 .addCFIIndex(CFIIndex);
1958
1959 // mov SR1, sp
1960 if (Thumb) {
1961 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1962 .addReg(ARM::SP));
1963 } else if (CompareStackPointer) {
1964 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1965 .addReg(ARM::SP)).addReg(0);
1966 }
1967
1968 // sub SR1, sp, #StackSize
1969 if (!CompareStackPointer && Thumb) {
1970 AddDefaultPred(
1971 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1972 .addReg(ScratchReg1).addImm(AlignedStackSize));
1973 } else if (!CompareStackPointer) {
1974 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1975 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1976 }
1977
1978 if (Thumb && ST->isThumb1Only()) {
1979 unsigned PCLabelId = ARMFI->createPICLabelUId();
1980 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001981 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001982 MachineConstantPool *MCP = MF.getConstantPool();
1983 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1984
1985 // ldr SR0, [pc, offset(STACK_LIMIT)]
1986 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1987 .addConstantPoolIndex(CPI));
1988
1989 // ldr SR0, [SR0]
1990 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1991 .addReg(ScratchReg0).addImm(0));
1992 } else {
1993 // Get TLS base address from the coprocessor
1994 // mrc p15, #0, SR0, c13, c0, #3
1995 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1996 .addImm(15)
1997 .addImm(0)
1998 .addImm(13)
1999 .addImm(0)
2000 .addImm(3));
2001
2002 // Use the last tls slot on android and a private field of the TCP on linux.
2003 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2004 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2005
2006 // Get the stack limit from the right offset
2007 // ldr SR0, [sr0, #4 * TlsOffset]
2008 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2009 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2010 }
2011
2012 // Compare stack limit with stack size requested.
2013 // cmp SR0, SR1
2014 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2015 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2016 .addReg(ScratchReg0)
2017 .addReg(ScratchReg1));
2018
2019 // This jump is taken if StackLimit < SP - stack required.
2020 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2021 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2022 .addImm(ARMCC::LO)
2023 .addReg(ARM::CPSR);
2024
2025
2026 // Calling __morestack(StackSize, Size of stack arguments).
2027 // __morestack knows that the stack size requested is in SR0(r4)
2028 // and amount size of stack arguments is in SR1(r5).
2029
2030 // Pass first argument for the __morestack by Scratch Register #0.
2031 // The amount size of stack required
2032 if (Thumb) {
2033 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2034 ScratchReg0)).addImm(AlignedStackSize));
2035 } else {
2036 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2037 .addImm(AlignedStackSize)).addReg(0);
2038 }
2039 // Pass second argument for the __morestack by Scratch Register #1.
2040 // The amount size of stack consumed to save function arguments.
2041 if (Thumb) {
2042 AddDefaultPred(
2043 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2044 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2045 } else {
2046 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2047 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2048 .addReg(0);
2049 }
2050
2051 // push {lr} - Save return address of this function.
2052 if (Thumb) {
2053 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2054 .addReg(ARM::LR);
2055 } else {
2056 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2057 .addReg(ARM::SP, RegState::Define)
2058 .addReg(ARM::SP))
2059 .addReg(ARM::LR);
2060 }
2061
2062 // Emit the DWARF info about the change in stack as well as where to find the
2063 // previous link register
2064 CFIIndex =
2065 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2066 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2067 .addCFIIndex(CFIIndex);
2068 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2069 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2070 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2071 .addCFIIndex(CFIIndex);
2072
2073 // Call __morestack().
2074 if (Thumb) {
2075 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2076 .addExternalSymbol("__morestack");
2077 } else {
2078 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2079 .addExternalSymbol("__morestack");
2080 }
2081
2082 // pop {lr} - Restore return address of this original function.
2083 if (Thumb) {
2084 if (ST->isThumb1Only()) {
2085 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2086 .addReg(ScratchReg0);
2087 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2088 .addReg(ScratchReg0));
2089 } else {
2090 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2091 .addReg(ARM::LR, RegState::Define)
2092 .addReg(ARM::SP, RegState::Define)
2093 .addReg(ARM::SP)
2094 .addImm(4));
2095 }
2096 } else {
2097 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2098 .addReg(ARM::SP, RegState::Define)
2099 .addReg(ARM::SP))
2100 .addReg(ARM::LR);
2101 }
2102
2103 // Restore SR0 and SR1 in case of __morestack() was called.
2104 // __morestack() will skip PostStackMBB block so we need to restore
2105 // scratch registers from here.
2106 // pop {SR0, SR1}
2107 if (Thumb) {
2108 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2109 .addReg(ScratchReg0)
2110 .addReg(ScratchReg1);
2111 } else {
2112 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2113 .addReg(ARM::SP, RegState::Define)
2114 .addReg(ARM::SP))
2115 .addReg(ScratchReg0)
2116 .addReg(ScratchReg1);
2117 }
2118
2119 // Update the CFA offset now that we've popped
2120 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2121 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2122 .addCFIIndex(CFIIndex);
2123
2124 // bx lr - Return from this function.
2125 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2126 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2127
2128 // Restore SR0 and SR1 in case of __morestack() was not called.
2129 // pop {SR0, SR1}
2130 if (Thumb) {
2131 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2132 .addReg(ScratchReg0)
2133 .addReg(ScratchReg1);
2134 } else {
2135 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2136 .addReg(ARM::SP, RegState::Define)
2137 .addReg(ARM::SP))
2138 .addReg(ScratchReg0)
2139 .addReg(ScratchReg1);
2140 }
2141
2142 // Update the CFA offset now that we've popped
2143 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2144 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2145 .addCFIIndex(CFIIndex);
2146
2147 // Tell debuggers that r4 and r5 are now the same as they were in the
2148 // previous function, that they're the "Same Value".
2149 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2150 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2151 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2152 .addCFIIndex(CFIIndex);
2153 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2154 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2155 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2156 .addCFIIndex(CFIIndex);
2157
2158 // Organizing MBB lists
2159 PostStackMBB->addSuccessor(&prologueMBB);
2160
2161 AllocMBB->addSuccessor(PostStackMBB);
2162
2163 GetMBB->addSuccessor(PostStackMBB);
2164 GetMBB->addSuccessor(AllocMBB);
2165
2166 McrMBB->addSuccessor(GetMBB);
2167
2168 PrevStackMBB->addSuccessor(McrMBB);
2169
2170#ifdef XDEBUG
2171 MF.verify();
2172#endif
2173}