blob: 5a114a94e6f88b5b7254bb43ec8a5f74352488a2 [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
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000042/// hasFP - Return true if the specified function should have a dedicated frame
43/// pointer register. This is true if the function has variable sized allocas
44/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000045bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000046 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
47
Evan Cheng801d98b2012-01-04 01:55:04 +000048 // iOS requires FP not to be clobbered for backtracing purpose.
49 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000050 return true;
51
52 const MachineFrameInfo *MFI = MF.getFrameInfo();
53 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000054 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
55 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000056 RegInfo->needsStackRealignment(MF) ||
57 MFI->hasVarSizedObjects() ||
58 MFI->isFrameAddressTaken());
59}
60
Bob Wilson657f2272011-01-13 21:10:12 +000061/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
62/// not required, we reserve argument space for call sites in the function
63/// immediately on entry to the current function. This eliminates the need for
64/// add/sub sp brackets around call sites. Returns true if the call frame is
65/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000066bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000067 const MachineFrameInfo *FFI = MF.getFrameInfo();
68 unsigned CFSize = FFI->getMaxCallFrameSize();
69 // It's not always a good idea to include the call frame as part of the
70 // stack frame. ARM (especially Thumb) has small immediate offset to
71 // address the stack frame. So a large call frame can cause poor codegen
72 // and may even makes it impossible to scavenge a register.
73 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
74 return false;
75
76 return !MF.getFrameInfo()->hasVarSizedObjects();
77}
78
Bob Wilson657f2272011-01-13 21:10:12 +000079/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
80/// call frame pseudos can be simplified. Unlike most targets, having a FP
81/// is not sufficient here since we still may reference some objects via SP
82/// even when FP is available in Thumb2 mode.
83bool
84ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000085 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
86}
87
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000088static bool isCSRestore(MachineInstr *MI,
89 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +000090 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +000091 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +000092 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +000093 // The first two operands are predicates. The last two are
94 // imp-def and imp-use of SP. Check everything in between.
95 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
96 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
97 return false;
98 return true;
99 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000100 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
101 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000102 MI->getOpcode() == ARM::t2LDR_POST) &&
103 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
104 MI->getOperand(1).getReg() == ARM::SP)
105 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000106
107 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000108}
109
Tim Northoverc9432eb2013-11-04 23:04:15 +0000110static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
112 const ARMBaseInstrInfo &TII, unsigned DestReg,
113 unsigned SrcReg, int NumBytes,
114 unsigned MIFlags = MachineInstr::NoFlags,
115 ARMCC::CondCodes Pred = ARMCC::AL,
116 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000117 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000118 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000119 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000120 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000121 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000122 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000123}
124
Tim Northoverc9432eb2013-11-04 23:04:15 +0000125static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
127 const ARMBaseInstrInfo &TII, int NumBytes,
128 unsigned MIFlags = MachineInstr::NoFlags,
129 ARMCC::CondCodes Pred = ARMCC::AL,
130 unsigned PredReg = 0) {
131 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
132 MIFlags, Pred, PredReg);
133}
134
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000135static int sizeOfSPAdjustment(const MachineInstr *MI) {
136 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
137 int count = 0;
138 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
139 // pred) so the list starts at 4.
140 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
141 count += 8;
142 return count;
143}
144
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000145static bool WindowsRequiresStackProbe(const MachineFunction &MF,
146 size_t StackSizeInBytes) {
147 const MachineFrameInfo *MFI = MF.getFrameInfo();
148 if (MFI->getStackProtectorIndex() > 0)
149 return StackSizeInBytes >= 4080;
150 return StackSizeInBytes >= 4096;
151}
152
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000153void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000154 MachineBasicBlock &MBB = MF.front();
155 MachineBasicBlock::iterator MBBI = MBB.begin();
156 MachineFrameInfo *MFI = MF.getFrameInfo();
157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000158 MachineModuleInfo &MMI = MF.getMMI();
159 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000160 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000161 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000162 const ARMBaseRegisterInfo *RegInfo =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000163 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000164 const ARMBaseInstrInfo &TII =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000165 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000166 assert(!AFI->isThumb1OnlyFunction() &&
167 "This emitPrologue does not support Thumb1!");
168 bool isARM = !AFI->isThumbFunction();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000169 unsigned Align = TM.getFrameLowering()->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000170 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000171 unsigned NumBytes = MFI->getStackSize();
172 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
173 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
174 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000175 int CFAOffset = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000176
177 // Determine the sizes of each callee-save spill areas and record which frame
178 // belongs to which callee-save spill areas.
179 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
180 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000181 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000182
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000183 // All calls are tail calls in GHC calling conv, and functions have no
184 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000185 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
186 return;
187
Oliver Stannardd55e1152014-03-05 15:25:27 +0000188 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000189 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000190 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000191 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000192 CFAOffset -= ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000193 unsigned CFIIndex = MMI.addFrameInst(
194 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
195 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
196 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000197 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000198
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000199 if (!AFI->hasStackFrame() &&
200 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000201 if (NumBytes - ArgRegsSaveSize != 0) {
202 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000203 MachineInstr::FrameSetup);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000204 CFAOffset -= NumBytes - ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000205 unsigned CFIIndex = MMI.addFrameInst(
206 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
207 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
208 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000209 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000210 return;
211 }
212
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000213 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
215 unsigned Reg = CSI[i].getReg();
216 int FI = CSI[i].getFrameIdx();
217 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000218 case ARM::R8:
219 case ARM::R9:
220 case ARM::R10:
221 case ARM::R11:
222 case ARM::R12:
223 if (STI.isTargetMachO()) {
224 GPRCS2Size += 4;
225 break;
226 }
227 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000228 case ARM::R0:
229 case ARM::R1:
230 case ARM::R2:
231 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000232 case ARM::R4:
233 case ARM::R5:
234 case ARM::R6:
235 case ARM::R7:
236 case ARM::LR:
237 if (Reg == FramePtr)
238 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000239 GPRCS1Size += 4;
240 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000241 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000242 // This is a DPR. Exclude the aligned DPRCS2 spills.
243 if (Reg == ARM::D8)
244 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000245 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000246 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000247 }
248 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000249
Eric Christopherb006fc92010-11-18 19:40:05 +0000250 // Move past area 1.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000251 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
252 DPRCSPush;
Tim Northover93bcc662013-11-08 17:18:07 +0000253 if (GPRCS1Size > 0)
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000254 GPRCS1Push = LastPush = MBBI++;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000255
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000256 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000257 bool HasFP = hasFP(MF);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000258 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
259 + GPRCS2Size + DPRCSSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000260 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
261 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
Tim Northover93bcc662013-11-08 17:18:07 +0000262 int FramePtrOffsetInPush = 0;
263 if (HasFP) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000264 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
265 + GPRCS1Size + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000266 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
267 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000268 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000269 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
270 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
271 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
272
Tim Northoverc9432eb2013-11-04 23:04:15 +0000273 // Move past area 2.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000274 if (GPRCS2Size > 0)
275 GPRCS2Push = LastPush = MBBI++;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000276
Eric Christopherb006fc92010-11-18 19:40:05 +0000277 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000278 if (DPRCSSize > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000279 DPRCSPush = MBBI;
Evan Cheng70d29632011-02-25 00:24:46 +0000280 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000281 // instructions in the prologue.
Evan Cheng70d29632011-02-25 00:24:46 +0000282 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
Tim Northover93bcc662013-11-08 17:18:07 +0000283 LastPush = MBBI++;
Evan Cheng70d29632011-02-25 00:24:46 +0000284 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000285
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000286 // Move past the aligned DPRCS2 area.
287 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
288 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
289 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
290 // leaves the stack pointer pointing to the DPRCS2 area.
291 //
292 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
293 NumBytes += MFI->getObjectOffset(D8SpillFI);
294 } else
295 NumBytes = DPRCSOffset;
296
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000297 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
298 uint32_t NumWords = NumBytes >> 2;
299
300 if (NumWords < 65536)
301 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
302 .addImm(NumWords));
303 else
304 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
305 .addImm(NumWords);
306
307 switch (TM.getCodeModel()) {
308 case CodeModel::Small:
309 case CodeModel::Medium:
310 case CodeModel::Default:
311 case CodeModel::Kernel:
312 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
313 .addImm((unsigned)ARMCC::AL).addReg(0)
314 .addExternalSymbol("__chkstk")
315 .addReg(ARM::R4, RegState::Implicit);
316 break;
317 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000318 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000319 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000320 .addExternalSymbol("__chkstk");
321
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000322 BuildMI(MBB, MBBI, dl, TII.get(ARM::BLX))
323 .addReg(ARM::R12, RegState::Kill)
324 .addReg(ARM::R4, RegState::Implicit);
325 break;
326 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000327
328 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
329 ARM::SP)
330 .addReg(ARM::SP, RegState::Define)
331 .addReg(ARM::R4, RegState::Kill)
332 .setMIFlags(MachineInstr::FrameSetup)));
333 NumBytes = 0;
334 }
335
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000336 unsigned adjustedGPRCS1Size = GPRCS1Size;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000337 if (NumBytes) {
338 // Adjust SP after all the callee-save spills.
Tim Northovera4173712013-12-08 15:56:50 +0000339 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000340 if (LastPush == GPRCS1Push) {
Tim Northovera4173712013-12-08 15:56:50 +0000341 FramePtrOffsetInPush += NumBytes;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000342 adjustedGPRCS1Size += NumBytes;
343 NumBytes = 0;
344 }
Tim Northovera4173712013-12-08 15:56:50 +0000345 } else
Tim Northover93bcc662013-11-08 17:18:07 +0000346 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
347 MachineInstr::FrameSetup);
348
Evan Chengeb56dca2010-11-22 18:12:04 +0000349 if (HasFP && isARM)
350 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
351 // Note it's not safe to do this in Thumb2 mode because it would have
352 // taken two instructions:
353 // mov sp, r7
354 // sub sp, #24
355 // If an interrupt is taken between the two instructions, then sp is in
356 // an inconsistent state (pointing to the middle of callee-saved area).
357 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000358 AFI->setShouldRestoreSPFromFP(true);
359 }
360
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000361 if (adjustedGPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000362 CFAOffset -= adjustedGPRCS1Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000363 unsigned CFIIndex = MMI.addFrameInst(
364 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
365 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
366 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
367 .addCFIIndex(CFIIndex);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000368 for (const auto &Entry : CSI) {
369 unsigned Reg = Entry.getReg();
370 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000371 switch (Reg) {
372 case ARM::R8:
373 case ARM::R9:
374 case ARM::R10:
375 case ARM::R11:
376 case ARM::R12:
377 if (STI.isTargetMachO())
378 break;
379 // fallthrough
380 case ARM::R0:
381 case ARM::R1:
382 case ARM::R2:
383 case ARM::R3:
384 case ARM::R4:
385 case ARM::R5:
386 case ARM::R6:
387 case ARM::R7:
388 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000389 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
390 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
391 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
392 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000393 break;
394 }
395 }
396 }
397
Tim Northover93bcc662013-11-08 17:18:07 +0000398 // Set FP to point to the stack slot that contains the previous FP.
399 // For iOS, FP is R7, which has now been stored in spill area 1.
400 // Otherwise, if this is not iOS, all the callee-saved registers go
401 // into spill area 1, including the FP in R11. In either case, it
402 // is in area one and the adjustment needs to take place just after
403 // that push.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000404 if (HasFP) {
405 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
Tim Northover93bcc662013-11-08 17:18:07 +0000406 FramePtr, ARM::SP, FramePtrOffsetInPush,
407 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000408 if (FramePtrOffsetInPush) {
409 CFAOffset += FramePtrOffsetInPush;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000410 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
411 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
412 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
413 .addCFIIndex(CFIIndex);
414
415 } else {
416 unsigned CFIIndex =
417 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
418 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
419 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
420 .addCFIIndex(CFIIndex);
421 }
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000422 }
Tim Northover93bcc662013-11-08 17:18:07 +0000423
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000424 if (GPRCS2Size > 0) {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000425 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000426 if (!HasFP) {
427 CFAOffset -= GPRCS2Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000428 unsigned CFIIndex = MMI.addFrameInst(
429 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
430 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
431 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000432 }
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000433 for (const auto &Entry : CSI) {
434 unsigned Reg = Entry.getReg();
435 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000436 switch (Reg) {
437 case ARM::R8:
438 case ARM::R9:
439 case ARM::R10:
440 case ARM::R11:
441 case ARM::R12:
442 if (STI.isTargetMachO()) {
443 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000444 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000445 unsigned CFIIndex = MMI.addFrameInst(
446 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
447 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
448 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000449 }
450 break;
451 }
452 }
453 }
454
455 if (DPRCSSize > 0) {
456 // Since vpush register list cannot have gaps, there may be multiple vpush
457 // instructions in the prologue.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000458 do {
459 MachineBasicBlock::iterator Push = DPRCSPush++;
460 if (!HasFP) {
Alp Toker98444342014-04-19 23:56:35 +0000461 CFAOffset -= sizeOfSPAdjustment(Push);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000462 unsigned CFIIndex = MMI.addFrameInst(
463 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
464 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
465 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000466 }
467 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
468
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000469 for (const auto &Entry : CSI) {
470 unsigned Reg = Entry.getReg();
471 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000472 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
473 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
474 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
475 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000476 unsigned CFIIndex = MMI.addFrameInst(
477 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
478 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
479 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000480 }
481 }
482 }
483
484 if (NumBytes) {
485 if (!HasFP) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000486 CFAOffset -= NumBytes;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000487 unsigned CFIIndex = MMI.addFrameInst(
488 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
489 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
490 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000491 }
492 }
Tim Northover93bcc662013-11-08 17:18:07 +0000493
Evan Chengeb56dca2010-11-22 18:12:04 +0000494 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000495 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
496 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000497
498 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
499 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
500 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
501
502 // If we need dynamic stack realignment, do it here. Be paranoid and make
503 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000504 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000505 // realigned.
506 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000507 unsigned MaxAlign = MFI->getMaxAlignment();
508 assert (!AFI->isThumb1OnlyFunction());
509 if (!AFI->isThumbFunction()) {
510 // Emit bic sp, sp, MaxAlign
511 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
512 TII.get(ARM::BICri), ARM::SP)
513 .addReg(ARM::SP, RegState::Kill)
514 .addImm(MaxAlign-1)));
515 } else {
516 // We cannot use sp as source/dest register here, thus we're emitting the
517 // following sequence:
518 // mov r4, sp
519 // bic r4, r4, MaxAlign
520 // mov sp, r4
521 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000522 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000523 .addReg(ARM::SP, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000524 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
525 TII.get(ARM::t2BICri), ARM::R4)
526 .addReg(ARM::R4, RegState::Kill)
527 .addImm(MaxAlign-1)));
Jim Grosbache9cc9012011-06-30 23:38:17 +0000528 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000529 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000530 }
531
532 AFI->setShouldRestoreSPFromFP(true);
533 }
534
535 // If we need a base pointer, set it up here. It's whatever the value
536 // of the stack pointer is at this point. Any variable size objects
537 // will be allocated after this, so we can still use the base pointer
538 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000539 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000540 if (RegInfo->hasBasePointer(MF)) {
541 if (isARM)
542 BuildMI(MBB, MBBI, dl,
543 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
544 .addReg(ARM::SP)
545 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
546 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000547 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000548 RegInfo->getBaseRegister())
549 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000550 }
551
552 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000553 // the sp from fp. We can assume there's an FP here since hasFP already
554 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000555 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000556 AFI->setShouldRestoreSPFromFP(true);
557}
558
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000559void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000560 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000561 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000562 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000563 unsigned RetOpcode = MBBI->getOpcode();
564 DebugLoc dl = MBBI->getDebugLoc();
565 MachineFrameInfo *MFI = MF.getFrameInfo();
566 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
567 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
568 const ARMBaseInstrInfo &TII =
569 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
570 assert(!AFI->isThumb1OnlyFunction() &&
571 "This emitEpilogue does not support Thumb1!");
572 bool isARM = !AFI->isThumbFunction();
573
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000574 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
575 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000576 int NumBytes = (int)MFI->getStackSize();
577 unsigned FramePtr = RegInfo->getFrameRegister(MF);
578
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000579 // All calls are tail calls in GHC calling conv, and functions have no
580 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000581 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
582 return;
583
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000584 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000585 if (NumBytes - ArgRegsSaveSize != 0)
586 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000587 } else {
588 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000589 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000590 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000591 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000592 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000593 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000594 if (!isCSRestore(MBBI, TII, CSRegs))
595 ++MBBI;
596 }
597
598 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000599 NumBytes -= (ArgRegsSaveSize +
600 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000601 AFI->getGPRCalleeSavedArea2Size() +
602 AFI->getDPRCalleeSavedAreaSize());
603
604 // Reset SP based on frame pointer only if the stack frame extends beyond
605 // frame pointer stack slot or target is ELF and the function has FP.
606 if (AFI->shouldRestoreSPFromFP()) {
607 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
608 if (NumBytes) {
609 if (isARM)
610 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
611 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000612 else {
613 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000614 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000615 // mov sp, r7
616 // sub sp, #24
617 // This is bad, if an interrupt is taken after the mov, sp is in an
618 // inconsistent state.
619 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000620 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000621 "No scratch register to restore SP from FP!");
622 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000623 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000624 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000625 ARM::SP)
626 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000627 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000628 } else {
629 // Thumb2 or ARM.
630 if (isARM)
631 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
632 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
633 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000634 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000635 ARM::SP)
636 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000637 }
Tim Northoverdee86042013-12-02 14:46:26 +0000638 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000639 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000640 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000641
Eric Christopherb006fc92010-11-18 19:40:05 +0000642 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000643 if (AFI->getDPRCalleeSavedAreaSize()) {
644 MBBI++;
645 // Since vpop register list cannot have gaps, there may be multiple vpop
646 // instructions in the epilogue.
647 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
648 MBBI++;
649 }
Eric Christopherb006fc92010-11-18 19:40:05 +0000650 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
651 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000652 }
653
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000654 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000655 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000656 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000657 MachineOperand &JumpTarget = MBBI->getOperand(0);
658
659 // Jump to label or value in register.
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000660 if (RetOpcode == ARM::TCRETURNdi) {
661 unsigned TCOpcode = STI.isThumb() ?
Tim Northoverd6a729b2014-01-06 14:28:05 +0000662 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000663 ARM::TAILJMPd;
Evan Chengd4b08732010-11-30 23:55:39 +0000664 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
665 if (JumpTarget.isGlobal())
666 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
667 JumpTarget.getTargetFlags());
668 else {
669 assert(JumpTarget.isSymbol());
670 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
671 JumpTarget.getTargetFlags());
672 }
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000673
674 // Add the default predicate in Thumb mode.
675 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000676 } else if (RetOpcode == ARM::TCRETURNri) {
Jim Grosbach3af6fe62011-03-15 00:30:40 +0000677 BuildMI(MBB, MBBI, dl,
678 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000679 addReg(JumpTarget.getReg(), RegState::Kill);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000680 }
681
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000682 MachineInstr *NewMI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000683 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
684 NewMI->addOperand(MBBI->getOperand(i));
685
686 // Delete the pseudo instruction TCRETURN.
687 MBB.erase(MBBI);
Cameron Zwarich033026f2011-06-17 02:16:43 +0000688 MBBI = NewMI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000689 }
690
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000691 if (ArgRegsSaveSize)
692 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000693}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000694
Bob Wilson657f2272011-01-13 21:10:12 +0000695/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
696/// debug info. It's the same as what we use for resolving the code-gen
697/// references for now. FIXME: This can go wrong when references are
698/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000699int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000700ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000701 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000702 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
703}
704
705int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000706ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000707 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000708 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000709 const MachineFrameInfo *MFI = MF.getFrameInfo();
710 const ARMBaseRegisterInfo *RegInfo =
711 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
712 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
713 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
714 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
715 bool isFixed = MFI->isFixedObjectIndex(FI);
716
717 FrameReg = ARM::SP;
718 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000719
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000720 // SP can move around if there are allocas. We may also lose track of SP
721 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000722 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000723
Anton Korobeynikov46877782010-11-20 15:59:32 +0000724 // When dynamically realigning the stack, use the frame pointer for
725 // parameters, and the stack/base pointer for locals.
726 if (RegInfo->needsStackRealignment(MF)) {
727 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
728 if (isFixed) {
729 FrameReg = RegInfo->getFrameRegister(MF);
730 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000731 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000732 assert(RegInfo->hasBasePointer(MF) &&
733 "VLAs and dynamic stack alignment, but missing base pointer!");
734 FrameReg = RegInfo->getBaseRegister();
735 }
736 return Offset;
737 }
738
739 // If there is a frame pointer, use it when we can.
740 if (hasFP(MF) && AFI->hasStackFrame()) {
741 // Use frame pointer to reference fixed objects. Use it for locals if
742 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000743 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000744 FrameReg = RegInfo->getFrameRegister(MF);
745 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000746 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000747 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000748 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000749 // Try to use the frame pointer if we can, else use the base pointer
750 // since it's available. This is handy for the emergency spill slot, in
751 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000752 if (FPOffset >= -255 && FPOffset < 0) {
753 FrameReg = RegInfo->getFrameRegister(MF);
754 return FPOffset;
755 }
Evan Chengc0d20042011-04-22 01:42:52 +0000756 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000757 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000758 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000759 // ldr <rd>, [sp, #<imm8>]
760 // if at all possible to save space.
761 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
762 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000763 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000764 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000765 if (FPOffset >= -255 && FPOffset < 0) {
766 FrameReg = RegInfo->getFrameRegister(MF);
767 return FPOffset;
768 }
769 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
770 // Otherwise, use SP or FP, whichever is closer to the stack slot.
771 FrameReg = RegInfo->getFrameRegister(MF);
772 return FPOffset;
773 }
774 }
775 // Use the base pointer if we have one.
776 if (RegInfo->hasBasePointer(MF))
777 FrameReg = RegInfo->getBaseRegister();
778 return Offset;
779}
780
Bob Wilson657f2272011-01-13 21:10:12 +0000781int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
782 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000783 unsigned FrameReg;
784 return getFrameIndexReference(MF, FI, FrameReg);
785}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000786
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000787void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000788 MachineBasicBlock::iterator MI,
789 const std::vector<CalleeSavedInfo> &CSI,
790 unsigned StmOpc, unsigned StrOpc,
791 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000792 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000793 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000794 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000795 MachineFunction &MF = *MBB.getParent();
796 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
797
798 DebugLoc DL;
799 if (MI != MBB.end()) DL = MI->getDebugLoc();
800
Evan Chengc27c9562010-12-07 19:59:34 +0000801 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000802 unsigned i = CSI.size();
803 while (i != 0) {
804 unsigned LastReg = 0;
805 for (; i != 0; --i) {
806 unsigned Reg = CSI[i-1].getReg();
Tim Northoverd6a729b2014-01-06 14:28:05 +0000807 if (!(Func)(Reg, STI.isTargetMachO())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000808
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000809 // D-registers in the aligned area DPRCS2 are NOT spilled here.
810 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
811 continue;
812
Evan Cheng775ead32010-12-07 23:08:38 +0000813 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000814 // @llvm.returnaddress is called. If LR is returned for
815 // @llvm.returnaddress then it's already added to the function and
816 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000817 bool isKill = true;
818 if (Reg == ARM::LR) {
819 if (MF.getFrameInfo()->isReturnAddressTaken() &&
820 MF.getRegInfo().isLiveIn(Reg))
821 isKill = false;
822 }
823
824 if (isKill)
825 MBB.addLiveIn(Reg);
826
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000827 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000828 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000829 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000830 if (NoGap && LastReg && LastReg != Reg-1)
831 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000832 LastReg = Reg;
833 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000834 }
835
Jim Grosbach5fccad82010-12-09 18:31:13 +0000836 if (Regs.empty())
837 continue;
838 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000839 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000840 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000841 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000842 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
843 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000844 } else if (Regs.size() == 1) {
845 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
846 ARM::SP)
847 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000848 .addReg(ARM::SP).setMIFlags(MIFlags)
849 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000850 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000851 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000852 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000853
854 // Put any subsequent vpush instructions before this one: they will refer to
855 // higher register numbers so need to be pushed first in order to preserve
856 // monotonicity.
857 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000858 }
Evan Cheng775ead32010-12-07 23:08:38 +0000859}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000860
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000861void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000862 MachineBasicBlock::iterator MI,
863 const std::vector<CalleeSavedInfo> &CSI,
864 unsigned LdmOpc, unsigned LdrOpc,
865 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000866 bool(*Func)(unsigned, bool),
867 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000868 MachineFunction &MF = *MBB.getParent();
869 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
870 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
871 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +0000872 unsigned RetOpcode = MI->getOpcode();
873 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000874 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +0000875 bool isInterrupt =
876 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +0000877
878 SmallVector<unsigned, 4> Regs;
879 unsigned i = CSI.size();
880 while (i != 0) {
881 unsigned LastReg = 0;
882 bool DeleteRet = false;
883 for (; i != 0; --i) {
884 unsigned Reg = CSI[i-1].getReg();
Tim Northoverd6a729b2014-01-06 14:28:05 +0000885 if (!(Func)(Reg, STI.isTargetMachO())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000886
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000887 // The aligned reloads from area DPRCS2 are not inserted here.
888 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
889 continue;
890
Tim Northoverd8407452013-10-01 14:33:28 +0000891 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
892 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +0000893 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000894 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +0000895 // Fold the return instruction into the LDM.
896 DeleteRet = true;
897 }
898
Evan Cheng9d54ae62010-12-08 06:29:02 +0000899 // If NoGap is true, pop consecutive registers and then leave the rest
900 // for other instructions. e.g.
901 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
902 if (NoGap && LastReg && LastReg != Reg-1)
903 break;
904
Evan Cheng775ead32010-12-07 23:08:38 +0000905 LastReg = Reg;
906 Regs.push_back(Reg);
907 }
908
Jim Grosbach5fccad82010-12-09 18:31:13 +0000909 if (Regs.empty())
910 continue;
911 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000912 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000913 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +0000914 .addReg(ARM::SP));
915 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
916 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +0000917 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +0000918 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +0000919 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +0000920 }
Evan Cheng775ead32010-12-07 23:08:38 +0000921 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000922 } else if (Regs.size() == 1) {
923 // If we adjusted the reg to PC from LR above, switch it back here. We
924 // only do that for LDM.
925 if (Regs[0] == ARM::PC)
926 Regs[0] = ARM::LR;
927 MachineInstrBuilder MIB =
928 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
929 .addReg(ARM::SP, RegState::Define)
930 .addReg(ARM::SP);
931 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
932 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +0000933 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +0000934 MIB.addReg(0);
935 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
936 } else
937 MIB.addImm(4);
938 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000939 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000940 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000941
942 // Put any subsequent vpop instructions after this one: they will refer to
943 // higher register numbers so need to be popped afterwards.
944 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +0000945 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000946}
947
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000948/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000949/// starting from d8. Also insert stack realignment code and leave the stack
950/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000951static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
952 MachineBasicBlock::iterator MI,
953 unsigned NumAlignedDPRCS2Regs,
954 const std::vector<CalleeSavedInfo> &CSI,
955 const TargetRegisterInfo *TRI) {
956 MachineFunction &MF = *MBB.getParent();
957 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
958 DebugLoc DL = MI->getDebugLoc();
959 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
960 MachineFrameInfo &MFI = *MF.getFrameInfo();
961
962 // Mark the D-register spill slots as properly aligned. Since MFI computes
963 // stack slot layout backwards, this can actually mean that the d-reg stack
964 // slot offsets can be wrong. The offset for d8 will always be correct.
965 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
966 unsigned DNum = CSI[i].getReg() - ARM::D8;
967 if (DNum >= 8)
968 continue;
969 int FI = CSI[i].getFrameIdx();
970 // The even-numbered registers will be 16-byte aligned, the odd-numbered
971 // registers will be 8-byte aligned.
972 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
973
974 // The stack slot for D8 needs to be maximally aligned because this is
975 // actually the point where we align the stack pointer. MachineFrameInfo
976 // computes all offsets relative to the incoming stack pointer which is a
977 // bit weird when realigning the stack. Any extra padding for this
978 // over-alignment is not realized because the code inserted below adjusts
979 // the stack pointer by numregs * 8 before aligning the stack pointer.
980 if (DNum == 0)
981 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
982 }
983
984 // Move the stack pointer to the d8 spill slot, and align it at the same
985 // time. Leave the stack slot address in the scratch register r4.
986 //
987 // sub r4, sp, #numregs * 8
988 // bic r4, r4, #align - 1
989 // mov sp, r4
990 //
991 bool isThumb = AFI->isThumbFunction();
992 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
993 AFI->setShouldRestoreSPFromFP(true);
994
995 // sub r4, sp, #numregs * 8
996 // The immediate is <= 64, so it doesn't need any special encoding.
997 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
998 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
999 .addReg(ARM::SP)
1000 .addImm(8 * NumAlignedDPRCS2Regs)));
1001
1002 // bic r4, r4, #align-1
1003 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1004 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1005 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1006 .addReg(ARM::R4, RegState::Kill)
1007 .addImm(MaxAlign - 1)));
1008
1009 // mov sp, r4
1010 // The stack pointer must be adjusted before spilling anything, otherwise
1011 // the stack slots could be clobbered by an interrupt handler.
1012 // Leave r4 live, it is used below.
1013 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1014 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1015 .addReg(ARM::R4);
1016 MIB = AddDefaultPred(MIB);
1017 if (!isThumb)
1018 AddDefaultCC(MIB);
1019
1020 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1021 // r4 holds the stack slot address.
1022 unsigned NextReg = ARM::D8;
1023
1024 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1025 // The writeback is only needed when emitting two vst1.64 instructions.
1026 if (NumAlignedDPRCS2Regs >= 6) {
1027 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001028 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001029 MBB.addLiveIn(SupReg);
1030 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1031 ARM::R4)
1032 .addReg(ARM::R4, RegState::Kill).addImm(16)
1033 .addReg(NextReg)
1034 .addReg(SupReg, RegState::ImplicitKill));
1035 NextReg += 4;
1036 NumAlignedDPRCS2Regs -= 4;
1037 }
1038
1039 // We won't modify r4 beyond this point. It currently points to the next
1040 // register to be spilled.
1041 unsigned R4BaseReg = NextReg;
1042
1043 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1044 if (NumAlignedDPRCS2Regs >= 4) {
1045 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001046 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001047 MBB.addLiveIn(SupReg);
1048 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1049 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1050 .addReg(SupReg, RegState::ImplicitKill));
1051 NextReg += 4;
1052 NumAlignedDPRCS2Regs -= 4;
1053 }
1054
1055 // 16-byte aligned vst1.64 with 2 d-regs.
1056 if (NumAlignedDPRCS2Regs >= 2) {
1057 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001058 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001059 MBB.addLiveIn(SupReg);
1060 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001061 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001062 NextReg += 2;
1063 NumAlignedDPRCS2Regs -= 2;
1064 }
1065
1066 // Finally, use a vanilla vstr.64 for the odd last register.
1067 if (NumAlignedDPRCS2Regs) {
1068 MBB.addLiveIn(NextReg);
1069 // vstr.64 uses addrmode5 which has an offset scale of 4.
1070 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1071 .addReg(NextReg)
1072 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1073 }
1074
1075 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001076 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001077}
1078
1079/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1080/// iterator to the following instruction.
1081static MachineBasicBlock::iterator
1082skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1083 unsigned NumAlignedDPRCS2Regs) {
1084 // sub r4, sp, #numregs * 8
1085 // bic r4, r4, #align - 1
1086 // mov sp, r4
1087 ++MI; ++MI; ++MI;
1088 assert(MI->mayStore() && "Expecting spill instruction");
1089
1090 // These switches all fall through.
1091 switch(NumAlignedDPRCS2Regs) {
1092 case 7:
1093 ++MI;
1094 assert(MI->mayStore() && "Expecting spill instruction");
1095 default:
1096 ++MI;
1097 assert(MI->mayStore() && "Expecting spill instruction");
1098 case 1:
1099 case 2:
1100 case 4:
1101 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1102 ++MI;
1103 }
1104 return MI;
1105}
1106
1107/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1108/// starting from d8. These instructions are assumed to execute while the
1109/// stack is still aligned, unlike the code inserted by emitPopInst.
1110static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1111 MachineBasicBlock::iterator MI,
1112 unsigned NumAlignedDPRCS2Regs,
1113 const std::vector<CalleeSavedInfo> &CSI,
1114 const TargetRegisterInfo *TRI) {
1115 MachineFunction &MF = *MBB.getParent();
1116 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1117 DebugLoc DL = MI->getDebugLoc();
1118 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1119
1120 // Find the frame index assigned to d8.
1121 int D8SpillFI = 0;
1122 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1123 if (CSI[i].getReg() == ARM::D8) {
1124 D8SpillFI = CSI[i].getFrameIdx();
1125 break;
1126 }
1127
1128 // Materialize the address of the d8 spill slot into the scratch register r4.
1129 // This can be fairly complicated if the stack frame is large, so just use
1130 // the normal frame index elimination mechanism to do it. This code runs as
1131 // the initial part of the epilog where the stack and base pointers haven't
1132 // been changed yet.
1133 bool isThumb = AFI->isThumbFunction();
1134 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1135
1136 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1137 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1138 .addFrameIndex(D8SpillFI).addImm(0)));
1139
1140 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1141 unsigned NextReg = ARM::D8;
1142
1143 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1144 if (NumAlignedDPRCS2Regs >= 6) {
1145 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001146 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001147 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1148 .addReg(ARM::R4, RegState::Define)
1149 .addReg(ARM::R4, RegState::Kill).addImm(16)
1150 .addReg(SupReg, RegState::ImplicitDefine));
1151 NextReg += 4;
1152 NumAlignedDPRCS2Regs -= 4;
1153 }
1154
1155 // We won't modify r4 beyond this point. It currently points to the next
1156 // register to be spilled.
1157 unsigned R4BaseReg = NextReg;
1158
1159 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1160 if (NumAlignedDPRCS2Regs >= 4) {
1161 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001162 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001163 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1164 .addReg(ARM::R4).addImm(16)
1165 .addReg(SupReg, RegState::ImplicitDefine));
1166 NextReg += 4;
1167 NumAlignedDPRCS2Regs -= 4;
1168 }
1169
1170 // 16-byte aligned vld1.64 with 2 d-regs.
1171 if (NumAlignedDPRCS2Regs >= 2) {
1172 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001173 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001174 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1175 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001176 NextReg += 2;
1177 NumAlignedDPRCS2Regs -= 2;
1178 }
1179
1180 // Finally, use a vanilla vldr.64 for the remaining odd register.
1181 if (NumAlignedDPRCS2Regs)
1182 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1183 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1184
1185 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001186 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001187}
1188
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001189bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001190 MachineBasicBlock::iterator MI,
1191 const std::vector<CalleeSavedInfo> &CSI,
1192 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001193 if (CSI.empty())
1194 return false;
1195
1196 MachineFunction &MF = *MBB.getParent();
1197 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001198
1199 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001200 unsigned PushOneOpc = AFI->isThumbFunction() ?
1201 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001202 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001203 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1204 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001205 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001206 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001207 MachineInstr::FrameSetup);
1208 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001209 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1210
1211 // The code above does not insert spill code for the aligned DPRCS2 registers.
1212 // The stack realignment code will be inserted between the push instructions
1213 // and these spills.
1214 if (NumAlignedDPRCS2Regs)
1215 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001216
1217 return true;
1218}
1219
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001220bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001221 MachineBasicBlock::iterator MI,
1222 const std::vector<CalleeSavedInfo> &CSI,
1223 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001224 if (CSI.empty())
1225 return false;
1226
1227 MachineFunction &MF = *MBB.getParent();
1228 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001229 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001230 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1231
1232 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1233 // registers. Do that here instead.
1234 if (NumAlignedDPRCS2Regs)
1235 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001236
1237 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001238 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001239 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001240 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1241 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001242 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001243 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001244 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001245 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001246
1247 return true;
1248}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001249
1250// FIXME: Make generic?
1251static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1252 const ARMBaseInstrInfo &TII) {
1253 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001254 for (auto &MBB : MF) {
1255 for (auto &MI : MBB)
1256 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001257 }
1258 return FnSize;
1259}
1260
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001261/// estimateRSStackSizeLimit - Look at each instruction that references stack
1262/// frames and return the stack size limit beyond which some of these
1263/// instructions will require a scratch register during their expansion later.
1264// FIXME: Move to TII?
1265static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001266 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001267 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1268 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001269 for (auto &MBB : MF) {
1270 for (auto &MI : MBB) {
1271 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1272 if (!MI.getOperand(i).isFI())
1273 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001274
1275 // When using ADDri to get the address of a stack object, 255 is the
1276 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001277 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001278 Limit = std::min(Limit, (1U << 8) - 1);
1279 break;
1280 }
1281
1282 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001283 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001284 case ARMII::AddrMode3:
1285 case ARMII::AddrModeT2_i8:
1286 Limit = std::min(Limit, (1U << 8) - 1);
1287 break;
1288 case ARMII::AddrMode5:
1289 case ARMII::AddrModeT2_i8s4:
1290 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1291 break;
1292 case ARMII::AddrModeT2_i12:
1293 // i12 supports only positive offset so these will be converted to
1294 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1295 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1296 Limit = std::min(Limit, (1U << 8) - 1);
1297 break;
1298 case ARMII::AddrMode4:
1299 case ARMII::AddrMode6:
1300 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1301 // immediate offset for stack references.
1302 return 0;
1303 default:
1304 break;
1305 }
1306 break; // At most one FI per instruction
1307 }
1308 }
1309 }
1310
1311 return Limit;
1312}
1313
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001314// In functions that realign the stack, it can be an advantage to spill the
1315// callee-saved vector registers after realigning the stack. The vst1 and vld1
1316// instructions take alignment hints that can improve performance.
1317//
1318static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1319 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1320 if (!SpillAlignedNEONRegs)
1321 return;
1322
1323 // Naked functions don't spill callee-saved registers.
Bill Wendling698e84f2012-12-30 10:32:01 +00001324 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1325 Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001326 return;
1327
1328 // We are planning to use NEON instructions vst1 / vld1.
1329 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1330 return;
1331
1332 // Don't bother if the default stack alignment is sufficiently high.
1333 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1334 return;
1335
1336 // Aligned spills require stack realignment.
1337 const ARMBaseRegisterInfo *RegInfo =
1338 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1339 if (!RegInfo->canRealignStack(MF))
1340 return;
1341
1342 // We always spill contiguous d-registers starting from d8. Count how many
1343 // needs spilling. The register allocator will almost always use the
1344 // callee-saved registers in order, but it can happen that there are holes in
1345 // the range. Registers above the hole will be spilled to the standard DPRCS
1346 // area.
1347 MachineRegisterInfo &MRI = MF.getRegInfo();
1348 unsigned NumSpills = 0;
1349 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001350 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001351 break;
1352
1353 // Don't do this for just one d-register. It's not worth it.
1354 if (NumSpills < 2)
1355 return;
1356
1357 // Spill the first NumSpills D-registers after realigning the stack.
1358 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1359
1360 // A scratch register is required for the vst1 / vld1 instructions.
1361 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1362}
1363
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001364void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001365ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001366 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001367 // This tells PEI to spill the FP as if it is any other callee-save register
1368 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1369 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1370 // to combine multiple loads / stores.
1371 bool CanEliminateFrame = true;
1372 bool CS1Spilled = false;
1373 bool LRSpilled = false;
1374 unsigned NumGPRSpills = 0;
1375 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1376 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1377 const ARMBaseRegisterInfo *RegInfo =
1378 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1379 const ARMBaseInstrInfo &TII =
1380 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1381 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1382 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001383 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001384 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1385
1386 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1387 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001388 // since it's not always possible to restore sp from fp in a single
1389 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001390 // FIXME: It will be better just to find spare register here.
1391 if (AFI->isThumb2Function() &&
1392 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001393 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001394
Evan Cheng572756a2011-01-16 05:14:33 +00001395 if (AFI->isThumb1OnlyFunction()) {
1396 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001397 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001398 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001399
Jim Grosbachdca85312011-06-13 21:18:25 +00001400 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1401 // for sure what the stack size will be, but for this, an estimate is good
1402 // enough. If there anything changes it, it'll be a spill, which implies
1403 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001404 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001405 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001406 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001407 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001408 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001409 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001410
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001411 // See if we can spill vector registers to aligned stack.
1412 checkNumAlignedDPRCS2Regs(MF);
1413
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001414 // Spill the BasePtr if it's used.
1415 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001416 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001417
1418 // Don't spill FP if the frame can be eliminated. This is determined
1419 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001420 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001421 for (unsigned i = 0; CSRegs[i]; ++i) {
1422 unsigned Reg = CSRegs[i];
1423 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001424 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001425 Spilled = true;
1426 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001427 }
1428
Craig Topperc7242e02012-04-20 07:30:17 +00001429 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001430 continue;
1431
1432 if (Spilled) {
1433 NumGPRSpills++;
1434
Tim Northoverd6a729b2014-01-06 14:28:05 +00001435 if (!STI.isTargetMachO()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001436 if (Reg == ARM::LR)
1437 LRSpilled = true;
1438 CS1Spilled = true;
1439 continue;
1440 }
1441
1442 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1443 switch (Reg) {
1444 case ARM::LR:
1445 LRSpilled = true;
1446 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001447 case ARM::R0: case ARM::R1:
1448 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001449 case ARM::R4: case ARM::R5:
1450 case ARM::R6: case ARM::R7:
1451 CS1Spilled = true;
1452 break;
1453 default:
1454 break;
1455 }
1456 } else {
Tim Northoverd6a729b2014-01-06 14:28:05 +00001457 if (!STI.isTargetMachO()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001458 UnspilledCS1GPRs.push_back(Reg);
1459 continue;
1460 }
1461
1462 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001463 case ARM::R0: case ARM::R1:
1464 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001465 case ARM::R4: case ARM::R5:
1466 case ARM::R6: case ARM::R7:
1467 case ARM::LR:
1468 UnspilledCS1GPRs.push_back(Reg);
1469 break;
1470 default:
1471 UnspilledCS2GPRs.push_back(Reg);
1472 break;
1473 }
1474 }
1475 }
1476
1477 bool ForceLRSpill = false;
1478 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1479 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1480 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1481 // use of BL to implement far jump. If it turns out that it's not needed
1482 // then the branch fix up path will undo it.
1483 if (FnSize >= (1 << 11)) {
1484 CanEliminateFrame = false;
1485 ForceLRSpill = true;
1486 }
1487 }
1488
1489 // If any of the stack slot references may be out of range of an immediate
1490 // offset, make sure a register (or a spill slot) is available for the
1491 // register scavenger. Note that if we're indexing off the frame pointer, the
1492 // effective stack size is 4 bytes larger since the FP points to the stack
1493 // slot of the previous FP. Also, if we have variable sized objects in the
1494 // function, stack slot references will often be negative, and some of
1495 // our instructions are positive-offset only, so conservatively consider
1496 // that case to want a spill slot (or register) as well. Similarly, if
1497 // the function adjusts the stack pointer during execution and the
1498 // adjustments aren't already part of our stack size estimate, our offset
1499 // calculations may be off, so be conservative.
1500 // FIXME: We could add logic to be more precise about negative offsets
1501 // and which instructions will need a scratch register for them. Is it
1502 // worth the effort and added fragility?
1503 bool BigStack =
1504 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001505 (MFI->estimateStackSize(MF) +
1506 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001507 estimateRSStackSizeLimit(MF, this)))
1508 || MFI->hasVarSizedObjects()
1509 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1510
1511 bool ExtraCSSpill = false;
1512 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1513 AFI->setHasStackFrame(true);
1514
1515 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1516 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1517 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001518 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001519 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001520 SmallVectorImpl<unsigned>::iterator LRPos;
1521 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1522 (unsigned)ARM::LR);
1523 if (LRPos != UnspilledCS1GPRs.end())
1524 UnspilledCS1GPRs.erase(LRPos);
1525
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001526 ForceLRSpill = false;
1527 ExtraCSSpill = true;
1528 }
1529
1530 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001531 MRI.setPhysRegUsed(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001532 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1533 FramePtr);
1534 if (FPPos != UnspilledCS1GPRs.end())
1535 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001536 NumGPRSpills++;
1537 }
1538
1539 // If stack and double are 8-byte aligned and we are spilling an odd number
1540 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1541 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001542 unsigned TargetAlign = getStackAlignment();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001543 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1544 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1545 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1546 unsigned Reg = UnspilledCS1GPRs[i];
1547 // Don't spill high register if the function is thumb1
1548 if (!AFI->isThumb1OnlyFunction() ||
1549 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001550 MRI.setPhysRegUsed(Reg);
1551 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001552 ExtraCSSpill = true;
1553 break;
1554 }
1555 }
1556 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1557 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001558 MRI.setPhysRegUsed(Reg);
1559 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001560 ExtraCSSpill = true;
1561 }
1562 }
1563
1564 // Estimate if we might need to scavenge a register at some point in order
1565 // to materialize a stack offset. If so, either spill one additional
1566 // callee-saved register or reserve a special spill slot to facilitate
1567 // register scavenging. Thumb1 needs a spill slot for stack pointer
1568 // adjustments also, even when the frame itself is small.
1569 if (BigStack && !ExtraCSSpill) {
1570 // If any non-reserved CS register isn't spilled, just spill one or two
1571 // extra. That should take care of it!
1572 unsigned NumExtras = TargetAlign / 4;
1573 SmallVector<unsigned, 2> Extras;
1574 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1575 unsigned Reg = UnspilledCS1GPRs.back();
1576 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001577 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001578 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1579 Reg == ARM::LR)) {
1580 Extras.push_back(Reg);
1581 NumExtras--;
1582 }
1583 }
1584 // For non-Thumb1 functions, also check for hi-reg CS registers
1585 if (!AFI->isThumb1OnlyFunction()) {
1586 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1587 unsigned Reg = UnspilledCS2GPRs.back();
1588 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001589 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001590 Extras.push_back(Reg);
1591 NumExtras--;
1592 }
1593 }
1594 }
1595 if (Extras.size() && NumExtras == 0) {
1596 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001597 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001598 }
1599 } else if (!AFI->isThumb1OnlyFunction()) {
1600 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1601 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001602 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001603 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001604 RC->getAlignment(),
1605 false));
1606 }
1607 }
1608 }
1609
1610 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001611 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001612 AFI->setLRIsSpilledForFarJump(true);
1613 }
1614}
Eli Bendersky8da87162013-02-21 20:05:00 +00001615
1616
1617void ARMFrameLowering::
1618eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1619 MachineBasicBlock::iterator I) const {
1620 const ARMBaseInstrInfo &TII =
1621 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1622 if (!hasReservedCallFrame(MF)) {
1623 // If we have alloca, convert as follows:
1624 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1625 // ADJCALLSTACKUP -> add, sp, sp, amount
1626 MachineInstr *Old = I;
1627 DebugLoc dl = Old->getDebugLoc();
1628 unsigned Amount = Old->getOperand(0).getImm();
1629 if (Amount != 0) {
1630 // We need to keep the stack aligned properly. To do this, we round the
1631 // amount of space needed for the outgoing arguments up to the next
1632 // alignment boundary.
1633 unsigned Align = getStackAlignment();
1634 Amount = (Amount+Align-1)/Align*Align;
1635
1636 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1637 assert(!AFI->isThumb1OnlyFunction() &&
1638 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1639 bool isARM = !AFI->isThumbFunction();
1640
1641 // Replace the pseudo instruction with a new instruction...
1642 unsigned Opc = Old->getOpcode();
1643 int PIdx = Old->findFirstPredOperandIdx();
1644 ARMCC::CondCodes Pred = (PIdx == -1)
1645 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1646 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1647 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1648 unsigned PredReg = Old->getOperand(2).getReg();
1649 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1650 Pred, PredReg);
1651 } else {
1652 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1653 unsigned PredReg = Old->getOperand(3).getReg();
1654 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1655 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1656 Pred, PredReg);
1657 }
1658 }
1659 }
1660 MBB.erase(I);
1661}
1662
Oliver Stannardb14c6252014-04-02 16:10:33 +00001663/// Get the minimum constant for ARM that is greater than or equal to the
1664/// argument. In ARM, constants can have any value that can be produced by
1665/// rotating an 8-bit value to the right by an even number of bits within a
1666/// 32-bit word.
1667static uint32_t alignToARMConstant(uint32_t Value) {
1668 unsigned Shifted = 0;
1669
1670 if (Value == 0)
1671 return 0;
1672
1673 while (!(Value & 0xC0000000)) {
1674 Value = Value << 2;
1675 Shifted += 2;
1676 }
1677
1678 bool Carry = (Value & 0x00FFFFFF);
1679 Value = ((Value & 0xFF000000) >> 24) + Carry;
1680
1681 if (Value & 0x0000100)
1682 Value = Value & 0x000001FC;
1683
1684 if (Shifted > 24)
1685 Value = Value >> (Shifted - 24);
1686 else
1687 Value = Value << (24 - Shifted);
1688
1689 return Value;
1690}
1691
1692// The stack limit in the TCB is set to this many bytes above the actual
1693// stack limit.
1694static const uint64_t kSplitStackAvailable = 256;
1695
1696// Adjust the function prologue to enable split stacks. This currently only
1697// supports android and linux.
1698//
1699// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1700// must be well defined in order to allow for consistent implementations of the
1701// __morestack helper function. The ABI is also not a normal ABI in that it
1702// doesn't follow the normal calling conventions because this allows the
1703// prologue of each function to be optimized further.
1704//
1705// Currently, the ABI looks like (when calling __morestack)
1706//
1707// * r4 holds the minimum stack size requested for this function call
1708// * r5 holds the stack size of the arguments to the function
1709// * the beginning of the function is 3 instructions after the call to
1710// __morestack
1711//
1712// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1713// place the arguments on to the new stack, and the 3-instruction knowledge to
1714// jump directly to the body of the function when working on the new stack.
1715//
1716// An old (and possibly no longer compatible) implementation of __morestack for
1717// ARM can be found at [1].
1718//
1719// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1720void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1721 unsigned Opcode;
1722 unsigned CFIIndex;
1723 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1724 bool Thumb = ST->isThumb();
1725
1726 // Sadly, this currently doesn't support varargs, platforms other than
1727 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1728 if (MF.getFunction()->isVarArg())
1729 report_fatal_error("Segmented stacks do not support vararg functions.");
1730 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001731 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001732
1733 MachineBasicBlock &prologueMBB = MF.front();
1734 MachineFrameInfo *MFI = MF.getFrameInfo();
1735 MachineModuleInfo &MMI = MF.getMMI();
1736 MCContext &Context = MMI.getContext();
1737 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1738 const ARMBaseInstrInfo &TII =
1739 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1740 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1741 DebugLoc DL;
1742
1743 // Use R4 and R5 as scratch registers.
1744 // We save R4 and R5 before use and restore them before leaving the function.
1745 unsigned ScratchReg0 = ARM::R4;
1746 unsigned ScratchReg1 = ARM::R5;
1747 uint64_t AlignedStackSize;
1748
1749 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1750 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1751 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1752 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1753 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1754
1755 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1756 e = prologueMBB.livein_end();
1757 i != e; ++i) {
1758 AllocMBB->addLiveIn(*i);
1759 GetMBB->addLiveIn(*i);
1760 McrMBB->addLiveIn(*i);
1761 PrevStackMBB->addLiveIn(*i);
1762 PostStackMBB->addLiveIn(*i);
1763 }
1764
1765 MF.push_front(PostStackMBB);
1766 MF.push_front(AllocMBB);
1767 MF.push_front(GetMBB);
1768 MF.push_front(McrMBB);
1769 MF.push_front(PrevStackMBB);
1770
1771 // The required stack size that is aligned to ARM constant criterion.
1772 uint64_t StackSize = MFI->getStackSize();
1773
1774 AlignedStackSize = alignToARMConstant(StackSize);
1775
1776 // When the frame size is less than 256 we just compare the stack
1777 // boundary directly to the value of the stack pointer, per gcc.
1778 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1779
1780 // We will use two of the callee save registers as scratch registers so we
1781 // need to save those registers onto the stack.
1782 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1783 // requested and arguments for __morestack().
1784 // SR0: Scratch Register #0
1785 // SR1: Scratch Register #1
1786 // push {SR0, SR1}
1787 if (Thumb) {
1788 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1789 .addReg(ScratchReg0).addReg(ScratchReg1);
1790 } else {
1791 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1792 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1793 .addReg(ScratchReg0).addReg(ScratchReg1);
1794 }
1795
1796 // Emit the relevant DWARF information about the change in stack pointer as
1797 // well as where to find both r4 and r5 (the callee-save registers)
1798 CFIIndex =
1799 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1800 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1801 .addCFIIndex(CFIIndex);
1802 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1803 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1804 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1805 .addCFIIndex(CFIIndex);
1806 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1807 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1808 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1809 .addCFIIndex(CFIIndex);
1810
1811 // mov SR1, sp
1812 if (Thumb) {
1813 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1814 .addReg(ARM::SP));
1815 } else if (CompareStackPointer) {
1816 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1817 .addReg(ARM::SP)).addReg(0);
1818 }
1819
1820 // sub SR1, sp, #StackSize
1821 if (!CompareStackPointer && Thumb) {
1822 AddDefaultPred(
1823 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1824 .addReg(ScratchReg1).addImm(AlignedStackSize));
1825 } else if (!CompareStackPointer) {
1826 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1827 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1828 }
1829
1830 if (Thumb && ST->isThumb1Only()) {
1831 unsigned PCLabelId = ARMFI->createPICLabelUId();
1832 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001833 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001834 MachineConstantPool *MCP = MF.getConstantPool();
1835 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1836
1837 // ldr SR0, [pc, offset(STACK_LIMIT)]
1838 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1839 .addConstantPoolIndex(CPI));
1840
1841 // ldr SR0, [SR0]
1842 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1843 .addReg(ScratchReg0).addImm(0));
1844 } else {
1845 // Get TLS base address from the coprocessor
1846 // mrc p15, #0, SR0, c13, c0, #3
1847 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1848 .addImm(15)
1849 .addImm(0)
1850 .addImm(13)
1851 .addImm(0)
1852 .addImm(3));
1853
1854 // Use the last tls slot on android and a private field of the TCP on linux.
1855 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1856 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1857
1858 // Get the stack limit from the right offset
1859 // ldr SR0, [sr0, #4 * TlsOffset]
1860 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1861 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1862 }
1863
1864 // Compare stack limit with stack size requested.
1865 // cmp SR0, SR1
1866 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1867 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1868 .addReg(ScratchReg0)
1869 .addReg(ScratchReg1));
1870
1871 // This jump is taken if StackLimit < SP - stack required.
1872 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1873 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1874 .addImm(ARMCC::LO)
1875 .addReg(ARM::CPSR);
1876
1877
1878 // Calling __morestack(StackSize, Size of stack arguments).
1879 // __morestack knows that the stack size requested is in SR0(r4)
1880 // and amount size of stack arguments is in SR1(r5).
1881
1882 // Pass first argument for the __morestack by Scratch Register #0.
1883 // The amount size of stack required
1884 if (Thumb) {
1885 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1886 ScratchReg0)).addImm(AlignedStackSize));
1887 } else {
1888 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1889 .addImm(AlignedStackSize)).addReg(0);
1890 }
1891 // Pass second argument for the __morestack by Scratch Register #1.
1892 // The amount size of stack consumed to save function arguments.
1893 if (Thumb) {
1894 AddDefaultPred(
1895 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1896 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1897 } else {
1898 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1899 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1900 .addReg(0);
1901 }
1902
1903 // push {lr} - Save return address of this function.
1904 if (Thumb) {
1905 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1906 .addReg(ARM::LR);
1907 } else {
1908 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1909 .addReg(ARM::SP, RegState::Define)
1910 .addReg(ARM::SP))
1911 .addReg(ARM::LR);
1912 }
1913
1914 // Emit the DWARF info about the change in stack as well as where to find the
1915 // previous link register
1916 CFIIndex =
1917 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1918 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1919 .addCFIIndex(CFIIndex);
1920 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1921 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1922 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1923 .addCFIIndex(CFIIndex);
1924
1925 // Call __morestack().
1926 if (Thumb) {
1927 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1928 .addExternalSymbol("__morestack");
1929 } else {
1930 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1931 .addExternalSymbol("__morestack");
1932 }
1933
1934 // pop {lr} - Restore return address of this original function.
1935 if (Thumb) {
1936 if (ST->isThumb1Only()) {
1937 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1938 .addReg(ScratchReg0);
1939 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1940 .addReg(ScratchReg0));
1941 } else {
1942 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1943 .addReg(ARM::LR, RegState::Define)
1944 .addReg(ARM::SP, RegState::Define)
1945 .addReg(ARM::SP)
1946 .addImm(4));
1947 }
1948 } else {
1949 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1950 .addReg(ARM::SP, RegState::Define)
1951 .addReg(ARM::SP))
1952 .addReg(ARM::LR);
1953 }
1954
1955 // Restore SR0 and SR1 in case of __morestack() was called.
1956 // __morestack() will skip PostStackMBB block so we need to restore
1957 // scratch registers from here.
1958 // pop {SR0, SR1}
1959 if (Thumb) {
1960 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1961 .addReg(ScratchReg0)
1962 .addReg(ScratchReg1);
1963 } else {
1964 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1965 .addReg(ARM::SP, RegState::Define)
1966 .addReg(ARM::SP))
1967 .addReg(ScratchReg0)
1968 .addReg(ScratchReg1);
1969 }
1970
1971 // Update the CFA offset now that we've popped
1972 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1973 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1974 .addCFIIndex(CFIIndex);
1975
1976 // bx lr - Return from this function.
1977 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1978 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
1979
1980 // Restore SR0 and SR1 in case of __morestack() was not called.
1981 // pop {SR0, SR1}
1982 if (Thumb) {
1983 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
1984 .addReg(ScratchReg0)
1985 .addReg(ScratchReg1);
1986 } else {
1987 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
1988 .addReg(ARM::SP, RegState::Define)
1989 .addReg(ARM::SP))
1990 .addReg(ScratchReg0)
1991 .addReg(ScratchReg1);
1992 }
1993
1994 // Update the CFA offset now that we've popped
1995 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1996 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1997 .addCFIIndex(CFIIndex);
1998
1999 // Tell debuggers that r4 and r5 are now the same as they were in the
2000 // previous function, that they're the "Same Value".
2001 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2002 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2003 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2004 .addCFIIndex(CFIIndex);
2005 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2006 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2007 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2008 .addCFIIndex(CFIIndex);
2009
2010 // Organizing MBB lists
2011 PostStackMBB->addSuccessor(&prologueMBB);
2012
2013 AllocMBB->addSuccessor(PostStackMBB);
2014
2015 GetMBB->addSuccessor(PostStackMBB);
2016 GetMBB->addSuccessor(AllocMBB);
2017
2018 McrMBB->addSuccessor(GetMBB);
2019
2020 PrevStackMBB->addSuccessor(McrMBB);
2021
2022#ifdef XDEBUG
2023 MF.verify();
2024#endif
2025}