blob: d1e4bce1e0cd9a3e85475c066028f8332a540b5c [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +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"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000019#include "ARMSubtarget.h"
Evan Chenga20cde32011-07-20 23:34:39 +000020#include "MCTargetDesc/ARMAddressingModes.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000021#include "MCTargetDesc/ARMBaseInfo.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000022#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000023#include "llvm/ADT/BitVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000027#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000031#include "llvm/CodeGen/MachineInstr.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000033#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000034#include "llvm/CodeGen/MachineOperand.h"
Evan Chengeb56dca2010-11-22 18:12:04 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +000036#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000037#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetOpcodes.h"
39#include "llvm/CodeGen/TargetRegisterInfo.h"
40#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000041#include "llvm/IR/Attributes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/CallingConv.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000045#include "llvm/MC/MCContext.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000046#include "llvm/MC/MCDwarf.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000047#include "llvm/MC/MCInstrDesc.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000048#include "llvm/MC/MCRegisterInfo.h"
49#include "llvm/Support/CodeGen.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000050#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000051#include "llvm/Support/Compiler.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000056#include "llvm/Target/TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/Target/TargetOptions.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000058#include <algorithm>
59#include <cassert>
60#include <cstddef>
61#include <cstdint>
62#include <iterator>
63#include <utility>
64#include <vector>
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000065
Reid Klecknerbdfc05f2016-10-11 21:14:03 +000066#define DEBUG_TYPE "arm-frame-lowering"
67
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000068using namespace llvm;
69
Benjamin Kramer9fceb902012-02-24 22:09:25 +000070static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000071SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000072 cl::desc("Align ARM NEON spills in prolog and epilog"));
73
74static MachineBasicBlock::iterator
75skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
76 unsigned NumAlignedDPRCS2Regs);
77
Eric Christopher45fb7b62014-06-26 19:29:59 +000078ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
79 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
80 STI(sti) {}
81
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000082bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
83 // iOS always has a FP for backtracking, force other targets to keep their FP
84 // when doing FastISel. The emitted code is currently superior, and in cases
85 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
86 return TargetFrameLowering::noFramePointerElim(MF) ||
87 MF.getSubtarget<ARMSubtarget>().useFastISel();
88}
89
Tim Northovere25e4582018-04-07 10:57:03 +000090/// Returns true if the target can safely skip saving callee-saved registers
91/// for noreturn nounwind functions.
92bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
93 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
94 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
95 !MF.getFunction().hasFnAttribute(Attribute::UWTable));
96
97 // Frame pointer and link register are not treated as normal CSR, thus we
98 // can always skip CSR saves for nonreturning functions.
99 return true;
100}
101
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000102/// hasFP - Return true if the specified function should have a dedicated frame
103/// pointer register. This is true if the function has variable sized allocas
104/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000105bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000106 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000107 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000108
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000109 // ABI-required frame pointer.
110 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000111 return true;
112
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000113 // Frame pointer required for use within this function.
114 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +0000115 MFI.hasVarSizedObjects() ||
116 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000117}
118
Bob Wilson657f2272011-01-13 21:10:12 +0000119/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
120/// not required, we reserve argument space for call sites in the function
121/// immediately on entry to the current function. This eliminates the need for
122/// add/sub sp brackets around call sites. Returns true if the call frame is
123/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000124bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000125 const MachineFrameInfo &MFI = MF.getFrameInfo();
126 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000127 // It's not always a good idea to include the call frame as part of the
128 // stack frame. ARM (especially Thumb) has small immediate offset to
129 // address the stack frame. So a large call frame can cause poor codegen
130 // and may even makes it impossible to scavenge a register.
131 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
132 return false;
133
Matthias Braun941a7052016-07-28 18:40:00 +0000134 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000135}
136
Bob Wilson657f2272011-01-13 21:10:12 +0000137/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
138/// call frame pseudos can be simplified. Unlike most targets, having a FP
139/// is not sufficient here since we still may reference some objects via SP
140/// even when FP is available in Thumb2 mode.
141bool
142ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000143 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000144}
145
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000146static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000147 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000148 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000149 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000150 // The first two operands are predicates. The last two are
151 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000152 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
153 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000154 return false;
155 return true;
156 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000157 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
158 MI.getOpcode() == ARM::LDR_POST_REG ||
159 MI.getOpcode() == ARM::t2LDR_POST) &&
160 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
161 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000162 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000163
164 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000165}
166
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000167static void emitRegPlusImmediate(
168 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
169 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
170 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
171 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000172 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000173 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000174 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000175 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000176 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000177 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000178}
179
Tim Northoverc9432eb2013-11-04 23:04:15 +0000180static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000181 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000182 const ARMBaseInstrInfo &TII, int NumBytes,
183 unsigned MIFlags = MachineInstr::NoFlags,
184 ARMCC::CondCodes Pred = ARMCC::AL,
185 unsigned PredReg = 0) {
186 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
187 MIFlags, Pred, PredReg);
188}
189
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000190static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000191 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000192 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000193 case ARM::VSTMDDB_UPD:
194 RegSize = 8;
195 break;
196 case ARM::STMDB_UPD:
197 case ARM::t2STMDB_UPD:
198 RegSize = 4;
199 break;
200 case ARM::t2STR_PRE:
201 case ARM::STR_PRE_IMM:
202 return 4;
203 default:
204 llvm_unreachable("Unknown push or pop like instruction");
205 }
206
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000207 int count = 0;
208 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
209 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000210 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000211 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000212 return count;
213}
214
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000215static bool WindowsRequiresStackProbe(const MachineFunction &MF,
216 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000217 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000218 const Function &F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000219 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Matthias Braunf1caa282017-12-15 22:22:58 +0000220 if (F.hasFnAttribute("stack-probe-size"))
221 F.getFnAttribute("stack-probe-size")
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000222 .getValueAsString()
223 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000224 return (StackSizeInBytes >= StackProbeSize) &&
225 !F.hasFnAttribute("no-stack-arg-probe");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000226}
227
Tim Northover603d3162014-11-14 22:45:33 +0000228namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000229
Tim Northover603d3162014-11-14 22:45:33 +0000230struct StackAdjustingInsts {
231 struct InstInfo {
232 MachineBasicBlock::iterator I;
233 unsigned SPAdjust;
234 bool BeforeFPSet;
235 };
236
237 SmallVector<InstInfo, 4> Insts;
238
239 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
240 bool BeforeFPSet = false) {
241 InstInfo Info = {I, SPAdjust, BeforeFPSet};
242 Insts.push_back(Info);
243 }
244
245 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000246 auto Info =
247 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000248 assert(Info != Insts.end() && "invalid sp adjusting instruction");
249 Info->SPAdjust += ExtraBytes;
250 }
251
Matthias Braunf23ef432016-11-30 23:48:42 +0000252 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
253 const ARMBaseInstrInfo &TII, bool HasFP) {
254 MachineFunction &MF = *MBB.getParent();
Tim Northover603d3162014-11-14 22:45:33 +0000255 unsigned CFAOffset = 0;
256 for (auto &Info : Insts) {
257 if (HasFP && !Info.BeforeFPSet)
258 return;
259
260 CFAOffset -= Info.SPAdjust;
Matthias Braunf23ef432016-11-30 23:48:42 +0000261 unsigned CFIIndex = MF.addFrameInst(
Tim Northover603d3162014-11-14 22:45:33 +0000262 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
263 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000264 TII.get(TargetOpcode::CFI_INSTRUCTION))
265 .addCFIIndex(CFIIndex)
266 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000267 }
268 }
269};
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000270
271} // end anonymous namespace
Tim Northover603d3162014-11-14 22:45:33 +0000272
Kristof Beyls933de7a2015-01-08 15:09:14 +0000273/// Emit an instruction sequence that will align the address in
274/// register Reg by zero-ing out the lower bits. For versions of the
275/// architecture that support Neon, this must be done in a single
276/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
277/// single instruction. That function only gets called when optimizing
278/// spilling of D registers on a core with the Neon instruction set
279/// present.
280static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
281 const TargetInstrInfo &TII,
282 MachineBasicBlock &MBB,
283 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000284 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000285 const unsigned Alignment,
286 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000287 const ARMSubtarget &AST =
288 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000289 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
290 const unsigned AlignMask = Alignment - 1;
291 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
292 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
293 if (!AFI->isThumbFunction()) {
294 // if the BFC instruction is available, use that to zero the lower
295 // bits:
296 // bfc Reg, #0, log2(Alignment)
297 // otherwise use BIC, if the mask to zero the required number of bits
298 // can be encoded in the bic immediate field
299 // bic Reg, Reg, Alignment-1
300 // otherwise, emit
301 // lsr Reg, Reg, log2(Alignment)
302 // lsl Reg, Reg, log2(Alignment)
303 if (CanUseBFC) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000304 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
305 .addReg(Reg, RegState::Kill)
306 .addImm(~AlignMask)
307 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000308 } else if (AlignMask <= 255) {
Diana Picus8a73f552017-01-13 10:18:01 +0000309 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
310 .addReg(Reg, RegState::Kill)
311 .addImm(AlignMask)
312 .add(predOps(ARMCC::AL))
313 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000314 } else {
315 assert(!MustBeSingleInstruction &&
316 "Shouldn't call emitAligningInstructions demanding a single "
317 "instruction to be emitted for large stack alignment for a target "
318 "without BFC.");
Diana Picus8a73f552017-01-13 10:18:01 +0000319 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
320 .addReg(Reg, RegState::Kill)
321 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
322 .add(predOps(ARMCC::AL))
323 .add(condCodeOp());
324 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
325 .addReg(Reg, RegState::Kill)
326 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
327 .add(predOps(ARMCC::AL))
328 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000329 }
330 } else {
331 // Since this is only reached for Thumb-2 targets, the BFC instruction
332 // should always be available.
333 assert(CanUseBFC);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000334 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
335 .addReg(Reg, RegState::Kill)
336 .addImm(~AlignMask)
337 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000338 }
339}
340
Matthias Braun8aaa3682017-04-19 21:11:44 +0000341/// We need the offset of the frame pointer relative to other MachineFrameInfo
342/// offsets which are encoded relative to SP at function begin.
343/// See also emitPrologue() for how the FP is set up.
344/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
345/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
346/// this to produce a conservative estimate that we check in an assert() later.
347static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
348 // This is a conservative estimation: Assume the frame pointer being r7 and
349 // pc("r15") up to r8 getting spilled before (= 8 registers).
350 return -AFI.getArgRegsSaveSize() - (8 * 4);
351}
352
Quentin Colombet61b305e2015-05-05 17:38:16 +0000353void ARMFrameLowering::emitPrologue(MachineFunction &MF,
354 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000355 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000356 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000357 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000358 MachineModuleInfo &MMI = MF.getMMI();
359 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000360 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000361 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000362 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
363 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000364 assert(!AFI->isThumb1OnlyFunction() &&
365 "This emitPrologue does not support Thumb1!");
366 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000367 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000368 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000369 unsigned NumBytes = MFI.getStackSize();
370 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000371
372 // Debug location must be unknown since the first debug location is used
373 // to determine the end of the prologue.
374 DebugLoc dl;
Fangrui Songf78650a2018-07-30 19:41:25 +0000375
Tim Northover775aaeb2015-11-05 21:54:58 +0000376 unsigned FramePtr = RegInfo->getFrameRegister(MF);
377
378 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000379 // belongs to which callee-save spill areas.
380 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
381 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000382 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000383
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000384 // All calls are tail calls in GHC calling conv, and functions have no
385 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000386 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000387 return;
388
Tim Northover603d3162014-11-14 22:45:33 +0000389 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000390 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000391
Oliver Stannardd55e1152014-03-05 15:25:27 +0000392 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000393 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000394 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000395 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000396 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000397 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000398
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000399 if (!AFI->hasStackFrame() &&
400 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000401 if (NumBytes - ArgRegsSaveSize != 0) {
402 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000403 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000404 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
405 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000406 }
Matthias Braunf23ef432016-11-30 23:48:42 +0000407 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000408 return;
409 }
410
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000411 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000412 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
413 unsigned Reg = CSI[i].getReg();
414 int FI = CSI[i].getFrameIdx();
415 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000416 case ARM::R8:
417 case ARM::R9:
418 case ARM::R10:
419 case ARM::R11:
420 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000421 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000422 GPRCS2Size += 4;
423 break;
424 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000425 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000426 case ARM::R0:
427 case ARM::R1:
428 case ARM::R2:
429 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000430 case ARM::R4:
431 case ARM::R5:
432 case ARM::R6:
433 case ARM::R7:
434 case ARM::LR:
435 if (Reg == FramePtr)
436 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000437 GPRCS1Size += 4;
438 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000439 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000440 // This is a DPR. Exclude the aligned DPRCS2 spills.
441 if (Reg == ARM::D8)
442 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000443 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000444 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000445 }
446 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000447
Eric Christopherb006fc92010-11-18 19:40:05 +0000448 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000449 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
450 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000451 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000452 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
453 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000454
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000455 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000456 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
457 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
458 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
459 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
460 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000461 int FramePtrOffsetInPush = 0;
462 if (HasFP) {
Matthias Braun8aaa3682017-04-19 21:11:44 +0000463 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
Matthias Braunf1caa282017-12-15 22:22:58 +0000464 assert(getMaxFPOffset(MF.getFunction(), *AFI) <= FPOffset &&
Matthias Braun8aaa3682017-04-19 21:11:44 +0000465 "Max FP estimation is wrong");
466 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
Matthias Braun941a7052016-07-28 18:40:00 +0000467 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000468 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000469 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000470 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
471 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
472 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
473
Tim Northoverc9432eb2013-11-04 23:04:15 +0000474 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000475 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000476 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000477 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
478 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000479
Tim Northover228c9432014-11-05 00:27:13 +0000480 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
481 // .cfi_offset operations will reflect that.
482 if (DPRGapSize) {
483 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000484 if (LastPush != MBB.end() &&
485 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000486 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
487 else {
Tim Northover228c9432014-11-05 00:27:13 +0000488 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
489 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000490 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
491 }
Tim Northover228c9432014-11-05 00:27:13 +0000492 }
493
Eric Christopherb006fc92010-11-18 19:40:05 +0000494 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000495 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000496 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000497 // instructions in the prologue.
Matthias Braun5d01e702017-11-28 01:17:52 +0000498 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000499 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000500 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000501 }
Evan Cheng70d29632011-02-25 00:24:46 +0000502 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000503
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000504 // Move past the aligned DPRCS2 area.
505 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
506 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
507 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
508 // leaves the stack pointer pointing to the DPRCS2 area.
509 //
510 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000511 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000512 } else
513 NumBytes = DPRCSOffset;
514
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000515 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
516 uint32_t NumWords = NumBytes >> 2;
517
518 if (NumWords < 65536)
Diana Picus4f8c3e12017-01-13 09:37:56 +0000519 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
520 .addImm(NumWords)
521 .setMIFlags(MachineInstr::FrameSetup)
522 .add(predOps(ARMCC::AL));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000523 else
524 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000525 .addImm(NumWords)
526 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000527
528 switch (TM.getCodeModel()) {
David Green9dd1d452018-08-22 11:31:39 +0000529 case CodeModel::Tiny:
530 llvm_unreachable("Tiny code model not available on ARM.");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000531 case CodeModel::Small:
532 case CodeModel::Medium:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000533 case CodeModel::Kernel:
534 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000535 .add(predOps(ARMCC::AL))
536 .addExternalSymbol("__chkstk")
537 .addReg(ARM::R4, RegState::Implicit)
538 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000539 break;
540 case CodeModel::Large:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000541 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000542 .addExternalSymbol("__chkstk")
543 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000544
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000545 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000546 .add(predOps(ARMCC::AL))
547 .addReg(ARM::R12, RegState::Kill)
548 .addReg(ARM::R4, RegState::Implicit)
549 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000550 break;
551 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000552
Diana Picus8a73f552017-01-13 10:18:01 +0000553 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
554 .addReg(ARM::SP, RegState::Kill)
555 .addReg(ARM::R4, RegState::Kill)
556 .setMIFlags(MachineInstr::FrameSetup)
557 .add(predOps(ARMCC::AL))
558 .add(condCodeOp());
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000559 NumBytes = 0;
560 }
561
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000562 if (NumBytes) {
563 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000564 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000565 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000566 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
567 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000568 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
569 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000570 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
571 }
Tim Northover93bcc662013-11-08 17:18:07 +0000572
Evan Chengeb56dca2010-11-22 18:12:04 +0000573 if (HasFP && isARM)
574 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
575 // Note it's not safe to do this in Thumb2 mode because it would have
576 // taken two instructions:
577 // mov sp, r7
578 // sub sp, #24
579 // If an interrupt is taken between the two instructions, then sp is in
580 // an inconsistent state (pointing to the middle of callee-saved area).
581 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000582 AFI->setShouldRestoreSPFromFP(true);
583 }
584
Tim Northover603d3162014-11-14 22:45:33 +0000585 // Set FP to point to the stack slot that contains the previous FP.
586 // For iOS, FP is R7, which has now been stored in spill area 1.
587 // Otherwise, if this is not iOS, all the callee-saved registers go
588 // into spill area 1, including the FP in R11. In either case, it
589 // is in area one and the adjustment needs to take place just after
590 // that push.
591 if (HasFP) {
592 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000593 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000594 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
595 dl, TII, FramePtr, ARM::SP,
596 PushSize + FramePtrOffsetInPush,
597 MachineInstr::FrameSetup);
598 if (FramePtrOffsetInPush + PushSize != 0) {
Matthias Braunf23ef432016-11-30 23:48:42 +0000599 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
Tim Northover603d3162014-11-14 22:45:33 +0000600 nullptr, MRI->getDwarfRegNum(FramePtr, true),
601 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
602 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000603 .addCFIIndex(CFIIndex)
604 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000605 } else {
606 unsigned CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +0000607 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
Tim Northover603d3162014-11-14 22:45:33 +0000608 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
609 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000610 .addCFIIndex(CFIIndex)
611 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000612 }
613 }
614
615 // Now that the prologue's actual instructions are finalised, we can insert
616 // the necessary DWARF cf instructions to describe the situation. Start by
617 // recording where each register ended up:
618 if (GPRCS1Size > 0) {
619 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
620 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000621 for (const auto &Entry : CSI) {
622 unsigned Reg = Entry.getReg();
623 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000624 switch (Reg) {
625 case ARM::R8:
626 case ARM::R9:
627 case ARM::R10:
628 case ARM::R11:
629 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000630 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000631 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000632 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000633 case ARM::R0:
634 case ARM::R1:
635 case ARM::R2:
636 case ARM::R3:
637 case ARM::R4:
638 case ARM::R5:
639 case ARM::R6:
640 case ARM::R7:
641 case ARM::LR:
Matthias Braunf23ef432016-11-30 23:48:42 +0000642 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000643 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000644 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000645 .addCFIIndex(CFIIndex)
646 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000647 break;
648 }
649 }
650 }
651
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000652 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000653 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000654 for (const auto &Entry : CSI) {
655 unsigned Reg = Entry.getReg();
656 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000657 switch (Reg) {
658 case ARM::R8:
659 case ARM::R9:
660 case ARM::R10:
661 case ARM::R11:
662 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000663 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000664 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000665 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000666 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000667 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
668 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000669 .addCFIIndex(CFIIndex)
670 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000671 }
672 break;
673 }
674 }
675 }
676
677 if (DPRCSSize > 0) {
678 // Since vpush register list cannot have gaps, there may be multiple vpush
679 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000680 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000681 for (const auto &Entry : CSI) {
682 unsigned Reg = Entry.getReg();
683 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000684 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
685 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
686 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000687 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000688 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000689 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000690 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000691 .addCFIIndex(CFIIndex)
692 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000693 }
694 }
695 }
696
Tim Northover603d3162014-11-14 22:45:33 +0000697 // Now we can emit descriptions of where the canonical frame address was
698 // throughout the process. If we have a frame pointer, it takes over the job
699 // half-way through, so only the first few .cfi_def_cfa_offset instructions
700 // actually get emitted.
Matthias Braunf23ef432016-11-30 23:48:42 +0000701 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000702
Evan Chengeb56dca2010-11-22 18:12:04 +0000703 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000704 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
705 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000706
707 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
708 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000709 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000710 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
711
712 // If we need dynamic stack realignment, do it here. Be paranoid and make
713 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000714 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000715 // realigned.
716 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000717 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000718 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000719 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000720 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
721 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000722 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000723 // We cannot use sp as source/dest register here, thus we're using r4 to
724 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000725 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000726 // -- use emitAligningInstructions to produce best sequence to zero
727 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000728 // mov sp, r4
729 // FIXME: It will be better just to find spare register here.
Diana Picus4f8c3e12017-01-13 09:37:56 +0000730 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
731 .addReg(ARM::SP, RegState::Kill)
732 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000733 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
734 false);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000735 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
736 .addReg(ARM::R4, RegState::Kill)
737 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000738 }
739
740 AFI->setShouldRestoreSPFromFP(true);
741 }
742
743 // If we need a base pointer, set it up here. It's whatever the value
744 // of the stack pointer is at this point. Any variable size objects
745 // will be allocated after this, so we can still use the base pointer
746 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000747 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000748 if (RegInfo->hasBasePointer(MF)) {
749 if (isARM)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000750 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
751 .addReg(ARM::SP)
752 .add(predOps(ARMCC::AL))
753 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000754 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000755 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
756 .addReg(ARM::SP)
757 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000758 }
759
760 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000761 // the sp from fp. We can assume there's an FP here since hasFP already
762 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000763 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000764 AFI->setShouldRestoreSPFromFP(true);
765}
766
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000767void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000768 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000769 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000770 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000771 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000772 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000773 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000774 assert(!AFI->isThumb1OnlyFunction() &&
775 "This emitEpilogue does not support Thumb1!");
776 bool isARM = !AFI->isThumbFunction();
777
Tim Northover8cda34f2015-03-11 18:54:22 +0000778 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000779 int NumBytes = (int)MFI.getStackSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000780 unsigned FramePtr = RegInfo->getFrameRegister(MF);
781
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000782 // All calls are tail calls in GHC calling conv, and functions have no
783 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000784 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000785 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000786
787 // First put ourselves on the first (from top) terminator instructions.
788 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
789 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000790
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000791 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000792 if (NumBytes - ArgRegsSaveSize != 0)
793 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000794 } else {
795 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000796 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000797 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000798 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000799 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000800 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
801 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000802 ++MBBI;
803 }
804
805 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000806 NumBytes -= (ArgRegsSaveSize +
807 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000808 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000809 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000810 AFI->getDPRCalleeSavedAreaSize());
811
812 // Reset SP based on frame pointer only if the stack frame extends beyond
813 // frame pointer stack slot or target is ELF and the function has FP.
814 if (AFI->shouldRestoreSPFromFP()) {
815 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
816 if (NumBytes) {
817 if (isARM)
818 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
819 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000820 else {
821 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000822 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000823 // mov sp, r7
824 // sub sp, #24
825 // This is bad, if an interrupt is taken after the mov, sp is in an
826 // inconsistent state.
827 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000828 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000829 "No scratch register to restore SP from FP!");
830 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000831 ARMCC::AL, 0, TII);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000832 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
833 .addReg(ARM::R4)
834 .add(predOps(ARMCC::AL));
Evan Chengeb56dca2010-11-22 18:12:04 +0000835 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000836 } else {
837 // Thumb2 or ARM.
838 if (isARM)
839 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000840 .addReg(FramePtr)
841 .add(predOps(ARMCC::AL))
842 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000843 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000844 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
845 .addReg(FramePtr)
846 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000847 }
Tim Northoverdee86042013-12-02 14:46:26 +0000848 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000849 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
850 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000851
Eric Christopherb006fc92010-11-18 19:40:05 +0000852 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000853 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000854 MBBI++;
855 // Since vpop register list cannot have gaps, there may be multiple vpop
856 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000857 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000858 MBBI++;
859 }
Tim Northover228c9432014-11-05 00:27:13 +0000860 if (AFI->getDPRCalleeSavedGapSize()) {
861 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
862 "unexpected DPR alignment gap");
863 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
864 }
865
Eric Christopherb006fc92010-11-18 19:40:05 +0000866 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
867 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000868 }
869
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000870 if (ArgRegsSaveSize)
871 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000872}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000873
Bob Wilson657f2272011-01-13 21:10:12 +0000874/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
875/// debug info. It's the same as what we use for resolving the code-gen
876/// references for now. FIXME: This can go wrong when references are
877/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000878int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000879ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000880 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000881 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
882}
883
884int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000885ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000886 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000887 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000888 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000889 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000890 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000891 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000892 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000893 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000894 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000895
896 FrameReg = ARM::SP;
897 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000898
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000899 // SP can move around if there are allocas. We may also lose track of SP
900 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000901 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000902
Anton Korobeynikov46877782010-11-20 15:59:32 +0000903 // When dynamically realigning the stack, use the frame pointer for
904 // parameters, and the stack/base pointer for locals.
905 if (RegInfo->needsStackRealignment(MF)) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000906 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000907 if (isFixed) {
908 FrameReg = RegInfo->getFrameRegister(MF);
909 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000910 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000911 assert(RegInfo->hasBasePointer(MF) &&
912 "VLAs and dynamic stack alignment, but missing base pointer!");
913 FrameReg = RegInfo->getBaseRegister();
914 }
915 return Offset;
916 }
917
918 // If there is a frame pointer, use it when we can.
919 if (hasFP(MF) && AFI->hasStackFrame()) {
920 // Use frame pointer to reference fixed objects. Use it for locals if
921 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000922 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000923 FrameReg = RegInfo->getFrameRegister(MF);
924 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000925 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000926 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000927 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000928 // Try to use the frame pointer if we can, else use the base pointer
929 // since it's available. This is handy for the emergency spill slot, in
930 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000931 if (FPOffset >= -255 && FPOffset < 0) {
932 FrameReg = RegInfo->getFrameRegister(MF);
933 return FPOffset;
934 }
Evan Chengc0d20042011-04-22 01:42:52 +0000935 }
Momchil Velikov505614b2018-03-02 15:47:14 +0000936 } else if (AFI->isThumbFunction()) {
937 // Prefer SP to base pointer, if the offset is suitably aligned and in
938 // range as the effective range of the immediate offset is bigger when
939 // basing off SP.
Andrew Trickf7ecc162011-08-25 17:40:54 +0000940 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000941 // ldr <rd>, [sp, #<imm8>]
Evan Chengc0d20042011-04-22 01:42:52 +0000942 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
943 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000944 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000945 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Momchil Velikov505614b2018-03-02 15:47:14 +0000946 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000947 FrameReg = RegInfo->getFrameRegister(MF);
948 return FPOffset;
949 }
950 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
951 // Otherwise, use SP or FP, whichever is closer to the stack slot.
952 FrameReg = RegInfo->getFrameRegister(MF);
953 return FPOffset;
954 }
955 }
956 // Use the base pointer if we have one.
957 if (RegInfo->hasBasePointer(MF))
958 FrameReg = RegInfo->getBaseRegister();
959 return Offset;
960}
961
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000962void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000963 MachineBasicBlock::iterator MI,
964 const std::vector<CalleeSavedInfo> &CSI,
965 unsigned StmOpc, unsigned StrOpc,
966 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000967 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000968 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000969 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000970 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000971 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000972 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000973
974 DebugLoc DL;
975
Eugene Zelenko076468c2017-09-20 21:35:51 +0000976 using RegAndKill = std::pair<unsigned, bool>;
977
Tim Northover46a6f0f2016-11-14 20:28:24 +0000978 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000979 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000980 while (i != 0) {
981 unsigned LastReg = 0;
982 for (; i != 0; --i) {
983 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000984 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000985
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000986 // D-registers in the aligned area DPRCS2 are NOT spilled here.
987 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
988 continue;
989
Matthias Braun0dba4e32017-05-31 01:21:30 +0000990 const MachineRegisterInfo &MRI = MF.getRegInfo();
991 bool isLiveIn = MRI.isLiveIn(Reg);
992 if (!isLiveIn && !MRI.isReserved(Reg))
Evan Cheng775ead32010-12-07 23:08:38 +0000993 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000994 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000995 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000996 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000997 if (NoGap && LastReg && LastReg != Reg-1)
998 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000999 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +00001000 // Do not set a kill flag on values that are also marked as live-in. This
1001 // happens with the @llvm-returnaddress intrinsic and with arguments
1002 // passed in callee saved registers.
1003 // Omitting the kill flags is conservatively correct even if the live-in
1004 // is not used after all.
1005 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001006 }
1007
Jim Grosbach5fccad82010-12-09 18:31:13 +00001008 if (Regs.empty())
1009 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001010
Fangrui Song0cac7262018-09-27 02:13:45 +00001011 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001012 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1013 });
1014
Jim Grosbach5fccad82010-12-09 18:31:13 +00001015 if (Regs.size() > 1 || StrOpc== 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001016 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1017 .addReg(ARM::SP)
1018 .setMIFlags(MIFlags)
1019 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001020 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1021 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +00001022 } else if (Regs.size() == 1) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001023 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1024 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1025 .addReg(ARM::SP)
1026 .setMIFlags(MIFlags)
1027 .addImm(-4)
1028 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001029 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001030 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001031
1032 // Put any subsequent vpush instructions before this one: they will refer to
1033 // higher register numbers so need to be pushed first in order to preserve
1034 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +00001035 if (MI != MBB.begin())
1036 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001037 }
Evan Cheng775ead32010-12-07 23:08:38 +00001038}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001039
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001040void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001041 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001042 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001043 unsigned LdmOpc, unsigned LdrOpc,
1044 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001045 bool(*Func)(unsigned, bool),
1046 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001047 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001048 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +00001049 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001050 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +00001051 DebugLoc DL;
1052 bool isTailCall = false;
1053 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001054 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +00001055 if (MBB.end() != MI) {
1056 DL = MI->getDebugLoc();
1057 unsigned RetOpcode = MI->getOpcode();
1058 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1059 isInterrupt =
1060 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001061 isTrap =
1062 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1063 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +00001064 }
Evan Cheng775ead32010-12-07 23:08:38 +00001065
1066 SmallVector<unsigned, 4> Regs;
1067 unsigned i = CSI.size();
1068 while (i != 0) {
1069 unsigned LastReg = 0;
1070 bool DeleteRet = false;
1071 for (; i != 0; --i) {
Matthias Braun51687912017-09-28 23:12:06 +00001072 CalleeSavedInfo &Info = CSI[i-1];
1073 unsigned Reg = Info.getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001074 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001075
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001076 // The aligned reloads from area DPRCS2 are not inserted here.
1077 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1078 continue;
1079
Tim Northoverd8407452013-10-01 14:33:28 +00001080 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001081 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001082 if (MBB.succ_empty()) {
1083 Reg = ARM::PC;
Thomas Preud'hommec699eaa2018-03-05 11:49:00 +00001084 // Fold the return instruction into the LDM.
Quentin Colombet71a71482015-07-20 21:42:14 +00001085 DeleteRet = true;
1086 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Matthias Braun51687912017-09-28 23:12:06 +00001087 // We 'restore' LR into PC so it is not live out of the return block:
1088 // Clear Restored bit.
1089 Info.setRestored(false);
Quentin Colombet71a71482015-07-20 21:42:14 +00001090 } else
1091 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001092 }
1093
Evan Cheng9d54ae62010-12-08 06:29:02 +00001094 // If NoGap is true, pop consecutive registers and then leave the rest
1095 // for other instructions. e.g.
1096 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1097 if (NoGap && LastReg && LastReg != Reg-1)
1098 break;
1099
Evan Cheng775ead32010-12-07 23:08:38 +00001100 LastReg = Reg;
1101 Regs.push_back(Reg);
1102 }
1103
Jim Grosbach5fccad82010-12-09 18:31:13 +00001104 if (Regs.empty())
1105 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001106
Fangrui Song0cac7262018-09-27 02:13:45 +00001107 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001108 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1109 });
1110
Jim Grosbach5fccad82010-12-09 18:31:13 +00001111 if (Regs.size() > 1 || LdrOpc == 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001112 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1113 .addReg(ARM::SP)
1114 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001115 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1116 MIB.addReg(Regs[i], getDefRegState(true));
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001117 if (DeleteRet) {
1118 if (MI != MBB.end()) {
1119 MIB.copyImplicitOps(*MI);
1120 MI->eraseFromParent();
1121 }
Andrew Trick6446bf72011-08-25 17:50:53 +00001122 }
Evan Cheng775ead32010-12-07 23:08:38 +00001123 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001124 } else if (Regs.size() == 1) {
1125 // If we adjusted the reg to PC from LR above, switch it back here. We
1126 // only do that for LDM.
1127 if (Regs[0] == ARM::PC)
1128 Regs[0] = ARM::LR;
1129 MachineInstrBuilder MIB =
1130 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1131 .addReg(ARM::SP, RegState::Define)
1132 .addReg(ARM::SP);
1133 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1134 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001135 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001136 MIB.addReg(0);
1137 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1138 } else
1139 MIB.addImm(4);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001140 MIB.add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001141 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001142 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001143
1144 // Put any subsequent vpop instructions after this one: they will refer to
1145 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001146 if (MI != MBB.end())
1147 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001148 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001149}
1150
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001151/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001152/// starting from d8. Also insert stack realignment code and leave the stack
1153/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001154static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1155 MachineBasicBlock::iterator MI,
1156 unsigned NumAlignedDPRCS2Regs,
1157 const std::vector<CalleeSavedInfo> &CSI,
1158 const TargetRegisterInfo *TRI) {
1159 MachineFunction &MF = *MBB.getParent();
1160 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001161 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001162 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001163 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001164
1165 // Mark the D-register spill slots as properly aligned. Since MFI computes
1166 // stack slot layout backwards, this can actually mean that the d-reg stack
1167 // slot offsets can be wrong. The offset for d8 will always be correct.
1168 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1169 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001170 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001171 continue;
1172 int FI = CSI[i].getFrameIdx();
1173 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1174 // registers will be 8-byte aligned.
1175 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1176
1177 // The stack slot for D8 needs to be maximally aligned because this is
1178 // actually the point where we align the stack pointer. MachineFrameInfo
1179 // computes all offsets relative to the incoming stack pointer which is a
1180 // bit weird when realigning the stack. Any extra padding for this
1181 // over-alignment is not realized because the code inserted below adjusts
1182 // the stack pointer by numregs * 8 before aligning the stack pointer.
1183 if (DNum == 0)
1184 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1185 }
1186
1187 // Move the stack pointer to the d8 spill slot, and align it at the same
1188 // time. Leave the stack slot address in the scratch register r4.
1189 //
1190 // sub r4, sp, #numregs * 8
1191 // bic r4, r4, #align - 1
1192 // mov sp, r4
1193 //
1194 bool isThumb = AFI->isThumbFunction();
1195 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1196 AFI->setShouldRestoreSPFromFP(true);
1197
1198 // sub r4, sp, #numregs * 8
1199 // The immediate is <= 64, so it doesn't need any special encoding.
1200 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
Diana Picus8a73f552017-01-13 10:18:01 +00001201 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1202 .addReg(ARM::SP)
1203 .addImm(8 * NumAlignedDPRCS2Regs)
1204 .add(predOps(ARMCC::AL))
1205 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001206
Matthias Braun941a7052016-07-28 18:40:00 +00001207 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001208 // We must set parameter MustBeSingleInstruction to true, since
1209 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1210 // stack alignment. Luckily, this can always be done since all ARM
1211 // architecture versions that support Neon also support the BFC
1212 // instruction.
1213 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001214
1215 // mov sp, r4
1216 // The stack pointer must be adjusted before spilling anything, otherwise
1217 // the stack slots could be clobbered by an interrupt handler.
1218 // Leave r4 live, it is used below.
1219 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1220 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001221 .addReg(ARM::R4)
1222 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001223 if (!isThumb)
Diana Picus8a73f552017-01-13 10:18:01 +00001224 MIB.add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001225
1226 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1227 // r4 holds the stack slot address.
1228 unsigned NextReg = ARM::D8;
1229
1230 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1231 // The writeback is only needed when emitting two vst1.64 instructions.
1232 if (NumAlignedDPRCS2Regs >= 6) {
1233 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001234 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001235 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001236 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1237 .addReg(ARM::R4, RegState::Kill)
1238 .addImm(16)
1239 .addReg(NextReg)
1240 .addReg(SupReg, RegState::ImplicitKill)
1241 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001242 NextReg += 4;
1243 NumAlignedDPRCS2Regs -= 4;
1244 }
1245
1246 // We won't modify r4 beyond this point. It currently points to the next
1247 // register to be spilled.
1248 unsigned R4BaseReg = NextReg;
1249
1250 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1251 if (NumAlignedDPRCS2Regs >= 4) {
1252 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001253 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001254 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001255 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1256 .addReg(ARM::R4)
1257 .addImm(16)
1258 .addReg(NextReg)
1259 .addReg(SupReg, RegState::ImplicitKill)
1260 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001261 NextReg += 4;
1262 NumAlignedDPRCS2Regs -= 4;
1263 }
1264
1265 // 16-byte aligned vst1.64 with 2 d-regs.
1266 if (NumAlignedDPRCS2Regs >= 2) {
1267 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001268 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001269 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001270 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1271 .addReg(ARM::R4)
1272 .addImm(16)
1273 .addReg(SupReg)
1274 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001275 NextReg += 2;
1276 NumAlignedDPRCS2Regs -= 2;
1277 }
1278
1279 // Finally, use a vanilla vstr.64 for the odd last register.
1280 if (NumAlignedDPRCS2Regs) {
1281 MBB.addLiveIn(NextReg);
1282 // vstr.64 uses addrmode5 which has an offset scale of 4.
Diana Picus4f8c3e12017-01-13 09:37:56 +00001283 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1284 .addReg(NextReg)
1285 .addReg(ARM::R4)
1286 .addImm((NextReg - R4BaseReg) * 2)
1287 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001288 }
1289
1290 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001291 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001292}
1293
1294/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1295/// iterator to the following instruction.
1296static MachineBasicBlock::iterator
1297skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1298 unsigned NumAlignedDPRCS2Regs) {
1299 // sub r4, sp, #numregs * 8
1300 // bic r4, r4, #align - 1
1301 // mov sp, r4
1302 ++MI; ++MI; ++MI;
1303 assert(MI->mayStore() && "Expecting spill instruction");
1304
1305 // These switches all fall through.
1306 switch(NumAlignedDPRCS2Regs) {
1307 case 7:
1308 ++MI;
1309 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001310 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001311 default:
1312 ++MI;
1313 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001314 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001315 case 1:
1316 case 2:
1317 case 4:
1318 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1319 ++MI;
1320 }
1321 return MI;
1322}
1323
1324/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1325/// starting from d8. These instructions are assumed to execute while the
1326/// stack is still aligned, unlike the code inserted by emitPopInst.
1327static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1328 MachineBasicBlock::iterator MI,
1329 unsigned NumAlignedDPRCS2Regs,
1330 const std::vector<CalleeSavedInfo> &CSI,
1331 const TargetRegisterInfo *TRI) {
1332 MachineFunction &MF = *MBB.getParent();
1333 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001334 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001335 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001336
1337 // Find the frame index assigned to d8.
1338 int D8SpillFI = 0;
1339 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1340 if (CSI[i].getReg() == ARM::D8) {
1341 D8SpillFI = CSI[i].getFrameIdx();
1342 break;
1343 }
1344
1345 // Materialize the address of the d8 spill slot into the scratch register r4.
1346 // This can be fairly complicated if the stack frame is large, so just use
1347 // the normal frame index elimination mechanism to do it. This code runs as
1348 // the initial part of the epilog where the stack and base pointers haven't
1349 // been changed yet.
1350 bool isThumb = AFI->isThumbFunction();
1351 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1352
1353 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
Diana Picus8a73f552017-01-13 10:18:01 +00001354 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1355 .addFrameIndex(D8SpillFI)
1356 .addImm(0)
1357 .add(predOps(ARMCC::AL))
1358 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001359
1360 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1361 unsigned NextReg = ARM::D8;
1362
1363 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1364 if (NumAlignedDPRCS2Regs >= 6) {
1365 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001366 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001367 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1368 .addReg(ARM::R4, RegState::Define)
1369 .addReg(ARM::R4, RegState::Kill)
1370 .addImm(16)
1371 .addReg(SupReg, RegState::ImplicitDefine)
1372 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001373 NextReg += 4;
1374 NumAlignedDPRCS2Regs -= 4;
1375 }
1376
1377 // We won't modify r4 beyond this point. It currently points to the next
1378 // register to be spilled.
1379 unsigned R4BaseReg = NextReg;
1380
1381 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1382 if (NumAlignedDPRCS2Regs >= 4) {
1383 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001384 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001385 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1386 .addReg(ARM::R4)
1387 .addImm(16)
1388 .addReg(SupReg, RegState::ImplicitDefine)
1389 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001390 NextReg += 4;
1391 NumAlignedDPRCS2Regs -= 4;
1392 }
1393
1394 // 16-byte aligned vld1.64 with 2 d-regs.
1395 if (NumAlignedDPRCS2Regs >= 2) {
1396 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001397 &ARM::QPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001398 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1399 .addReg(ARM::R4)
1400 .addImm(16)
1401 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001402 NextReg += 2;
1403 NumAlignedDPRCS2Regs -= 2;
1404 }
1405
1406 // Finally, use a vanilla vldr.64 for the remaining odd register.
1407 if (NumAlignedDPRCS2Regs)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001408 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1409 .addReg(ARM::R4)
1410 .addImm(2 * (NextReg - R4BaseReg))
1411 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001412
1413 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001414 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001415}
1416
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001417bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001418 MachineBasicBlock::iterator MI,
1419 const std::vector<CalleeSavedInfo> &CSI,
1420 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001421 if (CSI.empty())
1422 return false;
1423
1424 MachineFunction &MF = *MBB.getParent();
1425 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001426
1427 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001428 unsigned PushOneOpc = AFI->isThumbFunction() ?
1429 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001430 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001431 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1432 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001433 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001434 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001435 MachineInstr::FrameSetup);
1436 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001437 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1438
1439 // The code above does not insert spill code for the aligned DPRCS2 registers.
1440 // The stack realignment code will be inserted between the push instructions
1441 // and these spills.
1442 if (NumAlignedDPRCS2Regs)
1443 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001444
1445 return true;
1446}
1447
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001448bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001449 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001450 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001451 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001452 if (CSI.empty())
1453 return false;
1454
1455 MachineFunction &MF = *MBB.getParent();
1456 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001457 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001458 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1459
1460 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1461 // registers. Do that here instead.
1462 if (NumAlignedDPRCS2Regs)
1463 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001464
1465 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001466 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001467 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001468 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1469 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001470 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001471 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001472 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001473 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001474
1475 return true;
1476}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001477
1478// FIXME: Make generic?
1479static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1480 const ARMBaseInstrInfo &TII) {
1481 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001482 for (auto &MBB : MF) {
1483 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001484 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001485 }
1486 return FnSize;
1487}
1488
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001489/// estimateRSStackSizeLimit - Look at each instruction that references stack
1490/// frames and return the stack size limit beyond which some of these
1491/// instructions will require a scratch register during their expansion later.
1492// FIXME: Move to TII?
1493static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001494 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001495 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1496 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001497 for (auto &MBB : MF) {
1498 for (auto &MI : MBB) {
1499 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1500 if (!MI.getOperand(i).isFI())
1501 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001502
1503 // When using ADDri to get the address of a stack object, 255 is the
1504 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001505 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001506 Limit = std::min(Limit, (1U << 8) - 1);
1507 break;
1508 }
1509
1510 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001511 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001512 case ARMII::AddrMode3:
1513 case ARMII::AddrModeT2_i8:
1514 Limit = std::min(Limit, (1U << 8) - 1);
1515 break;
1516 case ARMII::AddrMode5:
1517 case ARMII::AddrModeT2_i8s4:
Tim Northoverbb7d7b32018-09-07 09:21:25 +00001518 case ARMII::AddrModeT2_ldrex:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001519 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1520 break;
1521 case ARMII::AddrModeT2_i12:
1522 // i12 supports only positive offset so these will be converted to
1523 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1524 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1525 Limit = std::min(Limit, (1U << 8) - 1);
1526 break;
1527 case ARMII::AddrMode4:
1528 case ARMII::AddrMode6:
1529 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1530 // immediate offset for stack references.
1531 return 0;
1532 default:
1533 break;
1534 }
1535 break; // At most one FI per instruction
1536 }
1537 }
1538 }
1539
1540 return Limit;
1541}
1542
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001543// In functions that realign the stack, it can be an advantage to spill the
1544// callee-saved vector registers after realigning the stack. The vst1 and vld1
1545// instructions take alignment hints that can improve performance.
Matthias Braun02564862015-07-14 17:17:13 +00001546static void
1547checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001548 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1549 if (!SpillAlignedNEONRegs)
1550 return;
1551
1552 // Naked functions don't spill callee-saved registers.
Matthias Braunf1caa282017-12-15 22:22:58 +00001553 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001554 return;
1555
1556 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001557 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001558 return;
1559
1560 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001561 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001562 return;
1563
1564 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001565 if (!static_cast<const ARMBaseRegisterInfo *>(
1566 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001567 return;
1568
1569 // We always spill contiguous d-registers starting from d8. Count how many
1570 // needs spilling. The register allocator will almost always use the
1571 // callee-saved registers in order, but it can happen that there are holes in
1572 // the range. Registers above the hole will be spilled to the standard DPRCS
1573 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001574 unsigned NumSpills = 0;
1575 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001576 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001577 break;
1578
1579 // Don't do this for just one d-register. It's not worth it.
1580 if (NumSpills < 2)
1581 return;
1582
1583 // Spill the first NumSpills D-registers after realigning the stack.
1584 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1585
1586 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001587 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001588}
1589
Matthias Braun02564862015-07-14 17:17:13 +00001590void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1591 BitVector &SavedRegs,
1592 RegScavenger *RS) const {
1593 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001594 // This tells PEI to spill the FP as if it is any other callee-save register
1595 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1596 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1597 // to combine multiple loads / stores.
1598 bool CanEliminateFrame = true;
1599 bool CS1Spilled = false;
1600 bool LRSpilled = false;
1601 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001602 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001603 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1604 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001605 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001606 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001607 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001608 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001609 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001610 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001611 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001612 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1613 (void)TRI; // Silence unused warning in non-assert builds.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001614 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1615
1616 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1617 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001618 // since it's not always possible to restore sp from fp in a single
1619 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001620 // FIXME: It will be better just to find spare register here.
1621 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001622 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001623 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001624
Martin Storsjoace7ae92018-05-14 21:32:52 +00001625 // If a stack probe will be emitted, spill R4 and LR, since they are
1626 // clobbered by the stack probe call.
1627 // This estimate should be a safe, conservative estimate. The actual
1628 // stack probe is enabled based on the size of the local objects;
1629 // this estimate also includes the varargs store size.
1630 if (STI.isTargetWindows() &&
1631 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
1632 SavedRegs.set(ARM::R4);
1633 SavedRegs.set(ARM::LR);
1634 }
1635
Evan Cheng572756a2011-01-16 05:14:33 +00001636 if (AFI->isThumb1OnlyFunction()) {
1637 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001638 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001639 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001640
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001641 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1642 // requires stack alignment. We don't know for sure what the stack size
1643 // will be, but for this, an estimate is good enough. If there anything
1644 // changes it, it'll be a spill, which implies we've used all the registers
1645 // and so R4 is already used, so not marking it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001646 // FIXME: It will be better just to find spare register here.
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001647 if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
1648 MFI.estimateStackSize(MF) > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001649 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001650 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001651
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001652 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001653 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001654
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001655 // Spill the BasePtr if it's used.
1656 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001657 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001658
1659 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001660 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001661 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001662 for (unsigned i = 0; CSRegs[i]; ++i) {
1663 unsigned Reg = CSRegs[i];
1664 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001665 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001666 Spilled = true;
1667 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001668 }
1669
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001670 if (!ARM::GPRRegClass.contains(Reg)) {
1671 if (Spilled) {
1672 if (ARM::SPRRegClass.contains(Reg))
1673 NumFPRSpills++;
1674 else if (ARM::DPRRegClass.contains(Reg))
1675 NumFPRSpills += 2;
1676 else if (ARM::QPRRegClass.contains(Reg))
1677 NumFPRSpills += 4;
1678 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001679 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001680 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001681
1682 if (Spilled) {
1683 NumGPRSpills++;
1684
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001685 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001686 if (Reg == ARM::LR)
1687 LRSpilled = true;
1688 CS1Spilled = true;
1689 continue;
1690 }
1691
1692 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1693 switch (Reg) {
1694 case ARM::LR:
1695 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001696 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001697 case ARM::R0: case ARM::R1:
1698 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001699 case ARM::R4: case ARM::R5:
1700 case ARM::R6: case ARM::R7:
1701 CS1Spilled = true;
1702 break;
1703 default:
1704 break;
1705 }
1706 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001707 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001708 UnspilledCS1GPRs.push_back(Reg);
1709 continue;
1710 }
1711
1712 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001713 case ARM::R0: case ARM::R1:
1714 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001715 case ARM::R4: case ARM::R5:
1716 case ARM::R6: case ARM::R7:
1717 case ARM::LR:
1718 UnspilledCS1GPRs.push_back(Reg);
1719 break;
1720 default:
1721 UnspilledCS2GPRs.push_back(Reg);
1722 break;
1723 }
1724 }
1725 }
1726
1727 bool ForceLRSpill = false;
1728 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1729 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1730 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1731 // use of BL to implement far jump. If it turns out that it's not needed
1732 // then the branch fix up path will undo it.
1733 if (FnSize >= (1 << 11)) {
1734 CanEliminateFrame = false;
1735 ForceLRSpill = true;
1736 }
1737 }
1738
1739 // If any of the stack slot references may be out of range of an immediate
1740 // offset, make sure a register (or a spill slot) is available for the
1741 // register scavenger. Note that if we're indexing off the frame pointer, the
1742 // effective stack size is 4 bytes larger since the FP points to the stack
1743 // slot of the previous FP. Also, if we have variable sized objects in the
1744 // function, stack slot references will often be negative, and some of
1745 // our instructions are positive-offset only, so conservatively consider
1746 // that case to want a spill slot (or register) as well. Similarly, if
1747 // the function adjusts the stack pointer during execution and the
1748 // adjustments aren't already part of our stack size estimate, our offset
1749 // calculations may be off, so be conservative.
1750 // FIXME: We could add logic to be more precise about negative offsets
1751 // and which instructions will need a scratch register for them. Is it
1752 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001753 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001754 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001755
1756 // Determine biggest (positive) SP offset in MachineFrameInfo.
1757 int MaxFixedOffset = 0;
1758 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1759 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1760 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1761 }
1762
Matthias Braun44047422017-04-05 16:58:41 +00001763 bool HasFP = hasFP(MF);
1764 if (HasFP) {
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001765 if (AFI->hasStackFrame())
1766 EstimatedStackSize += 4;
1767 } else {
1768 // If FP is not used, SP will be used to access arguments, so count the
1769 // size of arguments into the estimation.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001770 EstimatedStackSize += MaxFixedOffset;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001771 }
1772 EstimatedStackSize += 16; // For possible paddings.
1773
Matthias Braun8aaa3682017-04-19 21:11:44 +00001774 unsigned EstimatedRSStackSizeLimit = estimateRSStackSizeLimit(MF, this);
Matthias Braunf1caa282017-12-15 22:22:58 +00001775 int MaxFPOffset = getMaxFPOffset(MF.getFunction(), *AFI);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001776 bool BigFrameOffsets = EstimatedStackSize >= EstimatedRSStackSizeLimit ||
1777 MFI.hasVarSizedObjects() ||
1778 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)) ||
1779 // For large argument stacks fp relative addressed may overflow.
1780 (HasFP && (MaxFixedOffset - MaxFPOffset) >= (int)EstimatedRSStackSizeLimit);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001781 if (BigFrameOffsets ||
1782 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001783 AFI->setHasStackFrame(true);
1784
Matthias Braun44047422017-04-05 16:58:41 +00001785 if (HasFP) {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001786 SavedRegs.set(FramePtr);
1787 // If the frame pointer is required by the ABI, also spill LR so that we
1788 // emit a complete frame record.
1789 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1790 SavedRegs.set(ARM::LR);
1791 LRSpilled = true;
1792 NumGPRSpills++;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001793 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001794 if (LRPos != UnspilledCS1GPRs.end())
1795 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001796 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001797 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001798 if (FPPos != UnspilledCS1GPRs.end())
1799 UnspilledCS1GPRs.erase(FPPos);
1800 NumGPRSpills++;
1801 if (FramePtr == ARM::R7)
1802 CS1Spilled = true;
1803 }
1804
Matthias Braunc618a462017-07-28 01:36:32 +00001805 // This is true when we inserted a spill for an unused register that can now
1806 // be used for register scavenging.
1807 bool ExtraCSSpill = false;
1808
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001809 if (AFI->isThumb1OnlyFunction()) {
1810 // For Thumb1-only targets, we need some low registers when we save and
1811 // restore the high registers (which aren't allocatable, but could be
1812 // used by inline assembly) because the push/pop instructions can not
1813 // access high registers. If necessary, we might need to push more low
1814 // registers to ensure that there is at least one free that can be used
1815 // for the saving & restoring, and preferably we should ensure that as
1816 // many as are needed are available so that fewer push/pop instructions
1817 // are required.
1818
1819 // Low registers which are not currently pushed, but could be (r4-r7).
1820 SmallVector<unsigned, 4> AvailableRegs;
1821
1822 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1823 // free.
1824 int EntryRegDeficit = 0;
1825 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1826 if (!MF.getRegInfo().isLiveIn(Reg)) {
1827 --EntryRegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001828 LLVM_DEBUG(dbgs()
1829 << printReg(Reg, TRI)
1830 << " is unused argument register, EntryRegDeficit = "
1831 << EntryRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001832 }
1833 }
1834
1835 // Unused return registers can be clobbered in the epilogue for free.
1836 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001837 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
1838 << " return regs used, ExitRegDeficit = "
1839 << ExitRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001840
1841 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001842 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001843
1844 // r4-r6 can be used in the prologue if they are pushed by the first push
1845 // instruction.
1846 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1847 if (SavedRegs.test(Reg)) {
1848 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001849 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1850 << " is saved low register, RegDeficit = "
1851 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001852 } else {
1853 AvailableRegs.push_back(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001854 LLVM_DEBUG(
1855 dbgs()
1856 << printReg(Reg, TRI)
1857 << " is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001858 }
1859 }
1860
1861 // r7 can be used if it is not being used as the frame pointer.
Matthias Braun44047422017-04-05 16:58:41 +00001862 if (!HasFP) {
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001863 if (SavedRegs.test(ARM::R7)) {
1864 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001865 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
1866 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001867 } else {
1868 AvailableRegs.push_back(ARM::R7);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001869 LLVM_DEBUG(
1870 dbgs()
1871 << "%r7 is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001872 }
1873 }
1874
1875 // Each of r8-r11 needs to be copied to a low register, then pushed.
1876 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1877 if (SavedRegs.test(Reg)) {
1878 ++RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001879 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1880 << " is saved high register, RegDeficit = "
1881 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001882 }
1883 }
1884
1885 // LR can only be used by PUSH, not POP, and can't be used at all if the
1886 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1887 // are more limited at function entry than exit.
1888 if ((EntryRegDeficit > ExitRegDeficit) &&
1889 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1890 MF.getFrameInfo().isReturnAddressTaken())) {
1891 if (SavedRegs.test(ARM::LR)) {
1892 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001893 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
1894 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001895 } else {
1896 AvailableRegs.push_back(ARM::LR);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001897 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001898 }
1899 }
1900
1901 // If there are more high registers that need pushing than low registers
1902 // available, push some more low registers so that we can use fewer push
1903 // instructions. This might not reduce RegDeficit all the way to zero,
1904 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1905 // need saving.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001906 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001907 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1908 unsigned Reg = AvailableRegs.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001909 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1910 << " to make up reg deficit\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001911 SavedRegs.set(Reg);
1912 NumGPRSpills++;
1913 CS1Spilled = true;
Matthias Braunc618a462017-07-28 01:36:32 +00001914 assert(!MRI.isReserved(Reg) && "Should not be reserved");
1915 if (!MRI.isPhysRegUsed(Reg))
1916 ExtraCSSpill = true;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001917 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001918 if (Reg == ARM::LR)
1919 LRSpilled = true;
1920 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001921 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
1922 << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001923 }
1924
Eli Friedman5b45a392018-08-08 20:03:10 +00001925 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
1926 // restore LR in that case.
1927 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
1928
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001929 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1930 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
Eli Friedman5b45a392018-08-08 20:03:10 +00001931 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
Matthias Braun02564862015-07-14 17:17:13 +00001932 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001933 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001934 SmallVectorImpl<unsigned>::iterator LRPos;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001935 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00001936 if (LRPos != UnspilledCS1GPRs.end())
1937 UnspilledCS1GPRs.erase(LRPos);
1938
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001939 ForceLRSpill = false;
Matthias Braunc618a462017-07-28 01:36:32 +00001940 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR))
1941 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001942 }
1943
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001944 // If stack and double are 8-byte aligned and we are spilling an odd number
1945 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1946 // the integer and double callee save areas.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001947 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001948 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001949 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001950 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1951 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1952 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001953 // Don't spill high register if the function is thumb. In the case of
1954 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001955 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001956 (STI.isTargetWindows() && Reg == ARM::R11) ||
Eli Friedman5b45a392018-08-08 20:03:10 +00001957 isARMLowRegister(Reg) ||
1958 (Reg == ARM::LR && !ExpensiveLRRestore)) {
Matthias Braun02564862015-07-14 17:17:13 +00001959 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001960 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1961 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001962 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001963 ExtraCSSpill = true;
1964 break;
1965 }
1966 }
1967 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1968 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001969 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001970 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1971 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001972 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001973 ExtraCSSpill = true;
1974 }
1975 }
1976
1977 // Estimate if we might need to scavenge a register at some point in order
1978 // to materialize a stack offset. If so, either spill one additional
1979 // callee-saved register or reserve a special spill slot to facilitate
1980 // register scavenging. Thumb1 needs a spill slot for stack pointer
1981 // adjustments also, even when the frame itself is small.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001982 if (BigFrameOffsets && !ExtraCSSpill) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001983 // If any non-reserved CS register isn't spilled, just spill one or two
1984 // extra. That should take care of it!
1985 unsigned NumExtras = TargetAlign / 4;
1986 SmallVector<unsigned, 2> Extras;
1987 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1988 unsigned Reg = UnspilledCS1GPRs.back();
1989 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001990 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001991 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1992 Reg == ARM::LR)) {
1993 Extras.push_back(Reg);
1994 NumExtras--;
1995 }
1996 }
1997 // For non-Thumb1 functions, also check for hi-reg CS registers
1998 if (!AFI->isThumb1OnlyFunction()) {
1999 while (NumExtras && !UnspilledCS2GPRs.empty()) {
2000 unsigned Reg = UnspilledCS2GPRs.back();
2001 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00002002 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002003 Extras.push_back(Reg);
2004 NumExtras--;
2005 }
2006 }
2007 }
Matthias Braunc618a462017-07-28 01:36:32 +00002008 if (NumExtras == 0) {
2009 for (unsigned Reg : Extras) {
2010 SavedRegs.set(Reg);
2011 if (!MRI.isPhysRegUsed(Reg))
2012 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002013 }
Matthias Braunc618a462017-07-28 01:36:32 +00002014 }
2015 if (!ExtraCSSpill && !AFI->isThumb1OnlyFunction()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002016 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
2017 // closest to SP or frame pointer.
Weiming Zhao5b5501e2016-05-08 05:11:54 +00002018 assert(RS && "Register scavenging not provided");
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00002019 const TargetRegisterClass &RC = ARM::GPRRegClass;
2020 unsigned Size = TRI->getSpillSize(RC);
2021 unsigned Align = TRI->getSpillAlignment(RC);
2022 RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002023 }
2024 }
2025 }
2026
2027 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00002028 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002029 AFI->setLRIsSpilledForFarJump(true);
2030 }
2031}
Eli Bendersky8da87162013-02-21 20:05:00 +00002032
Hans Wennborge1a2e902016-03-31 18:33:38 +00002033MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
2034 MachineFunction &MF, MachineBasicBlock &MBB,
2035 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00002036 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002037 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00002038 if (!hasReservedCallFrame(MF)) {
2039 // If we have alloca, convert as follows:
2040 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2041 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002042 MachineInstr &Old = *I;
2043 DebugLoc dl = Old.getDebugLoc();
Serge Pavlov5943a962017-04-19 03:12:05 +00002044 unsigned Amount = TII.getFrameSize(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002045 if (Amount != 0) {
2046 // We need to keep the stack aligned properly. To do this, we round the
2047 // amount of space needed for the outgoing arguments up to the next
2048 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00002049 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00002050
2051 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2052 assert(!AFI->isThumb1OnlyFunction() &&
2053 "This eliminateCallFramePseudoInstr does not support Thumb1!");
2054 bool isARM = !AFI->isThumbFunction();
2055
2056 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002057 unsigned Opc = Old.getOpcode();
2058 int PIdx = Old.findFirstPredOperandIdx();
2059 ARMCC::CondCodes Pred =
2060 (PIdx == -1) ? ARMCC::AL
2061 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Serge Pavlov5943a962017-04-19 03:12:05 +00002062 unsigned PredReg = TII.getFramePred(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002063 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
Eli Bendersky8da87162013-02-21 20:05:00 +00002064 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2065 Pred, PredReg);
2066 } else {
Eli Bendersky8da87162013-02-21 20:05:00 +00002067 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2068 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2069 Pred, PredReg);
2070 }
2071 }
2072 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00002073 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00002074}
2075
Oliver Stannardb14c6252014-04-02 16:10:33 +00002076/// Get the minimum constant for ARM that is greater than or equal to the
2077/// argument. In ARM, constants can have any value that can be produced by
2078/// rotating an 8-bit value to the right by an even number of bits within a
2079/// 32-bit word.
2080static uint32_t alignToARMConstant(uint32_t Value) {
2081 unsigned Shifted = 0;
2082
2083 if (Value == 0)
2084 return 0;
2085
2086 while (!(Value & 0xC0000000)) {
2087 Value = Value << 2;
2088 Shifted += 2;
2089 }
2090
2091 bool Carry = (Value & 0x00FFFFFF);
2092 Value = ((Value & 0xFF000000) >> 24) + Carry;
2093
2094 if (Value & 0x0000100)
2095 Value = Value & 0x000001FC;
2096
2097 if (Shifted > 24)
2098 Value = Value >> (Shifted - 24);
2099 else
2100 Value = Value << (24 - Shifted);
2101
2102 return Value;
2103}
2104
2105// The stack limit in the TCB is set to this many bytes above the actual
2106// stack limit.
2107static const uint64_t kSplitStackAvailable = 256;
2108
2109// Adjust the function prologue to enable split stacks. This currently only
2110// supports android and linux.
2111//
2112// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2113// must be well defined in order to allow for consistent implementations of the
2114// __morestack helper function. The ABI is also not a normal ABI in that it
2115// doesn't follow the normal calling conventions because this allows the
2116// prologue of each function to be optimized further.
2117//
2118// Currently, the ABI looks like (when calling __morestack)
2119//
2120// * r4 holds the minimum stack size requested for this function call
2121// * r5 holds the stack size of the arguments to the function
2122// * the beginning of the function is 3 instructions after the call to
2123// __morestack
2124//
2125// Implementations of __morestack should use r4 to allocate a new stack, r5 to
2126// place the arguments on to the new stack, and the 3-instruction knowledge to
2127// jump directly to the body of the function when working on the new stack.
2128//
2129// An old (and possibly no longer compatible) implementation of __morestack for
2130// ARM can be found at [1].
2131//
2132// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00002133void ARMFrameLowering::adjustForSegmentedStacks(
2134 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00002135 unsigned Opcode;
2136 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00002137 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002138 bool Thumb = ST->isThumb();
2139
2140 // Sadly, this currently doesn't support varargs, platforms other than
2141 // android/linux. Note that thumb1/thumb2 are support for android/linux.
Matthias Braunf1caa282017-12-15 22:22:58 +00002142 if (MF.getFunction().isVarArg())
Oliver Stannardb14c6252014-04-02 16:10:33 +00002143 report_fatal_error("Segmented stacks do not support vararg functions.");
2144 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00002145 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00002146
Matthias Braun941a7052016-07-28 18:40:00 +00002147 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002148 MachineModuleInfo &MMI = MF.getMMI();
2149 MCContext &Context = MMI.getContext();
2150 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2151 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002152 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002153 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2154 DebugLoc DL;
2155
Matthias Braun941a7052016-07-28 18:40:00 +00002156 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002157
Than McIntosh31909932018-06-26 14:11:30 +00002158 // Do not generate a prologue for leaf functions with a stack of size zero.
2159 // For non-leaf functions we have to allow for the possibility that the
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002160 // callis to a non-split function, as in PR37807. This function could also
2161 // take the address of a non-split function. When the linker tries to adjust
2162 // its non-existent prologue, it would fail with an error. Mark the object
2163 // file so that such failures are not errors. See this Go language bug-report
2164 // https://go-review.googlesource.com/c/go/+/148819/
2165 if (StackSize == 0 && !MFI.hasTailCall()) {
2166 MF.getMMI().setHasNosplitStack(true);
Tim Northoverf9e798b2014-05-22 13:03:43 +00002167 return;
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002168 }
Tim Northoverf9e798b2014-05-22 13:03:43 +00002169
Oliver Stannardb14c6252014-04-02 16:10:33 +00002170 // Use R4 and R5 as scratch registers.
2171 // We save R4 and R5 before use and restore them before leaving the function.
2172 unsigned ScratchReg0 = ARM::R4;
2173 unsigned ScratchReg1 = ARM::R5;
2174 uint64_t AlignedStackSize;
2175
2176 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2177 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2178 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2179 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2180 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2181
Quentin Colombet71a71482015-07-20 21:42:14 +00002182 // Grab everything that reaches PrologueMBB to update there liveness as well.
2183 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2184 SmallVector<MachineBasicBlock *, 2> WalkList;
2185 WalkList.push_back(&PrologueMBB);
2186
2187 do {
2188 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2189 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2190 if (BeforePrologueRegion.insert(PredBB).second)
2191 WalkList.push_back(PredBB);
2192 }
2193 } while (!WalkList.empty());
2194
2195 // The order in that list is important.
2196 // The blocks will all be inserted before PrologueMBB using that order.
2197 // Therefore the block that should appear first in the CFG should appear
2198 // first in the list.
2199 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2200 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002201
Craig Topper80720812015-12-01 06:13:01 +00002202 for (MachineBasicBlock *B : AddedBlocks)
2203 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002204
Matthias Braund9da1622015-09-09 18:08:03 +00002205 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002206 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002207 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002208 }
2209
Quentin Colombet71a71482015-07-20 21:42:14 +00002210 // Remove the newly added blocks from the list, since we know
2211 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002212 for (MachineBasicBlock *B : AddedBlocks) {
2213 BeforePrologueRegion.erase(B);
2214 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002215 }
2216
2217 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2218 // Make sure the LiveIns are still sorted and unique.
2219 MBB->sortUniqueLiveIns();
2220 // Replace the edges to PrologueMBB by edges to the sequences
2221 // we are about to add.
2222 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2223 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002224
2225 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002226 AlignedStackSize = alignToARMConstant(StackSize);
2227
2228 // When the frame size is less than 256 we just compare the stack
2229 // boundary directly to the value of the stack pointer, per gcc.
2230 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2231
2232 // We will use two of the callee save registers as scratch registers so we
2233 // need to save those registers onto the stack.
2234 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2235 // requested and arguments for __morestack().
2236 // SR0: Scratch Register #0
2237 // SR1: Scratch Register #1
2238 // push {SR0, SR1}
2239 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002240 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2241 .add(predOps(ARMCC::AL))
2242 .addReg(ScratchReg0)
2243 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002244 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002245 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2246 .addReg(ARM::SP, RegState::Define)
2247 .addReg(ARM::SP)
2248 .add(predOps(ARMCC::AL))
2249 .addReg(ScratchReg0)
2250 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002251 }
2252
2253 // Emit the relevant DWARF information about the change in stack pointer as
2254 // well as where to find both r4 and r5 (the callee-save registers)
2255 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002256 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002257 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2258 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002259 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002260 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2261 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2262 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002263 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002264 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2265 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2266 .addCFIIndex(CFIIndex);
2267
2268 // mov SR1, sp
2269 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002270 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2271 .addReg(ARM::SP)
2272 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002273 } else if (CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002274 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2275 .addReg(ARM::SP)
2276 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002277 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002278 }
2279
2280 // sub SR1, sp, #StackSize
2281 if (!CompareStackPointer && Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002282 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2283 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002284 .addReg(ScratchReg1)
2285 .addImm(AlignedStackSize)
2286 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002287 } else if (!CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002288 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2289 .addReg(ARM::SP)
2290 .addImm(AlignedStackSize)
2291 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002292 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002293 }
2294
2295 if (Thumb && ST->isThumb1Only()) {
2296 unsigned PCLabelId = ARMFI->createPICLabelUId();
2297 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Matthias Braunf1caa282017-12-15 22:22:58 +00002298 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002299 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002300 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002301
2302 // ldr SR0, [pc, offset(STACK_LIMIT)]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002303 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2304 .addConstantPoolIndex(CPI)
2305 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002306
2307 // ldr SR0, [SR0]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002308 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2309 .addReg(ScratchReg0)
2310 .addImm(0)
2311 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002312 } else {
2313 // Get TLS base address from the coprocessor
2314 // mrc p15, #0, SR0, c13, c0, #3
Diana Picus4f8c3e12017-01-13 09:37:56 +00002315 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2316 .addImm(15)
2317 .addImm(0)
2318 .addImm(13)
2319 .addImm(0)
2320 .addImm(3)
2321 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002322
2323 // Use the last tls slot on android and a private field of the TCP on linux.
2324 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2325 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2326
2327 // Get the stack limit from the right offset
2328 // ldr SR0, [sr0, #4 * TlsOffset]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002329 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2330 .addReg(ScratchReg0)
2331 .addImm(4 * TlsOffset)
2332 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002333 }
2334
2335 // Compare stack limit with stack size requested.
2336 // cmp SR0, SR1
2337 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002338 BuildMI(GetMBB, DL, TII.get(Opcode))
2339 .addReg(ScratchReg0)
2340 .addReg(ScratchReg1)
2341 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002342
2343 // This jump is taken if StackLimit < SP - stack required.
2344 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2345 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2346 .addImm(ARMCC::LO)
2347 .addReg(ARM::CPSR);
2348
2349
2350 // Calling __morestack(StackSize, Size of stack arguments).
2351 // __morestack knows that the stack size requested is in SR0(r4)
2352 // and amount size of stack arguments is in SR1(r5).
2353
2354 // Pass first argument for the __morestack by Scratch Register #0.
2355 // The amount size of stack required
2356 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002357 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2358 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002359 .addImm(AlignedStackSize)
2360 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002361 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002362 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2363 .addImm(AlignedStackSize)
2364 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002365 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002366 }
2367 // Pass second argument for the __morestack by Scratch Register #1.
2368 // The amount size of stack consumed to save function arguments.
2369 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002370 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2371 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002372 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2373 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002374 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002375 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2376 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2377 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002378 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002379 }
2380
2381 // push {lr} - Save return address of this function.
2382 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002383 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2384 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002385 .addReg(ARM::LR);
2386 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002387 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2388 .addReg(ARM::SP, RegState::Define)
2389 .addReg(ARM::SP)
2390 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002391 .addReg(ARM::LR);
2392 }
2393
2394 // Emit the DWARF info about the change in stack as well as where to find the
2395 // previous link register
2396 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002397 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002398 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2399 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002400 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002401 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2402 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2403 .addCFIIndex(CFIIndex);
2404
2405 // Call __morestack().
2406 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002407 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2408 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002409 .addExternalSymbol("__morestack");
2410 } else {
2411 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2412 .addExternalSymbol("__morestack");
2413 }
2414
2415 // pop {lr} - Restore return address of this original function.
2416 if (Thumb) {
2417 if (ST->isThumb1Only()) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002418 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2419 .add(predOps(ARMCC::AL))
2420 .addReg(ScratchReg0);
2421 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2422 .addReg(ScratchReg0)
2423 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002424 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002425 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2426 .addReg(ARM::LR, RegState::Define)
2427 .addReg(ARM::SP, RegState::Define)
2428 .addReg(ARM::SP)
2429 .addImm(4)
2430 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002431 }
2432 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002433 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2434 .addReg(ARM::SP, RegState::Define)
2435 .addReg(ARM::SP)
2436 .add(predOps(ARMCC::AL))
2437 .addReg(ARM::LR);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002438 }
2439
2440 // Restore SR0 and SR1 in case of __morestack() was called.
2441 // __morestack() will skip PostStackMBB block so we need to restore
2442 // scratch registers from here.
2443 // pop {SR0, SR1}
2444 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002445 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2446 .add(predOps(ARMCC::AL))
2447 .addReg(ScratchReg0)
2448 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002449 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002450 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2451 .addReg(ARM::SP, RegState::Define)
2452 .addReg(ARM::SP)
2453 .add(predOps(ARMCC::AL))
2454 .addReg(ScratchReg0)
2455 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002456 }
2457
2458 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002459 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002460 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2461 .addCFIIndex(CFIIndex);
2462
Joerg Sonnenberger0f76a352017-08-28 20:20:47 +00002463 // Return from this function.
2464 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002465
2466 // Restore SR0 and SR1 in case of __morestack() was not called.
2467 // pop {SR0, SR1}
2468 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002469 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2470 .add(predOps(ARMCC::AL))
2471 .addReg(ScratchReg0)
2472 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002473 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002474 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2475 .addReg(ARM::SP, RegState::Define)
2476 .addReg(ARM::SP)
2477 .add(predOps(ARMCC::AL))
2478 .addReg(ScratchReg0)
2479 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002480 }
2481
2482 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002483 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002484 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2485 .addCFIIndex(CFIIndex);
2486
2487 // Tell debuggers that r4 and r5 are now the same as they were in the
2488 // previous function, that they're the "Same Value".
Matthias Braunf23ef432016-11-30 23:48:42 +00002489 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002490 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2491 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2492 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002493 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002494 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2495 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2496 .addCFIIndex(CFIIndex);
2497
2498 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002499 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002500
2501 AllocMBB->addSuccessor(PostStackMBB);
2502
2503 GetMBB->addSuccessor(PostStackMBB);
2504 GetMBB->addSuccessor(AllocMBB);
2505
2506 McrMBB->addSuccessor(GetMBB);
2507
2508 PrevStackMBB->addSuccessor(McrMBB);
2509
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002510#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002511 MF.verify();
2512#endif
2513}