blob: d7cf9c9b6eb5d3156e022940a32ba99e694b99d3 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov2f931282011-01-10 12:39:04 +000010// This file contains the ARM implementation of TargetFrameLowering class.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov2f931282011-01-10 12:39:04 +000014#include "ARMFrameLowering.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000015#include "ARMBaseInstrInfo.h"
Evan Chenge45d6852011-01-11 21:46:47 +000016#include "ARMBaseRegisterInfo.h"
Oliver Stannardb14c6252014-04-02 16:10:33 +000017#include "ARMConstantPoolValue.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000020#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengeb56dca2010-11-22 18:12:04 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +000025#include "llvm/CodeGen/RegisterScavenging.h"
Tim Northovere0ccdc62015-10-28 22:46:43 +000026#include "llvm/MC/MCAsmInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/CallingConv.h"
28#include "llvm/IR/Function.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000029#include "llvm/MC/MCContext.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000030#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetOptions.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000032
Reid Klecknerbdfc05f2016-10-11 21:14:03 +000033#define DEBUG_TYPE "arm-frame-lowering"
34
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000035using namespace llvm;
36
Benjamin Kramer9fceb902012-02-24 22:09:25 +000037static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000038SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000039 cl::desc("Align ARM NEON spills in prolog and epilog"));
40
41static MachineBasicBlock::iterator
42skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
43 unsigned NumAlignedDPRCS2Regs);
44
Eric Christopher45fb7b62014-06-26 19:29:59 +000045ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
46 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
47 STI(sti) {}
48
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000049bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
50 // iOS always has a FP for backtracking, force other targets to keep their FP
51 // when doing FastISel. The emitted code is currently superior, and in cases
52 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
53 return TargetFrameLowering::noFramePointerElim(MF) ||
54 MF.getSubtarget<ARMSubtarget>().useFastISel();
55}
56
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000057/// hasFP - Return true if the specified function should have a dedicated frame
58/// pointer register. This is true if the function has variable sized allocas
59/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000060bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000061 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +000062 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000063
Oliver Stannard9aa6f012016-08-23 09:19:22 +000064 // ABI-required frame pointer.
65 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000066 return true;
67
Oliver Stannard9aa6f012016-08-23 09:19:22 +000068 // Frame pointer required for use within this function.
69 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +000070 MFI.hasVarSizedObjects() ||
71 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000072}
73
Bob Wilson657f2272011-01-13 21:10:12 +000074/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
75/// not required, we reserve argument space for call sites in the function
76/// immediately on entry to the current function. This eliminates the need for
77/// add/sub sp brackets around call sites. Returns true if the call frame is
78/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000079bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +000080 const MachineFrameInfo &MFI = MF.getFrameInfo();
81 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000082 // It's not always a good idea to include the call frame as part of the
83 // stack frame. ARM (especially Thumb) has small immediate offset to
84 // address the stack frame. So a large call frame can cause poor codegen
85 // and may even makes it impossible to scavenge a register.
86 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
87 return false;
88
Matthias Braun941a7052016-07-28 18:40:00 +000089 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000090}
91
Bob Wilson657f2272011-01-13 21:10:12 +000092/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
93/// call frame pseudos can be simplified. Unlike most targets, having a FP
94/// is not sufficient here since we still may reference some objects via SP
95/// even when FP is available in Thumb2 mode.
96bool
97ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +000098 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000099}
100
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000101static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000102 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000103 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000104 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000105 // The first two operands are predicates. The last two are
106 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000107 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
108 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000109 return false;
110 return true;
111 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000112 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
113 MI.getOpcode() == ARM::LDR_POST_REG ||
114 MI.getOpcode() == ARM::t2LDR_POST) &&
115 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
116 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000117 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000118
119 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000120}
121
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000122static void emitRegPlusImmediate(
123 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
124 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
125 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
126 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000127 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000128 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000129 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000130 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000131 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000132 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000133}
134
Tim Northoverc9432eb2013-11-04 23:04:15 +0000135static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000136 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000137 const ARMBaseInstrInfo &TII, int NumBytes,
138 unsigned MIFlags = MachineInstr::NoFlags,
139 ARMCC::CondCodes Pred = ARMCC::AL,
140 unsigned PredReg = 0) {
141 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
142 MIFlags, Pred, PredReg);
143}
144
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000145static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000146 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000147 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000148 case ARM::VSTMDDB_UPD:
149 RegSize = 8;
150 break;
151 case ARM::STMDB_UPD:
152 case ARM::t2STMDB_UPD:
153 RegSize = 4;
154 break;
155 case ARM::t2STR_PRE:
156 case ARM::STR_PRE_IMM:
157 return 4;
158 default:
159 llvm_unreachable("Unknown push or pop like instruction");
160 }
161
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000162 int count = 0;
163 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
164 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000165 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000166 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000167 return count;
168}
169
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000170static bool WindowsRequiresStackProbe(const MachineFunction &MF,
171 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000172 const MachineFrameInfo &MFI = MF.getFrameInfo();
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000173 const Function *F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000174 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000175 if (F->hasFnAttribute("stack-probe-size"))
176 F->getFnAttribute("stack-probe-size")
177 .getValueAsString()
178 .getAsInteger(0, StackProbeSize);
179 return StackSizeInBytes >= StackProbeSize;
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000180}
181
Tim Northover603d3162014-11-14 22:45:33 +0000182namespace {
183struct StackAdjustingInsts {
184 struct InstInfo {
185 MachineBasicBlock::iterator I;
186 unsigned SPAdjust;
187 bool BeforeFPSet;
188 };
189
190 SmallVector<InstInfo, 4> Insts;
191
192 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
193 bool BeforeFPSet = false) {
194 InstInfo Info = {I, SPAdjust, BeforeFPSet};
195 Insts.push_back(Info);
196 }
197
198 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
David Majnemer562e8292016-08-12 00:18:03 +0000199 auto Info = find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000200 assert(Info != Insts.end() && "invalid sp adjusting instruction");
201 Info->SPAdjust += ExtraBytes;
202 }
203
Matthias Braunf23ef432016-11-30 23:48:42 +0000204 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
205 const ARMBaseInstrInfo &TII, bool HasFP) {
206 MachineFunction &MF = *MBB.getParent();
Tim Northover603d3162014-11-14 22:45:33 +0000207 unsigned CFAOffset = 0;
208 for (auto &Info : Insts) {
209 if (HasFP && !Info.BeforeFPSet)
210 return;
211
212 CFAOffset -= Info.SPAdjust;
Matthias Braunf23ef432016-11-30 23:48:42 +0000213 unsigned CFIIndex = MF.addFrameInst(
Tim Northover603d3162014-11-14 22:45:33 +0000214 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
215 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000216 TII.get(TargetOpcode::CFI_INSTRUCTION))
217 .addCFIIndex(CFIIndex)
218 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000219 }
220 }
221};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Tim Northover603d3162014-11-14 22:45:33 +0000223
Kristof Beyls933de7a2015-01-08 15:09:14 +0000224/// Emit an instruction sequence that will align the address in
225/// register Reg by zero-ing out the lower bits. For versions of the
226/// architecture that support Neon, this must be done in a single
227/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
228/// single instruction. That function only gets called when optimizing
229/// spilling of D registers on a core with the Neon instruction set
230/// present.
231static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
232 const TargetInstrInfo &TII,
233 MachineBasicBlock &MBB,
234 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000235 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000236 const unsigned Alignment,
237 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000238 const ARMSubtarget &AST =
239 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000240 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
241 const unsigned AlignMask = Alignment - 1;
242 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
243 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
244 if (!AFI->isThumbFunction()) {
245 // if the BFC instruction is available, use that to zero the lower
246 // bits:
247 // bfc Reg, #0, log2(Alignment)
248 // otherwise use BIC, if the mask to zero the required number of bits
249 // can be encoded in the bic immediate field
250 // bic Reg, Reg, Alignment-1
251 // otherwise, emit
252 // lsr Reg, Reg, log2(Alignment)
253 // lsl Reg, Reg, log2(Alignment)
254 if (CanUseBFC) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000255 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
256 .addReg(Reg, RegState::Kill)
257 .addImm(~AlignMask)
258 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000259 } else if (AlignMask <= 255) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000260 AddDefaultCC(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
261 .addReg(Reg, RegState::Kill)
262 .addImm(AlignMask)
263 .add(predOps(ARMCC::AL)));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000264 } else {
265 assert(!MustBeSingleInstruction &&
266 "Shouldn't call emitAligningInstructions demanding a single "
267 "instruction to be emitted for large stack alignment for a target "
268 "without BFC.");
Diana Picus4f8c3e12017-01-13 09:37:56 +0000269 AddDefaultCC(BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
270 .addReg(Reg, RegState::Kill)
271 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
272 .add(predOps(ARMCC::AL)));
273 AddDefaultCC(BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
274 .addReg(Reg, RegState::Kill)
275 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
276 .add(predOps(ARMCC::AL)));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000277 }
278 } else {
279 // Since this is only reached for Thumb-2 targets, the BFC instruction
280 // should always be available.
281 assert(CanUseBFC);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000282 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
283 .addReg(Reg, RegState::Kill)
284 .addImm(~AlignMask)
285 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000286 }
287}
288
Quentin Colombet61b305e2015-05-05 17:38:16 +0000289void ARMFrameLowering::emitPrologue(MachineFunction &MF,
290 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000291 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000292 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000294 MachineModuleInfo &MMI = MF.getMMI();
295 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000296 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000297 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000298 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
299 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000300 assert(!AFI->isThumb1OnlyFunction() &&
301 "This emitPrologue does not support Thumb1!");
302 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000303 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000304 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000305 unsigned NumBytes = MFI.getStackSize();
306 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000307
308 // Debug location must be unknown since the first debug location is used
309 // to determine the end of the prologue.
310 DebugLoc dl;
311
312 unsigned FramePtr = RegInfo->getFrameRegister(MF);
313
314 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000315 // belongs to which callee-save spill areas.
316 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
317 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000318 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000319
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000320 // All calls are tail calls in GHC calling conv, and functions have no
321 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000322 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
323 return;
324
Tim Northover603d3162014-11-14 22:45:33 +0000325 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000326 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000327
Oliver Stannardd55e1152014-03-05 15:25:27 +0000328 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000329 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000330 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000331 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000332 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000333 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000334
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000335 if (!AFI->hasStackFrame() &&
336 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000337 if (NumBytes - ArgRegsSaveSize != 0) {
338 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000339 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000340 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
341 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000342 }
Matthias Braunf23ef432016-11-30 23:48:42 +0000343 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000344 return;
345 }
346
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000347 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000348 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
349 unsigned Reg = CSI[i].getReg();
350 int FI = CSI[i].getFrameIdx();
351 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000352 case ARM::R8:
353 case ARM::R9:
354 case ARM::R10:
355 case ARM::R11:
356 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000357 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000358 GPRCS2Size += 4;
359 break;
360 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000361 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000362 case ARM::R0:
363 case ARM::R1:
364 case ARM::R2:
365 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000366 case ARM::R4:
367 case ARM::R5:
368 case ARM::R6:
369 case ARM::R7:
370 case ARM::LR:
371 if (Reg == FramePtr)
372 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000373 GPRCS1Size += 4;
374 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000375 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000376 // This is a DPR. Exclude the aligned DPRCS2 spills.
377 if (Reg == ARM::D8)
378 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000379 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000380 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000381 }
382 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000383
Eric Christopherb006fc92010-11-18 19:40:05 +0000384 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000385 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
386 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000387 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000388 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
389 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000390
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000391 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000392 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
393 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
394 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
395 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
396 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000397 int FramePtrOffsetInPush = 0;
398 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000399 FramePtrOffsetInPush =
Matthias Braun941a7052016-07-28 18:40:00 +0000400 MFI.getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
401 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000402 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000403 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000404 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
405 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
406 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
407
Tim Northoverc9432eb2013-11-04 23:04:15 +0000408 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000409 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000410 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000411 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
412 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000413
Tim Northover228c9432014-11-05 00:27:13 +0000414 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
415 // .cfi_offset operations will reflect that.
416 if (DPRGapSize) {
417 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000418 if (LastPush != MBB.end() &&
419 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000420 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
421 else {
Tim Northover228c9432014-11-05 00:27:13 +0000422 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
423 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000424 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
425 }
Tim Northover228c9432014-11-05 00:27:13 +0000426 }
427
Eric Christopherb006fc92010-11-18 19:40:05 +0000428 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000429 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000430 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000431 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000432 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000433 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000434 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000435 }
Evan Cheng70d29632011-02-25 00:24:46 +0000436 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000437
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000438 // Move past the aligned DPRCS2 area.
439 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
440 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
441 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
442 // leaves the stack pointer pointing to the DPRCS2 area.
443 //
444 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000445 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000446 } else
447 NumBytes = DPRCSOffset;
448
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000449 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
450 uint32_t NumWords = NumBytes >> 2;
451
452 if (NumWords < 65536)
Diana Picus4f8c3e12017-01-13 09:37:56 +0000453 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
454 .addImm(NumWords)
455 .setMIFlags(MachineInstr::FrameSetup)
456 .add(predOps(ARMCC::AL));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000457 else
458 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000459 .addImm(NumWords)
460 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000461
462 switch (TM.getCodeModel()) {
463 case CodeModel::Small:
464 case CodeModel::Medium:
465 case CodeModel::Default:
466 case CodeModel::Kernel:
467 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
468 .addImm((unsigned)ARMCC::AL).addReg(0)
469 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000470 .addReg(ARM::R4, RegState::Implicit)
471 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000472 break;
473 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000474 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000475 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000476 .addExternalSymbol("__chkstk")
477 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000478
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000479 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
480 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000481 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000482 .addReg(ARM::R4, RegState::Implicit)
483 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000484 break;
485 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000486
Diana Picus4f8c3e12017-01-13 09:37:56 +0000487 AddDefaultCC(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
488 .addReg(ARM::SP, RegState::Kill)
489 .addReg(ARM::R4, RegState::Kill)
490 .setMIFlags(MachineInstr::FrameSetup)
491 .add(predOps(ARMCC::AL)));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000492 NumBytes = 0;
493 }
494
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000495 if (NumBytes) {
496 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000497 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000498 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000499 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
500 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000501 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
502 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000503 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
504 }
Tim Northover93bcc662013-11-08 17:18:07 +0000505
Evan Chengeb56dca2010-11-22 18:12:04 +0000506 if (HasFP && isARM)
507 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
508 // Note it's not safe to do this in Thumb2 mode because it would have
509 // taken two instructions:
510 // mov sp, r7
511 // sub sp, #24
512 // If an interrupt is taken between the two instructions, then sp is in
513 // an inconsistent state (pointing to the middle of callee-saved area).
514 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000515 AFI->setShouldRestoreSPFromFP(true);
516 }
517
Tim Northover603d3162014-11-14 22:45:33 +0000518 // Set FP to point to the stack slot that contains the previous FP.
519 // For iOS, FP is R7, which has now been stored in spill area 1.
520 // Otherwise, if this is not iOS, all the callee-saved registers go
521 // into spill area 1, including the FP in R11. In either case, it
522 // is in area one and the adjustment needs to take place just after
523 // that push.
524 if (HasFP) {
525 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000526 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000527 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
528 dl, TII, FramePtr, ARM::SP,
529 PushSize + FramePtrOffsetInPush,
530 MachineInstr::FrameSetup);
531 if (FramePtrOffsetInPush + PushSize != 0) {
Matthias Braunf23ef432016-11-30 23:48:42 +0000532 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
Tim Northover603d3162014-11-14 22:45:33 +0000533 nullptr, MRI->getDwarfRegNum(FramePtr, true),
534 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
535 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000536 .addCFIIndex(CFIIndex)
537 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000538 } else {
539 unsigned CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +0000540 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
Tim Northover603d3162014-11-14 22:45:33 +0000541 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
542 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000543 .addCFIIndex(CFIIndex)
544 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000545 }
546 }
547
548 // Now that the prologue's actual instructions are finalised, we can insert
549 // the necessary DWARF cf instructions to describe the situation. Start by
550 // recording where each register ended up:
551 if (GPRCS1Size > 0) {
552 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
553 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000554 for (const auto &Entry : CSI) {
555 unsigned Reg = Entry.getReg();
556 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000557 switch (Reg) {
558 case ARM::R8:
559 case ARM::R9:
560 case ARM::R10:
561 case ARM::R11:
562 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000563 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000564 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000565 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000566 case ARM::R0:
567 case ARM::R1:
568 case ARM::R2:
569 case ARM::R3:
570 case ARM::R4:
571 case ARM::R5:
572 case ARM::R6:
573 case ARM::R7:
574 case ARM::LR:
Matthias Braunf23ef432016-11-30 23:48:42 +0000575 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000576 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000577 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000578 .addCFIIndex(CFIIndex)
579 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000580 break;
581 }
582 }
583 }
584
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000585 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000586 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000587 for (const auto &Entry : CSI) {
588 unsigned Reg = Entry.getReg();
589 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000590 switch (Reg) {
591 case ARM::R8:
592 case ARM::R9:
593 case ARM::R10:
594 case ARM::R11:
595 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000596 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000597 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000598 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000599 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000600 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
601 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000602 .addCFIIndex(CFIIndex)
603 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000604 }
605 break;
606 }
607 }
608 }
609
610 if (DPRCSSize > 0) {
611 // Since vpush register list cannot have gaps, there may be multiple vpush
612 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000613 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000614 for (const auto &Entry : CSI) {
615 unsigned Reg = Entry.getReg();
616 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000617 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
618 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
619 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000620 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000621 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000622 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000623 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000624 .addCFIIndex(CFIIndex)
625 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000626 }
627 }
628 }
629
Tim Northover603d3162014-11-14 22:45:33 +0000630 // Now we can emit descriptions of where the canonical frame address was
631 // throughout the process. If we have a frame pointer, it takes over the job
632 // half-way through, so only the first few .cfi_def_cfa_offset instructions
633 // actually get emitted.
Matthias Braunf23ef432016-11-30 23:48:42 +0000634 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000635
Evan Chengeb56dca2010-11-22 18:12:04 +0000636 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000637 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
638 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000639
640 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
641 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000642 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000643 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
644
645 // If we need dynamic stack realignment, do it here. Be paranoid and make
646 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000647 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000648 // realigned.
649 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000650 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000651 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000652 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000653 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
654 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000655 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000656 // We cannot use sp as source/dest register here, thus we're using r4 to
657 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000658 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000659 // -- use emitAligningInstructions to produce best sequence to zero
660 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000661 // mov sp, r4
662 // FIXME: It will be better just to find spare register here.
Diana Picus4f8c3e12017-01-13 09:37:56 +0000663 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
664 .addReg(ARM::SP, RegState::Kill)
665 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000666 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
667 false);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000668 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
669 .addReg(ARM::R4, RegState::Kill)
670 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000671 }
672
673 AFI->setShouldRestoreSPFromFP(true);
674 }
675
676 // If we need a base pointer, set it up here. It's whatever the value
677 // of the stack pointer is at this point. Any variable size objects
678 // will be allocated after this, so we can still use the base pointer
679 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000680 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000681 if (RegInfo->hasBasePointer(MF)) {
682 if (isARM)
683 BuildMI(MBB, MBBI, dl,
684 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
685 .addReg(ARM::SP)
686 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
687 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000688 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
689 .addReg(ARM::SP)
690 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000691 }
692
693 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000694 // the sp from fp. We can assume there's an FP here since hasFP already
695 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000696 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000697 AFI->setShouldRestoreSPFromFP(true);
698}
699
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000700void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000701 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000702 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000703 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000704 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000705 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000706 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000707 assert(!AFI->isThumb1OnlyFunction() &&
708 "This emitEpilogue does not support Thumb1!");
709 bool isARM = !AFI->isThumbFunction();
710
Tim Northover8cda34f2015-03-11 18:54:22 +0000711 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000712 int NumBytes = (int)MFI.getStackSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000713 unsigned FramePtr = RegInfo->getFrameRegister(MF);
714
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000715 // All calls are tail calls in GHC calling conv, and functions have no
716 // prologue/epilogue.
Quentin Colombet71a71482015-07-20 21:42:14 +0000717 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000718 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000719
720 // First put ourselves on the first (from top) terminator instructions.
721 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
722 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000723
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000724 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000725 if (NumBytes - ArgRegsSaveSize != 0)
726 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000727 } else {
728 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000729 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000730 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000731 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000732 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000733 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
734 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000735 ++MBBI;
736 }
737
738 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000739 NumBytes -= (ArgRegsSaveSize +
740 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000741 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000742 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000743 AFI->getDPRCalleeSavedAreaSize());
744
745 // Reset SP based on frame pointer only if the stack frame extends beyond
746 // frame pointer stack slot or target is ELF and the function has FP.
747 if (AFI->shouldRestoreSPFromFP()) {
748 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
749 if (NumBytes) {
750 if (isARM)
751 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
752 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000753 else {
754 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000755 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000756 // mov sp, r7
757 // sub sp, #24
758 // This is bad, if an interrupt is taken after the mov, sp is in an
759 // inconsistent state.
760 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000761 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000762 "No scratch register to restore SP from FP!");
763 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000764 ARMCC::AL, 0, TII);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000765 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
766 .addReg(ARM::R4)
767 .add(predOps(ARMCC::AL));
Evan Chengeb56dca2010-11-22 18:12:04 +0000768 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000769 } else {
770 // Thumb2 or ARM.
771 if (isARM)
772 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
773 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
774 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000775 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
776 .addReg(FramePtr)
777 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000778 }
Tim Northoverdee86042013-12-02 14:46:26 +0000779 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000780 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
781 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000782
Eric Christopherb006fc92010-11-18 19:40:05 +0000783 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000784 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000785 MBBI++;
786 // Since vpop register list cannot have gaps, there may be multiple vpop
787 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000788 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000789 MBBI++;
790 }
Tim Northover228c9432014-11-05 00:27:13 +0000791 if (AFI->getDPRCalleeSavedGapSize()) {
792 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
793 "unexpected DPR alignment gap");
794 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
795 }
796
Eric Christopherb006fc92010-11-18 19:40:05 +0000797 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
798 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000799 }
800
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000801 if (ArgRegsSaveSize)
802 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000803}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000804
Bob Wilson657f2272011-01-13 21:10:12 +0000805/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
806/// debug info. It's the same as what we use for resolving the code-gen
807/// references for now. FIXME: This can go wrong when references are
808/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000809int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000810ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000811 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000812 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
813}
814
815int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000816ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000817 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000818 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000819 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000820 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000821 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000822 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000823 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000824 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000825 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000826
827 FrameReg = ARM::SP;
828 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000829
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000830 // SP can move around if there are allocas. We may also lose track of SP
831 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000832 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000833
Anton Korobeynikov46877782010-11-20 15:59:32 +0000834 // When dynamically realigning the stack, use the frame pointer for
835 // parameters, and the stack/base pointer for locals.
836 if (RegInfo->needsStackRealignment(MF)) {
837 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
838 if (isFixed) {
839 FrameReg = RegInfo->getFrameRegister(MF);
840 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000841 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000842 assert(RegInfo->hasBasePointer(MF) &&
843 "VLAs and dynamic stack alignment, but missing base pointer!");
844 FrameReg = RegInfo->getBaseRegister();
845 }
846 return Offset;
847 }
848
849 // If there is a frame pointer, use it when we can.
850 if (hasFP(MF) && AFI->hasStackFrame()) {
851 // Use frame pointer to reference fixed objects. Use it for locals if
852 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000853 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000854 FrameReg = RegInfo->getFrameRegister(MF);
855 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000856 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000857 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000858 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000859 // Try to use the frame pointer if we can, else use the base pointer
860 // since it's available. This is handy for the emergency spill slot, in
861 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000862 if (FPOffset >= -255 && FPOffset < 0) {
863 FrameReg = RegInfo->getFrameRegister(MF);
864 return FPOffset;
865 }
Evan Chengc0d20042011-04-22 01:42:52 +0000866 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000867 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000868 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000869 // ldr <rd>, [sp, #<imm8>]
870 // if at all possible to save space.
871 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
872 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000873 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000874 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000875 if (FPOffset >= -255 && FPOffset < 0) {
876 FrameReg = RegInfo->getFrameRegister(MF);
877 return FPOffset;
878 }
879 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
880 // Otherwise, use SP or FP, whichever is closer to the stack slot.
881 FrameReg = RegInfo->getFrameRegister(MF);
882 return FPOffset;
883 }
884 }
885 // Use the base pointer if we have one.
886 if (RegInfo->hasBasePointer(MF))
887 FrameReg = RegInfo->getBaseRegister();
888 return Offset;
889}
890
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000891void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000892 MachineBasicBlock::iterator MI,
893 const std::vector<CalleeSavedInfo> &CSI,
894 unsigned StmOpc, unsigned StrOpc,
895 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000896 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000897 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000898 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000899 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000900 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000901 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000902
903 DebugLoc DL;
904
Tim Northover46a6f0f2016-11-14 20:28:24 +0000905 typedef std::pair<unsigned, bool> RegAndKill;
906 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000907 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000908 while (i != 0) {
909 unsigned LastReg = 0;
910 for (; i != 0; --i) {
911 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000912 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000913
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000914 // D-registers in the aligned area DPRCS2 are NOT spilled here.
915 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
916 continue;
917
Matthias Braun707e02c2016-04-13 21:43:25 +0000918 bool isLiveIn = MF.getRegInfo().isLiveIn(Reg);
919 if (!isLiveIn)
Evan Cheng775ead32010-12-07 23:08:38 +0000920 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000921 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000922 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000923 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000924 if (NoGap && LastReg && LastReg != Reg-1)
925 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000926 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +0000927 // Do not set a kill flag on values that are also marked as live-in. This
928 // happens with the @llvm-returnaddress intrinsic and with arguments
929 // passed in callee saved registers.
930 // Omitting the kill flags is conservatively correct even if the live-in
931 // is not used after all.
932 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000933 }
934
Jim Grosbach5fccad82010-12-09 18:31:13 +0000935 if (Regs.empty())
936 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +0000937
Tim Northover3d38c382016-11-14 20:31:53 +0000938 std::sort(Regs.begin(), Regs.end(), [&](const RegAndKill &LHS,
939 const RegAndKill &RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +0000940 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
941 });
942
Jim Grosbach5fccad82010-12-09 18:31:13 +0000943 if (Regs.size() > 1 || StrOpc== 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000944 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
945 .addReg(ARM::SP)
946 .setMIFlags(MIFlags)
947 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +0000948 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
949 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000950 } else if (Regs.size() == 1) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000951 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
952 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
953 .addReg(ARM::SP)
954 .setMIFlags(MIFlags)
955 .addImm(-4)
956 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +0000957 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000958 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000959
960 // Put any subsequent vpush instructions before this one: they will refer to
961 // higher register numbers so need to be pushed first in order to preserve
962 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +0000963 if (MI != MBB.begin())
964 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000965 }
Evan Cheng775ead32010-12-07 23:08:38 +0000966}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000967
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000968void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000969 MachineBasicBlock::iterator MI,
970 const std::vector<CalleeSavedInfo> &CSI,
971 unsigned LdmOpc, unsigned LdrOpc,
972 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000973 bool(*Func)(unsigned, bool),
974 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000975 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000976 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000977 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +0000978 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +0000979 DebugLoc DL;
980 bool isTailCall = false;
981 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +0000982 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +0000983 if (MBB.end() != MI) {
984 DL = MI->getDebugLoc();
985 unsigned RetOpcode = MI->getOpcode();
986 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
987 isInterrupt =
988 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +0000989 isTrap =
990 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
991 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +0000992 }
Evan Cheng775ead32010-12-07 23:08:38 +0000993
994 SmallVector<unsigned, 4> Regs;
995 unsigned i = CSI.size();
996 while (i != 0) {
997 unsigned LastReg = 0;
998 bool DeleteRet = false;
999 for (; i != 0; --i) {
1000 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001001 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001002
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001003 // The aligned reloads from area DPRCS2 are not inserted here.
1004 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1005 continue;
1006
Tim Northoverd8407452013-10-01 14:33:28 +00001007 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001008 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001009 if (MBB.succ_empty()) {
1010 Reg = ARM::PC;
1011 DeleteRet = true;
1012 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1013 } else
1014 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001015 // Fold the return instruction into the LDM.
Evan Cheng775ead32010-12-07 23:08:38 +00001016 }
1017
Evan Cheng9d54ae62010-12-08 06:29:02 +00001018 // If NoGap is true, pop consecutive registers and then leave the rest
1019 // for other instructions. e.g.
1020 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1021 if (NoGap && LastReg && LastReg != Reg-1)
1022 break;
1023
Evan Cheng775ead32010-12-07 23:08:38 +00001024 LastReg = Reg;
1025 Regs.push_back(Reg);
1026 }
1027
Jim Grosbach5fccad82010-12-09 18:31:13 +00001028 if (Regs.empty())
1029 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001030
1031 std::sort(Regs.begin(), Regs.end(), [&](unsigned LHS, unsigned RHS) {
1032 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1033 });
1034
Jim Grosbach5fccad82010-12-09 18:31:13 +00001035 if (Regs.size() > 1 || LdrOpc == 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001036 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1037 .addReg(ARM::SP)
1038 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001039 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1040 MIB.addReg(Regs[i], getDefRegState(true));
Quentin Colombet71a71482015-07-20 21:42:14 +00001041 if (DeleteRet && MI != MBB.end()) {
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001042 MIB.copyImplicitOps(*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001043 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001044 }
Evan Cheng775ead32010-12-07 23:08:38 +00001045 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001046 } else if (Regs.size() == 1) {
1047 // If we adjusted the reg to PC from LR above, switch it back here. We
1048 // only do that for LDM.
1049 if (Regs[0] == ARM::PC)
1050 Regs[0] = ARM::LR;
1051 MachineInstrBuilder MIB =
1052 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1053 .addReg(ARM::SP, RegState::Define)
1054 .addReg(ARM::SP);
1055 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1056 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001057 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001058 MIB.addReg(0);
1059 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1060 } else
1061 MIB.addImm(4);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001062 MIB.add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001063 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001064 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001065
1066 // Put any subsequent vpop instructions after this one: they will refer to
1067 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001068 if (MI != MBB.end())
1069 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001070 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001071}
1072
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001073/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001074/// starting from d8. Also insert stack realignment code and leave the stack
1075/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001076static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1077 MachineBasicBlock::iterator MI,
1078 unsigned NumAlignedDPRCS2Regs,
1079 const std::vector<CalleeSavedInfo> &CSI,
1080 const TargetRegisterInfo *TRI) {
1081 MachineFunction &MF = *MBB.getParent();
1082 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001083 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001084 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001085 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001086
1087 // Mark the D-register spill slots as properly aligned. Since MFI computes
1088 // stack slot layout backwards, this can actually mean that the d-reg stack
1089 // slot offsets can be wrong. The offset for d8 will always be correct.
1090 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1091 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001092 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001093 continue;
1094 int FI = CSI[i].getFrameIdx();
1095 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1096 // registers will be 8-byte aligned.
1097 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1098
1099 // The stack slot for D8 needs to be maximally aligned because this is
1100 // actually the point where we align the stack pointer. MachineFrameInfo
1101 // computes all offsets relative to the incoming stack pointer which is a
1102 // bit weird when realigning the stack. Any extra padding for this
1103 // over-alignment is not realized because the code inserted below adjusts
1104 // the stack pointer by numregs * 8 before aligning the stack pointer.
1105 if (DNum == 0)
1106 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1107 }
1108
1109 // Move the stack pointer to the d8 spill slot, and align it at the same
1110 // time. Leave the stack slot address in the scratch register r4.
1111 //
1112 // sub r4, sp, #numregs * 8
1113 // bic r4, r4, #align - 1
1114 // mov sp, r4
1115 //
1116 bool isThumb = AFI->isThumbFunction();
1117 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1118 AFI->setShouldRestoreSPFromFP(true);
1119
1120 // sub r4, sp, #numregs * 8
1121 // The immediate is <= 64, so it doesn't need any special encoding.
1122 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
Diana Picus4f8c3e12017-01-13 09:37:56 +00001123 AddDefaultCC(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1124 .addReg(ARM::SP)
1125 .addImm(8 * NumAlignedDPRCS2Regs)
1126 .add(predOps(ARMCC::AL)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001127
Matthias Braun941a7052016-07-28 18:40:00 +00001128 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001129 // We must set parameter MustBeSingleInstruction to true, since
1130 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1131 // stack alignment. Luckily, this can always be done since all ARM
1132 // architecture versions that support Neon also support the BFC
1133 // instruction.
1134 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001135
1136 // mov sp, r4
1137 // The stack pointer must be adjusted before spilling anything, otherwise
1138 // the stack slots could be clobbered by an interrupt handler.
1139 // Leave r4 live, it is used below.
1140 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1141 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001142 .addReg(ARM::R4)
1143 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001144 if (!isThumb)
1145 AddDefaultCC(MIB);
1146
1147 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1148 // r4 holds the stack slot address.
1149 unsigned NextReg = ARM::D8;
1150
1151 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1152 // The writeback is only needed when emitting two vst1.64 instructions.
1153 if (NumAlignedDPRCS2Regs >= 6) {
1154 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001155 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001156 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001157 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1158 .addReg(ARM::R4, RegState::Kill)
1159 .addImm(16)
1160 .addReg(NextReg)
1161 .addReg(SupReg, RegState::ImplicitKill)
1162 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001163 NextReg += 4;
1164 NumAlignedDPRCS2Regs -= 4;
1165 }
1166
1167 // We won't modify r4 beyond this point. It currently points to the next
1168 // register to be spilled.
1169 unsigned R4BaseReg = NextReg;
1170
1171 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1172 if (NumAlignedDPRCS2Regs >= 4) {
1173 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001174 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001175 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001176 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1177 .addReg(ARM::R4)
1178 .addImm(16)
1179 .addReg(NextReg)
1180 .addReg(SupReg, RegState::ImplicitKill)
1181 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001182 NextReg += 4;
1183 NumAlignedDPRCS2Regs -= 4;
1184 }
1185
1186 // 16-byte aligned vst1.64 with 2 d-regs.
1187 if (NumAlignedDPRCS2Regs >= 2) {
1188 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001189 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001190 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001191 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1192 .addReg(ARM::R4)
1193 .addImm(16)
1194 .addReg(SupReg)
1195 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001196 NextReg += 2;
1197 NumAlignedDPRCS2Regs -= 2;
1198 }
1199
1200 // Finally, use a vanilla vstr.64 for the odd last register.
1201 if (NumAlignedDPRCS2Regs) {
1202 MBB.addLiveIn(NextReg);
1203 // vstr.64 uses addrmode5 which has an offset scale of 4.
Diana Picus4f8c3e12017-01-13 09:37:56 +00001204 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1205 .addReg(NextReg)
1206 .addReg(ARM::R4)
1207 .addImm((NextReg - R4BaseReg) * 2)
1208 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001209 }
1210
1211 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001212 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001213}
1214
1215/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1216/// iterator to the following instruction.
1217static MachineBasicBlock::iterator
1218skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1219 unsigned NumAlignedDPRCS2Regs) {
1220 // sub r4, sp, #numregs * 8
1221 // bic r4, r4, #align - 1
1222 // mov sp, r4
1223 ++MI; ++MI; ++MI;
1224 assert(MI->mayStore() && "Expecting spill instruction");
1225
1226 // These switches all fall through.
1227 switch(NumAlignedDPRCS2Regs) {
1228 case 7:
1229 ++MI;
1230 assert(MI->mayStore() && "Expecting spill instruction");
1231 default:
1232 ++MI;
1233 assert(MI->mayStore() && "Expecting spill instruction");
1234 case 1:
1235 case 2:
1236 case 4:
1237 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1238 ++MI;
1239 }
1240 return MI;
1241}
1242
1243/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1244/// starting from d8. These instructions are assumed to execute while the
1245/// stack is still aligned, unlike the code inserted by emitPopInst.
1246static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1247 MachineBasicBlock::iterator MI,
1248 unsigned NumAlignedDPRCS2Regs,
1249 const std::vector<CalleeSavedInfo> &CSI,
1250 const TargetRegisterInfo *TRI) {
1251 MachineFunction &MF = *MBB.getParent();
1252 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001253 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001254 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001255
1256 // Find the frame index assigned to d8.
1257 int D8SpillFI = 0;
1258 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1259 if (CSI[i].getReg() == ARM::D8) {
1260 D8SpillFI = CSI[i].getFrameIdx();
1261 break;
1262 }
1263
1264 // Materialize the address of the d8 spill slot into the scratch register r4.
1265 // This can be fairly complicated if the stack frame is large, so just use
1266 // the normal frame index elimination mechanism to do it. This code runs as
1267 // the initial part of the epilog where the stack and base pointers haven't
1268 // been changed yet.
1269 bool isThumb = AFI->isThumbFunction();
1270 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1271
1272 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
Diana Picus4f8c3e12017-01-13 09:37:56 +00001273 AddDefaultCC(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1274 .addFrameIndex(D8SpillFI)
1275 .addImm(0)
1276 .add(predOps(ARMCC::AL)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001277
1278 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1279 unsigned NextReg = ARM::D8;
1280
1281 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1282 if (NumAlignedDPRCS2Regs >= 6) {
1283 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001284 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001285 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1286 .addReg(ARM::R4, RegState::Define)
1287 .addReg(ARM::R4, RegState::Kill)
1288 .addImm(16)
1289 .addReg(SupReg, RegState::ImplicitDefine)
1290 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001291 NextReg += 4;
1292 NumAlignedDPRCS2Regs -= 4;
1293 }
1294
1295 // We won't modify r4 beyond this point. It currently points to the next
1296 // register to be spilled.
1297 unsigned R4BaseReg = NextReg;
1298
1299 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1300 if (NumAlignedDPRCS2Regs >= 4) {
1301 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001302 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001303 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1304 .addReg(ARM::R4)
1305 .addImm(16)
1306 .addReg(SupReg, RegState::ImplicitDefine)
1307 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001308 NextReg += 4;
1309 NumAlignedDPRCS2Regs -= 4;
1310 }
1311
1312 // 16-byte aligned vld1.64 with 2 d-regs.
1313 if (NumAlignedDPRCS2Regs >= 2) {
1314 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001315 &ARM::QPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001316 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1317 .addReg(ARM::R4)
1318 .addImm(16)
1319 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001320 NextReg += 2;
1321 NumAlignedDPRCS2Regs -= 2;
1322 }
1323
1324 // Finally, use a vanilla vldr.64 for the remaining odd register.
1325 if (NumAlignedDPRCS2Regs)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001326 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1327 .addReg(ARM::R4)
1328 .addImm(2 * (NextReg - R4BaseReg))
1329 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001330
1331 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001332 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001333}
1334
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001335bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001336 MachineBasicBlock::iterator MI,
1337 const std::vector<CalleeSavedInfo> &CSI,
1338 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001339 if (CSI.empty())
1340 return false;
1341
1342 MachineFunction &MF = *MBB.getParent();
1343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001344
1345 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001346 unsigned PushOneOpc = AFI->isThumbFunction() ?
1347 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001348 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001349 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1350 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001351 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001352 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001353 MachineInstr::FrameSetup);
1354 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001355 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1356
1357 // The code above does not insert spill code for the aligned DPRCS2 registers.
1358 // The stack realignment code will be inserted between the push instructions
1359 // and these spills.
1360 if (NumAlignedDPRCS2Regs)
1361 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001362
1363 return true;
1364}
1365
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001366bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001367 MachineBasicBlock::iterator MI,
1368 const std::vector<CalleeSavedInfo> &CSI,
1369 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001370 if (CSI.empty())
1371 return false;
1372
1373 MachineFunction &MF = *MBB.getParent();
1374 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001375 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001376 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1377
1378 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1379 // registers. Do that here instead.
1380 if (NumAlignedDPRCS2Regs)
1381 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001382
1383 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001384 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001385 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001386 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1387 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001388 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001389 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001390 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001391 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001392
1393 return true;
1394}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001395
1396// FIXME: Make generic?
1397static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1398 const ARMBaseInstrInfo &TII) {
1399 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001400 for (auto &MBB : MF) {
1401 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001402 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001403 }
1404 return FnSize;
1405}
1406
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001407/// estimateRSStackSizeLimit - Look at each instruction that references stack
1408/// frames and return the stack size limit beyond which some of these
1409/// instructions will require a scratch register during their expansion later.
1410// FIXME: Move to TII?
1411static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001412 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001413 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1414 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001415 for (auto &MBB : MF) {
1416 for (auto &MI : MBB) {
1417 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1418 if (!MI.getOperand(i).isFI())
1419 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001420
1421 // When using ADDri to get the address of a stack object, 255 is the
1422 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001423 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001424 Limit = std::min(Limit, (1U << 8) - 1);
1425 break;
1426 }
1427
1428 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001429 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001430 case ARMII::AddrMode3:
1431 case ARMII::AddrModeT2_i8:
1432 Limit = std::min(Limit, (1U << 8) - 1);
1433 break;
1434 case ARMII::AddrMode5:
1435 case ARMII::AddrModeT2_i8s4:
1436 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1437 break;
1438 case ARMII::AddrModeT2_i12:
1439 // i12 supports only positive offset so these will be converted to
1440 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1441 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1442 Limit = std::min(Limit, (1U << 8) - 1);
1443 break;
1444 case ARMII::AddrMode4:
1445 case ARMII::AddrMode6:
1446 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1447 // immediate offset for stack references.
1448 return 0;
1449 default:
1450 break;
1451 }
1452 break; // At most one FI per instruction
1453 }
1454 }
1455 }
1456
1457 return Limit;
1458}
1459
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001460// In functions that realign the stack, it can be an advantage to spill the
1461// callee-saved vector registers after realigning the stack. The vst1 and vld1
1462// instructions take alignment hints that can improve performance.
1463//
Matthias Braun02564862015-07-14 17:17:13 +00001464static void
1465checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001466 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1467 if (!SpillAlignedNEONRegs)
1468 return;
1469
1470 // Naked functions don't spill callee-saved registers.
Duncan P. N. Exon Smith2cff9e12015-02-14 02:24:44 +00001471 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001472 return;
1473
1474 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001475 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001476 return;
1477
1478 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001479 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001480 return;
1481
1482 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001483 if (!static_cast<const ARMBaseRegisterInfo *>(
1484 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001485 return;
1486
1487 // We always spill contiguous d-registers starting from d8. Count how many
1488 // needs spilling. The register allocator will almost always use the
1489 // callee-saved registers in order, but it can happen that there are holes in
1490 // the range. Registers above the hole will be spilled to the standard DPRCS
1491 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001492 unsigned NumSpills = 0;
1493 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001494 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001495 break;
1496
1497 // Don't do this for just one d-register. It's not worth it.
1498 if (NumSpills < 2)
1499 return;
1500
1501 // Spill the first NumSpills D-registers after realigning the stack.
1502 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1503
1504 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001505 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001506}
1507
Matthias Braun02564862015-07-14 17:17:13 +00001508void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1509 BitVector &SavedRegs,
1510 RegScavenger *RS) const {
1511 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001512 // This tells PEI to spill the FP as if it is any other callee-save register
1513 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1514 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1515 // to combine multiple loads / stores.
1516 bool CanEliminateFrame = true;
1517 bool CS1Spilled = false;
1518 bool LRSpilled = false;
1519 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001520 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001521 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1522 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001523 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001524 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001525 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001526 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001527 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001528 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001529 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001530 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1531 (void)TRI; // Silence unused warning in non-assert builds.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001532 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1533
1534 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1535 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001536 // since it's not always possible to restore sp from fp in a single
1537 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001538 // FIXME: It will be better just to find spare register here.
1539 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001540 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001541 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001542
Evan Cheng572756a2011-01-16 05:14:33 +00001543 if (AFI->isThumb1OnlyFunction()) {
1544 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001545 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001546 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001547
Jim Grosbachdca85312011-06-13 21:18:25 +00001548 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1549 // for sure what the stack size will be, but for this, an estimate is good
1550 // enough. If there anything changes it, it'll be a spill, which implies
1551 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001552 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001553 // FIXME: It will be better just to find spare register here.
Matthias Braun941a7052016-07-28 18:40:00 +00001554 unsigned StackSize = MFI.estimateStackSize(MF);
1555 if (MFI.hasVarSizedObjects() || StackSize > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001556 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001557 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001558
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001559 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001560 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001561
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001562 // Spill the BasePtr if it's used.
1563 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001564 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001565
1566 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001567 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001568 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001569 for (unsigned i = 0; CSRegs[i]; ++i) {
1570 unsigned Reg = CSRegs[i];
1571 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001572 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001573 Spilled = true;
1574 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001575 }
1576
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001577 if (!ARM::GPRRegClass.contains(Reg)) {
1578 if (Spilled) {
1579 if (ARM::SPRRegClass.contains(Reg))
1580 NumFPRSpills++;
1581 else if (ARM::DPRRegClass.contains(Reg))
1582 NumFPRSpills += 2;
1583 else if (ARM::QPRRegClass.contains(Reg))
1584 NumFPRSpills += 4;
1585 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001586 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001587 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001588
1589 if (Spilled) {
1590 NumGPRSpills++;
1591
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001592 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001593 if (Reg == ARM::LR)
1594 LRSpilled = true;
1595 CS1Spilled = true;
1596 continue;
1597 }
1598
1599 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1600 switch (Reg) {
1601 case ARM::LR:
1602 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001603 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001604 case ARM::R0: case ARM::R1:
1605 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001606 case ARM::R4: case ARM::R5:
1607 case ARM::R6: case ARM::R7:
1608 CS1Spilled = true;
1609 break;
1610 default:
1611 break;
1612 }
1613 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001614 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001615 UnspilledCS1GPRs.push_back(Reg);
1616 continue;
1617 }
1618
1619 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001620 case ARM::R0: case ARM::R1:
1621 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001622 case ARM::R4: case ARM::R5:
1623 case ARM::R6: case ARM::R7:
1624 case ARM::LR:
1625 UnspilledCS1GPRs.push_back(Reg);
1626 break;
1627 default:
1628 UnspilledCS2GPRs.push_back(Reg);
1629 break;
1630 }
1631 }
1632 }
1633
1634 bool ForceLRSpill = false;
1635 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1636 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1637 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1638 // use of BL to implement far jump. If it turns out that it's not needed
1639 // then the branch fix up path will undo it.
1640 if (FnSize >= (1 << 11)) {
1641 CanEliminateFrame = false;
1642 ForceLRSpill = true;
1643 }
1644 }
1645
1646 // If any of the stack slot references may be out of range of an immediate
1647 // offset, make sure a register (or a spill slot) is available for the
1648 // register scavenger. Note that if we're indexing off the frame pointer, the
1649 // effective stack size is 4 bytes larger since the FP points to the stack
1650 // slot of the previous FP. Also, if we have variable sized objects in the
1651 // function, stack slot references will often be negative, and some of
1652 // our instructions are positive-offset only, so conservatively consider
1653 // that case to want a spill slot (or register) as well. Similarly, if
1654 // the function adjusts the stack pointer during execution and the
1655 // adjustments aren't already part of our stack size estimate, our offset
1656 // calculations may be off, so be conservative.
1657 // FIXME: We could add logic to be more precise about negative offsets
1658 // and which instructions will need a scratch register for them. Is it
1659 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001660 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001661 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001662 if (hasFP(MF)) {
1663 if (AFI->hasStackFrame())
1664 EstimatedStackSize += 4;
1665 } else {
1666 // If FP is not used, SP will be used to access arguments, so count the
1667 // size of arguments into the estimation.
1668 EstimatedStackSize += MF.getInfo<ARMFunctionInfo>()->getArgumentStackSize();
1669 }
1670 EstimatedStackSize += 16; // For possible paddings.
1671
1672 bool BigStack = EstimatedStackSize >= estimateRSStackSizeLimit(MF, this) ||
Matthias Braun941a7052016-07-28 18:40:00 +00001673 MFI.hasVarSizedObjects() ||
1674 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001675 bool ExtraCSSpill = false;
1676 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1677 AFI->setHasStackFrame(true);
1678
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001679 if (hasFP(MF)) {
1680 SavedRegs.set(FramePtr);
1681 // If the frame pointer is required by the ABI, also spill LR so that we
1682 // emit a complete frame record.
1683 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1684 SavedRegs.set(ARM::LR);
1685 LRSpilled = true;
1686 NumGPRSpills++;
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001687 auto LRPos = find(UnspilledCS1GPRs, ARM::LR);
1688 if (LRPos != UnspilledCS1GPRs.end())
1689 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001690 }
1691 auto FPPos = find(UnspilledCS1GPRs, FramePtr);
1692 if (FPPos != UnspilledCS1GPRs.end())
1693 UnspilledCS1GPRs.erase(FPPos);
1694 NumGPRSpills++;
1695 if (FramePtr == ARM::R7)
1696 CS1Spilled = true;
1697 }
1698
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001699 if (AFI->isThumb1OnlyFunction()) {
1700 // For Thumb1-only targets, we need some low registers when we save and
1701 // restore the high registers (which aren't allocatable, but could be
1702 // used by inline assembly) because the push/pop instructions can not
1703 // access high registers. If necessary, we might need to push more low
1704 // registers to ensure that there is at least one free that can be used
1705 // for the saving & restoring, and preferably we should ensure that as
1706 // many as are needed are available so that fewer push/pop instructions
1707 // are required.
1708
1709 // Low registers which are not currently pushed, but could be (r4-r7).
1710 SmallVector<unsigned, 4> AvailableRegs;
1711
1712 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1713 // free.
1714 int EntryRegDeficit = 0;
1715 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1716 if (!MF.getRegInfo().isLiveIn(Reg)) {
1717 --EntryRegDeficit;
1718 DEBUG(dbgs() << PrintReg(Reg, TRI)
1719 << " is unused argument register, EntryRegDeficit = "
1720 << EntryRegDeficit << "\n");
1721 }
1722 }
1723
1724 // Unused return registers can be clobbered in the epilogue for free.
1725 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1726 DEBUG(dbgs() << AFI->getReturnRegsCount()
1727 << " return regs used, ExitRegDeficit = " << ExitRegDeficit
1728 << "\n");
1729
1730 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1731 DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1732
1733 // r4-r6 can be used in the prologue if they are pushed by the first push
1734 // instruction.
1735 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1736 if (SavedRegs.test(Reg)) {
1737 --RegDeficit;
1738 DEBUG(dbgs() << PrintReg(Reg, TRI)
1739 << " is saved low register, RegDeficit = " << RegDeficit
1740 << "\n");
1741 } else {
1742 AvailableRegs.push_back(Reg);
1743 DEBUG(dbgs()
1744 << PrintReg(Reg, TRI)
1745 << " is non-saved low register, adding to AvailableRegs\n");
1746 }
1747 }
1748
1749 // r7 can be used if it is not being used as the frame pointer.
1750 if (!hasFP(MF)) {
1751 if (SavedRegs.test(ARM::R7)) {
1752 --RegDeficit;
1753 DEBUG(dbgs() << "%R7 is saved low register, RegDeficit = "
1754 << RegDeficit << "\n");
1755 } else {
1756 AvailableRegs.push_back(ARM::R7);
1757 DEBUG(dbgs()
1758 << "%R7 is non-saved low register, adding to AvailableRegs\n");
1759 }
1760 }
1761
1762 // Each of r8-r11 needs to be copied to a low register, then pushed.
1763 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1764 if (SavedRegs.test(Reg)) {
1765 ++RegDeficit;
1766 DEBUG(dbgs() << PrintReg(Reg, TRI)
1767 << " is saved high register, RegDeficit = " << RegDeficit
1768 << "\n");
1769 }
1770 }
1771
1772 // LR can only be used by PUSH, not POP, and can't be used at all if the
1773 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1774 // are more limited at function entry than exit.
1775 if ((EntryRegDeficit > ExitRegDeficit) &&
1776 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1777 MF.getFrameInfo().isReturnAddressTaken())) {
1778 if (SavedRegs.test(ARM::LR)) {
1779 --RegDeficit;
1780 DEBUG(dbgs() << "%LR is saved register, RegDeficit = " << RegDeficit
1781 << "\n");
1782 } else {
1783 AvailableRegs.push_back(ARM::LR);
1784 DEBUG(dbgs() << "%LR is not saved, adding to AvailableRegs\n");
1785 }
1786 }
1787
1788 // If there are more high registers that need pushing than low registers
1789 // available, push some more low registers so that we can use fewer push
1790 // instructions. This might not reduce RegDeficit all the way to zero,
1791 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1792 // need saving.
1793 DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
1794 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1795 unsigned Reg = AvailableRegs.pop_back_val();
1796 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1797 << " to make up reg deficit\n");
1798 SavedRegs.set(Reg);
1799 NumGPRSpills++;
1800 CS1Spilled = true;
1801 ExtraCSSpill = true;
1802 UnspilledCS1GPRs.erase(find(UnspilledCS1GPRs, Reg));
1803 if (Reg == ARM::LR)
1804 LRSpilled = true;
1805 }
1806 DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit << "\n");
1807 }
1808
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001809 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1810 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1811 if (!LRSpilled && CS1Spilled) {
Matthias Braun02564862015-07-14 17:17:13 +00001812 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001813 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001814 SmallVectorImpl<unsigned>::iterator LRPos;
David Majnemer0d955d02016-08-11 22:21:41 +00001815 LRPos = find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00001816 if (LRPos != UnspilledCS1GPRs.end())
1817 UnspilledCS1GPRs.erase(LRPos);
1818
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001819 ForceLRSpill = false;
1820 ExtraCSSpill = true;
1821 }
1822
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001823 // If stack and double are 8-byte aligned and we are spilling an odd number
1824 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1825 // the integer and double callee save areas.
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001826 DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001827 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001828 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001829 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1830 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1831 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001832 // Don't spill high register if the function is thumb. In the case of
1833 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001834 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001835 (STI.isTargetWindows() && Reg == ARM::R11) ||
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001836 isARMLowRegister(Reg) || Reg == ARM::LR) {
Matthias Braun02564862015-07-14 17:17:13 +00001837 SavedRegs.set(Reg);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001838 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1839 << " to make up alignment\n");
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001840 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001841 ExtraCSSpill = true;
1842 break;
1843 }
1844 }
1845 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1846 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001847 SavedRegs.set(Reg);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001848 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1849 << " to make up alignment\n");
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001850 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001851 ExtraCSSpill = true;
1852 }
1853 }
1854
1855 // Estimate if we might need to scavenge a register at some point in order
1856 // to materialize a stack offset. If so, either spill one additional
1857 // callee-saved register or reserve a special spill slot to facilitate
1858 // register scavenging. Thumb1 needs a spill slot for stack pointer
1859 // adjustments also, even when the frame itself is small.
1860 if (BigStack && !ExtraCSSpill) {
1861 // If any non-reserved CS register isn't spilled, just spill one or two
1862 // extra. That should take care of it!
1863 unsigned NumExtras = TargetAlign / 4;
1864 SmallVector<unsigned, 2> Extras;
1865 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1866 unsigned Reg = UnspilledCS1GPRs.back();
1867 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001868 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001869 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1870 Reg == ARM::LR)) {
1871 Extras.push_back(Reg);
1872 NumExtras--;
1873 }
1874 }
1875 // For non-Thumb1 functions, also check for hi-reg CS registers
1876 if (!AFI->isThumb1OnlyFunction()) {
1877 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1878 unsigned Reg = UnspilledCS2GPRs.back();
1879 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001880 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001881 Extras.push_back(Reg);
1882 NumExtras--;
1883 }
1884 }
1885 }
1886 if (Extras.size() && NumExtras == 0) {
1887 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Matthias Braun02564862015-07-14 17:17:13 +00001888 SavedRegs.set(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001889 }
1890 } else if (!AFI->isThumb1OnlyFunction()) {
1891 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1892 // closest to SP or frame pointer.
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001893 assert(RS && "Register scavenging not provided");
Craig Topperc7242e02012-04-20 07:30:17 +00001894 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Matthias Braun941a7052016-07-28 18:40:00 +00001895 RS->addScavengingFrameIndex(MFI.CreateStackObject(RC->getSize(),
1896 RC->getAlignment(),
1897 false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001898 }
1899 }
1900 }
1901
1902 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00001903 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001904 AFI->setLRIsSpilledForFarJump(true);
1905 }
1906}
Eli Bendersky8da87162013-02-21 20:05:00 +00001907
Hans Wennborge1a2e902016-03-31 18:33:38 +00001908MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
1909 MachineFunction &MF, MachineBasicBlock &MBB,
1910 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001911 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001912 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001913 if (!hasReservedCallFrame(MF)) {
1914 // If we have alloca, convert as follows:
1915 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1916 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001917 MachineInstr &Old = *I;
1918 DebugLoc dl = Old.getDebugLoc();
1919 unsigned Amount = Old.getOperand(0).getImm();
Eli Bendersky8da87162013-02-21 20:05:00 +00001920 if (Amount != 0) {
1921 // We need to keep the stack aligned properly. To do this, we round the
1922 // amount of space needed for the outgoing arguments up to the next
1923 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00001924 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00001925
1926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1927 assert(!AFI->isThumb1OnlyFunction() &&
1928 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1929 bool isARM = !AFI->isThumbFunction();
1930
1931 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001932 unsigned Opc = Old.getOpcode();
1933 int PIdx = Old.findFirstPredOperandIdx();
1934 ARMCC::CondCodes Pred =
1935 (PIdx == -1) ? ARMCC::AL
1936 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Eli Bendersky8da87162013-02-21 20:05:00 +00001937 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1938 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001939 unsigned PredReg = Old.getOperand(2).getReg();
Eli Bendersky8da87162013-02-21 20:05:00 +00001940 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1941 Pred, PredReg);
1942 } else {
1943 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001944 unsigned PredReg = Old.getOperand(3).getReg();
Eli Bendersky8da87162013-02-21 20:05:00 +00001945 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1946 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1947 Pred, PredReg);
1948 }
1949 }
1950 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00001951 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001952}
1953
Oliver Stannardb14c6252014-04-02 16:10:33 +00001954/// Get the minimum constant for ARM that is greater than or equal to the
1955/// argument. In ARM, constants can have any value that can be produced by
1956/// rotating an 8-bit value to the right by an even number of bits within a
1957/// 32-bit word.
1958static uint32_t alignToARMConstant(uint32_t Value) {
1959 unsigned Shifted = 0;
1960
1961 if (Value == 0)
1962 return 0;
1963
1964 while (!(Value & 0xC0000000)) {
1965 Value = Value << 2;
1966 Shifted += 2;
1967 }
1968
1969 bool Carry = (Value & 0x00FFFFFF);
1970 Value = ((Value & 0xFF000000) >> 24) + Carry;
1971
1972 if (Value & 0x0000100)
1973 Value = Value & 0x000001FC;
1974
1975 if (Shifted > 24)
1976 Value = Value >> (Shifted - 24);
1977 else
1978 Value = Value << (24 - Shifted);
1979
1980 return Value;
1981}
1982
1983// The stack limit in the TCB is set to this many bytes above the actual
1984// stack limit.
1985static const uint64_t kSplitStackAvailable = 256;
1986
1987// Adjust the function prologue to enable split stacks. This currently only
1988// supports android and linux.
1989//
1990// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1991// must be well defined in order to allow for consistent implementations of the
1992// __morestack helper function. The ABI is also not a normal ABI in that it
1993// doesn't follow the normal calling conventions because this allows the
1994// prologue of each function to be optimized further.
1995//
1996// Currently, the ABI looks like (when calling __morestack)
1997//
1998// * r4 holds the minimum stack size requested for this function call
1999// * r5 holds the stack size of the arguments to the function
2000// * the beginning of the function is 3 instructions after the call to
2001// __morestack
2002//
2003// Implementations of __morestack should use r4 to allocate a new stack, r5 to
2004// place the arguments on to the new stack, and the 3-instruction knowledge to
2005// jump directly to the body of the function when working on the new stack.
2006//
2007// An old (and possibly no longer compatible) implementation of __morestack for
2008// ARM can be found at [1].
2009//
2010// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00002011void ARMFrameLowering::adjustForSegmentedStacks(
2012 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00002013 unsigned Opcode;
2014 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00002015 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002016 bool Thumb = ST->isThumb();
2017
2018 // Sadly, this currently doesn't support varargs, platforms other than
2019 // android/linux. Note that thumb1/thumb2 are support for android/linux.
2020 if (MF.getFunction()->isVarArg())
2021 report_fatal_error("Segmented stacks do not support vararg functions.");
2022 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00002023 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00002024
Matthias Braun941a7052016-07-28 18:40:00 +00002025 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002026 MachineModuleInfo &MMI = MF.getMMI();
2027 MCContext &Context = MMI.getContext();
2028 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2029 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002030 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002031 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2032 DebugLoc DL;
2033
Matthias Braun941a7052016-07-28 18:40:00 +00002034 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002035
2036 // Do not generate a prologue for functions with a stack of size zero
2037 if (StackSize == 0)
2038 return;
2039
Oliver Stannardb14c6252014-04-02 16:10:33 +00002040 // Use R4 and R5 as scratch registers.
2041 // We save R4 and R5 before use and restore them before leaving the function.
2042 unsigned ScratchReg0 = ARM::R4;
2043 unsigned ScratchReg1 = ARM::R5;
2044 uint64_t AlignedStackSize;
2045
2046 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2047 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2048 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2049 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2050 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2051
Quentin Colombet71a71482015-07-20 21:42:14 +00002052 // Grab everything that reaches PrologueMBB to update there liveness as well.
2053 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2054 SmallVector<MachineBasicBlock *, 2> WalkList;
2055 WalkList.push_back(&PrologueMBB);
2056
2057 do {
2058 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2059 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2060 if (BeforePrologueRegion.insert(PredBB).second)
2061 WalkList.push_back(PredBB);
2062 }
2063 } while (!WalkList.empty());
2064
2065 // The order in that list is important.
2066 // The blocks will all be inserted before PrologueMBB using that order.
2067 // Therefore the block that should appear first in the CFG should appear
2068 // first in the list.
2069 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2070 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002071
Craig Topper80720812015-12-01 06:13:01 +00002072 for (MachineBasicBlock *B : AddedBlocks)
2073 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002074
Matthias Braund9da1622015-09-09 18:08:03 +00002075 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002076 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002077 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002078 }
2079
Quentin Colombet71a71482015-07-20 21:42:14 +00002080 // Remove the newly added blocks from the list, since we know
2081 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002082 for (MachineBasicBlock *B : AddedBlocks) {
2083 BeforePrologueRegion.erase(B);
2084 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002085 }
2086
2087 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2088 // Make sure the LiveIns are still sorted and unique.
2089 MBB->sortUniqueLiveIns();
2090 // Replace the edges to PrologueMBB by edges to the sequences
2091 // we are about to add.
2092 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2093 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002094
2095 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002096 AlignedStackSize = alignToARMConstant(StackSize);
2097
2098 // When the frame size is less than 256 we just compare the stack
2099 // boundary directly to the value of the stack pointer, per gcc.
2100 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2101
2102 // We will use two of the callee save registers as scratch registers so we
2103 // need to save those registers onto the stack.
2104 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2105 // requested and arguments for __morestack().
2106 // SR0: Scratch Register #0
2107 // SR1: Scratch Register #1
2108 // push {SR0, SR1}
2109 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002110 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2111 .add(predOps(ARMCC::AL))
2112 .addReg(ScratchReg0)
2113 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002114 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002115 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2116 .addReg(ARM::SP, RegState::Define)
2117 .addReg(ARM::SP)
2118 .add(predOps(ARMCC::AL))
2119 .addReg(ScratchReg0)
2120 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002121 }
2122
2123 // Emit the relevant DWARF information about the change in stack pointer as
2124 // well as where to find both r4 and r5 (the callee-save registers)
2125 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002126 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002127 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2128 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002129 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002130 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2131 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2132 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002133 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002134 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2135 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2136 .addCFIIndex(CFIIndex);
2137
2138 // mov SR1, sp
2139 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002140 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2141 .addReg(ARM::SP)
2142 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002143 } else if (CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002144 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2145 .addReg(ARM::SP)
2146 .add(predOps(ARMCC::AL))
2147 .addReg(0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002148 }
2149
2150 // sub SR1, sp, #StackSize
2151 if (!CompareStackPointer && Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002152 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
2153 .addReg(ScratchReg1)
2154 .addImm(AlignedStackSize)
2155 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002156 } else if (!CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002157 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2158 .addReg(ARM::SP)
2159 .addImm(AlignedStackSize)
2160 .add(predOps(ARMCC::AL))
2161 .addReg(0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002162 }
2163
2164 if (Thumb && ST->isThumb1Only()) {
2165 unsigned PCLabelId = ARMFI->createPICLabelUId();
2166 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00002167 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002168 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002169 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002170
2171 // ldr SR0, [pc, offset(STACK_LIMIT)]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002172 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2173 .addConstantPoolIndex(CPI)
2174 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002175
2176 // ldr SR0, [SR0]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002177 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2178 .addReg(ScratchReg0)
2179 .addImm(0)
2180 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002181 } else {
2182 // Get TLS base address from the coprocessor
2183 // mrc p15, #0, SR0, c13, c0, #3
Diana Picus4f8c3e12017-01-13 09:37:56 +00002184 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2185 .addImm(15)
2186 .addImm(0)
2187 .addImm(13)
2188 .addImm(0)
2189 .addImm(3)
2190 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002191
2192 // Use the last tls slot on android and a private field of the TCP on linux.
2193 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2194 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2195
2196 // Get the stack limit from the right offset
2197 // ldr SR0, [sr0, #4 * TlsOffset]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002198 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2199 .addReg(ScratchReg0)
2200 .addImm(4 * TlsOffset)
2201 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002202 }
2203
2204 // Compare stack limit with stack size requested.
2205 // cmp SR0, SR1
2206 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002207 BuildMI(GetMBB, DL, TII.get(Opcode))
2208 .addReg(ScratchReg0)
2209 .addReg(ScratchReg1)
2210 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002211
2212 // This jump is taken if StackLimit < SP - stack required.
2213 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2214 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2215 .addImm(ARMCC::LO)
2216 .addReg(ARM::CPSR);
2217
2218
2219 // Calling __morestack(StackSize, Size of stack arguments).
2220 // __morestack knows that the stack size requested is in SR0(r4)
2221 // and amount size of stack arguments is in SR1(r5).
2222
2223 // Pass first argument for the __morestack by Scratch Register #0.
2224 // The amount size of stack required
2225 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002226 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0))
2227 .addImm(AlignedStackSize)
2228 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002229 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002230 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2231 .addImm(AlignedStackSize)
2232 .add(predOps(ARMCC::AL))
2233 .addReg(0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002234 }
2235 // Pass second argument for the __morestack by Scratch Register #1.
2236 // The amount size of stack consumed to save function arguments.
2237 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002238 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2239 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2240 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002241 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002242 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2243 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2244 .add(predOps(ARMCC::AL))
2245 .addReg(0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002246 }
2247
2248 // push {lr} - Save return address of this function.
2249 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002250 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2251 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002252 .addReg(ARM::LR);
2253 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002254 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2255 .addReg(ARM::SP, RegState::Define)
2256 .addReg(ARM::SP)
2257 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002258 .addReg(ARM::LR);
2259 }
2260
2261 // Emit the DWARF info about the change in stack as well as where to find the
2262 // previous link register
2263 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002264 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002265 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2266 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002267 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002268 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2269 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2270 .addCFIIndex(CFIIndex);
2271
2272 // Call __morestack().
2273 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002274 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2275 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002276 .addExternalSymbol("__morestack");
2277 } else {
2278 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2279 .addExternalSymbol("__morestack");
2280 }
2281
2282 // pop {lr} - Restore return address of this original function.
2283 if (Thumb) {
2284 if (ST->isThumb1Only()) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002285 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2286 .add(predOps(ARMCC::AL))
2287 .addReg(ScratchReg0);
2288 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2289 .addReg(ScratchReg0)
2290 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002291 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002292 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2293 .addReg(ARM::LR, RegState::Define)
2294 .addReg(ARM::SP, RegState::Define)
2295 .addReg(ARM::SP)
2296 .addImm(4)
2297 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002298 }
2299 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002300 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2301 .addReg(ARM::SP, RegState::Define)
2302 .addReg(ARM::SP)
2303 .add(predOps(ARMCC::AL))
2304 .addReg(ARM::LR);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002305 }
2306
2307 // Restore SR0 and SR1 in case of __morestack() was called.
2308 // __morestack() will skip PostStackMBB block so we need to restore
2309 // scratch registers from here.
2310 // pop {SR0, SR1}
2311 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002312 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2313 .add(predOps(ARMCC::AL))
2314 .addReg(ScratchReg0)
2315 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002316 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002317 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2318 .addReg(ARM::SP, RegState::Define)
2319 .addReg(ARM::SP)
2320 .add(predOps(ARMCC::AL))
2321 .addReg(ScratchReg0)
2322 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002323 }
2324
2325 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002326 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002327 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2328 .addCFIIndex(CFIIndex);
2329
2330 // bx lr - Return from this function.
2331 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002332 BuildMI(AllocMBB, DL, TII.get(Opcode)).add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002333
2334 // Restore SR0 and SR1 in case of __morestack() was not called.
2335 // pop {SR0, SR1}
2336 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002337 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2338 .add(predOps(ARMCC::AL))
2339 .addReg(ScratchReg0)
2340 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002341 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002342 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2343 .addReg(ARM::SP, RegState::Define)
2344 .addReg(ARM::SP)
2345 .add(predOps(ARMCC::AL))
2346 .addReg(ScratchReg0)
2347 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002348 }
2349
2350 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002351 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002352 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2353 .addCFIIndex(CFIIndex);
2354
2355 // Tell debuggers that r4 and r5 are now the same as they were in the
2356 // previous function, that they're the "Same Value".
Matthias Braunf23ef432016-11-30 23:48:42 +00002357 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002358 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2359 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2360 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002361 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002362 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2363 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2364 .addCFIIndex(CFIIndex);
2365
2366 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002367 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002368
2369 AllocMBB->addSuccessor(PostStackMBB);
2370
2371 GetMBB->addSuccessor(PostStackMBB);
2372 GetMBB->addSuccessor(AllocMBB);
2373
2374 McrMBB->addSuccessor(GetMBB);
2375
2376 PrevStackMBB->addSuccessor(McrMBB);
2377
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002378#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002379 MF.verify();
2380#endif
2381}