1*0b57cec5SDimitry Andric //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains the PPC implementation of TargetFrameLowering class.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "PPCFrameLowering.h"
1481ad6265SDimitry Andric #include "MCTargetDesc/PPCPredicates.h"
15*0b57cec5SDimitry Andric #include "PPCInstrBuilder.h"
16*0b57cec5SDimitry Andric #include "PPCInstrInfo.h"
17*0b57cec5SDimitry Andric #include "PPCMachineFunctionInfo.h"
18*0b57cec5SDimitry Andric #include "PPCSubtarget.h"
19*0b57cec5SDimitry Andric #include "PPCTargetMachine.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
2181ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
22*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
23*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
24*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
25*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
27*0b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
29*0b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
30*0b57cec5SDimitry Andric 
31*0b57cec5SDimitry Andric using namespace llvm;
32*0b57cec5SDimitry Andric 
33*0b57cec5SDimitry Andric #define DEBUG_TYPE "framelowering"
34*0b57cec5SDimitry Andric STATISTIC(NumPESpillVSR, "Number of spills to vector in prologue");
35*0b57cec5SDimitry Andric STATISTIC(NumPEReloadVSR, "Number of reloads from vector in epilogue");
365ffd83dbSDimitry Andric STATISTIC(NumPrologProbed, "Number of prologues probed");
37*0b57cec5SDimitry Andric 
38*0b57cec5SDimitry Andric static cl::opt<bool>
39*0b57cec5SDimitry Andric EnablePEVectorSpills("ppc-enable-pe-vector-spills",
40*0b57cec5SDimitry Andric                      cl::desc("Enable spills in prologue to vector registers."),
41*0b57cec5SDimitry Andric                      cl::init(false), cl::Hidden);
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
445ffd83dbSDimitry Andric   if (STI.isAIXABI())
45*0b57cec5SDimitry Andric     return STI.isPPC64() ? 16 : 8;
46*0b57cec5SDimitry Andric   // SVR4 ABI:
47*0b57cec5SDimitry Andric   return STI.isPPC64() ? 16 : 4;
48*0b57cec5SDimitry Andric }
49*0b57cec5SDimitry Andric 
50*0b57cec5SDimitry Andric static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
518bcb0991SDimitry Andric   if (STI.isAIXABI())
528bcb0991SDimitry Andric     return STI.isPPC64() ? 40 : 20;
53*0b57cec5SDimitry Andric   return STI.isELFv2ABI() ? 24 : 40;
54*0b57cec5SDimitry Andric }
55*0b57cec5SDimitry Andric 
56*0b57cec5SDimitry Andric static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
575ffd83dbSDimitry Andric   // First slot in the general register save area.
58*0b57cec5SDimitry Andric   return STI.isPPC64() ? -8U : -4U;
59*0b57cec5SDimitry Andric }
60*0b57cec5SDimitry Andric 
61*0b57cec5SDimitry Andric static unsigned computeLinkageSize(const PPCSubtarget &STI) {
625ffd83dbSDimitry Andric   if (STI.isAIXABI() || STI.isPPC64())
63*0b57cec5SDimitry Andric     return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
64*0b57cec5SDimitry Andric 
65*0b57cec5SDimitry Andric   // 32-bit SVR4 ABI:
66*0b57cec5SDimitry Andric   return 8;
67*0b57cec5SDimitry Andric }
68*0b57cec5SDimitry Andric 
69*0b57cec5SDimitry Andric static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
705ffd83dbSDimitry Andric   // Third slot in the general purpose register save area.
715ffd83dbSDimitry Andric   if (STI.is32BitELFABI() && STI.getTargetMachine().isPositionIndependent())
725ffd83dbSDimitry Andric     return -12U;
73*0b57cec5SDimitry Andric 
745ffd83dbSDimitry Andric   // Second slot in the general purpose register save area.
755ffd83dbSDimitry Andric   return STI.isPPC64() ? -16U : -8U;
76*0b57cec5SDimitry Andric }
77*0b57cec5SDimitry Andric 
785ffd83dbSDimitry Andric static unsigned computeCRSaveOffset(const PPCSubtarget &STI) {
795ffd83dbSDimitry Andric   return (STI.isAIXABI() && !STI.isPPC64()) ? 4 : 8;
808bcb0991SDimitry Andric }
818bcb0991SDimitry Andric 
82*0b57cec5SDimitry Andric PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
83*0b57cec5SDimitry Andric     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
84*0b57cec5SDimitry Andric                           STI.getPlatformStackAlignment(), 0),
85*0b57cec5SDimitry Andric       Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
86*0b57cec5SDimitry Andric       TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
87*0b57cec5SDimitry Andric       FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
88*0b57cec5SDimitry Andric       LinkageSize(computeLinkageSize(Subtarget)),
898bcb0991SDimitry Andric       BasePointerSaveOffset(computeBasePointerSaveOffset(Subtarget)),
905ffd83dbSDimitry Andric       CRSaveOffset(computeCRSaveOffset(Subtarget)) {}
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
93*0b57cec5SDimitry Andric const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
94*0b57cec5SDimitry Andric     unsigned &NumEntries) const {
95*0b57cec5SDimitry Andric 
965ffd83dbSDimitry Andric // Floating-point register save area offsets.
975ffd83dbSDimitry Andric #define CALLEE_SAVED_FPRS \
985ffd83dbSDimitry Andric       {PPC::F31, -8},     \
995ffd83dbSDimitry Andric       {PPC::F30, -16},    \
1005ffd83dbSDimitry Andric       {PPC::F29, -24},    \
1015ffd83dbSDimitry Andric       {PPC::F28, -32},    \
1025ffd83dbSDimitry Andric       {PPC::F27, -40},    \
1035ffd83dbSDimitry Andric       {PPC::F26, -48},    \
1045ffd83dbSDimitry Andric       {PPC::F25, -56},    \
1055ffd83dbSDimitry Andric       {PPC::F24, -64},    \
1065ffd83dbSDimitry Andric       {PPC::F23, -72},    \
1075ffd83dbSDimitry Andric       {PPC::F22, -80},    \
1085ffd83dbSDimitry Andric       {PPC::F21, -88},    \
1095ffd83dbSDimitry Andric       {PPC::F20, -96},    \
1105ffd83dbSDimitry Andric       {PPC::F19, -104},   \
1115ffd83dbSDimitry Andric       {PPC::F18, -112},   \
1125ffd83dbSDimitry Andric       {PPC::F17, -120},   \
1135ffd83dbSDimitry Andric       {PPC::F16, -128},   \
1145ffd83dbSDimitry Andric       {PPC::F15, -136},   \
1155ffd83dbSDimitry Andric       {PPC::F14, -144}
1165ffd83dbSDimitry Andric 
1175ffd83dbSDimitry Andric // 32-bit general purpose register save area offsets shared by ELF and
1185ffd83dbSDimitry Andric // AIX. AIX has an extra CSR with r13.
1195ffd83dbSDimitry Andric #define CALLEE_SAVED_GPRS32 \
1205ffd83dbSDimitry Andric       {PPC::R31, -4},       \
1215ffd83dbSDimitry Andric       {PPC::R30, -8},       \
1225ffd83dbSDimitry Andric       {PPC::R29, -12},      \
1235ffd83dbSDimitry Andric       {PPC::R28, -16},      \
1245ffd83dbSDimitry Andric       {PPC::R27, -20},      \
1255ffd83dbSDimitry Andric       {PPC::R26, -24},      \
1265ffd83dbSDimitry Andric       {PPC::R25, -28},      \
1275ffd83dbSDimitry Andric       {PPC::R24, -32},      \
1285ffd83dbSDimitry Andric       {PPC::R23, -36},      \
1295ffd83dbSDimitry Andric       {PPC::R22, -40},      \
1305ffd83dbSDimitry Andric       {PPC::R21, -44},      \
1315ffd83dbSDimitry Andric       {PPC::R20, -48},      \
1325ffd83dbSDimitry Andric       {PPC::R19, -52},      \
1335ffd83dbSDimitry Andric       {PPC::R18, -56},      \
1345ffd83dbSDimitry Andric       {PPC::R17, -60},      \
1355ffd83dbSDimitry Andric       {PPC::R16, -64},      \
1365ffd83dbSDimitry Andric       {PPC::R15, -68},      \
1375ffd83dbSDimitry Andric       {PPC::R14, -72}
1385ffd83dbSDimitry Andric 
1395ffd83dbSDimitry Andric // 64-bit general purpose register save area offsets.
1405ffd83dbSDimitry Andric #define CALLEE_SAVED_GPRS64 \
1415ffd83dbSDimitry Andric       {PPC::X31, -8},       \
1425ffd83dbSDimitry Andric       {PPC::X30, -16},      \
1435ffd83dbSDimitry Andric       {PPC::X29, -24},      \
1445ffd83dbSDimitry Andric       {PPC::X28, -32},      \
1455ffd83dbSDimitry Andric       {PPC::X27, -40},      \
1465ffd83dbSDimitry Andric       {PPC::X26, -48},      \
1475ffd83dbSDimitry Andric       {PPC::X25, -56},      \
1485ffd83dbSDimitry Andric       {PPC::X24, -64},      \
1495ffd83dbSDimitry Andric       {PPC::X23, -72},      \
1505ffd83dbSDimitry Andric       {PPC::X22, -80},      \
1515ffd83dbSDimitry Andric       {PPC::X21, -88},      \
1525ffd83dbSDimitry Andric       {PPC::X20, -96},      \
1535ffd83dbSDimitry Andric       {PPC::X19, -104},     \
1545ffd83dbSDimitry Andric       {PPC::X18, -112},     \
1555ffd83dbSDimitry Andric       {PPC::X17, -120},     \
1565ffd83dbSDimitry Andric       {PPC::X16, -128},     \
1575ffd83dbSDimitry Andric       {PPC::X15, -136},     \
1585ffd83dbSDimitry Andric       {PPC::X14, -144}
1595ffd83dbSDimitry Andric 
1605ffd83dbSDimitry Andric // Vector register save area offsets.
1615ffd83dbSDimitry Andric #define CALLEE_SAVED_VRS \
1625ffd83dbSDimitry Andric       {PPC::V31, -16},   \
1635ffd83dbSDimitry Andric       {PPC::V30, -32},   \
1645ffd83dbSDimitry Andric       {PPC::V29, -48},   \
1655ffd83dbSDimitry Andric       {PPC::V28, -64},   \
1665ffd83dbSDimitry Andric       {PPC::V27, -80},   \
1675ffd83dbSDimitry Andric       {PPC::V26, -96},   \
1685ffd83dbSDimitry Andric       {PPC::V25, -112},  \
1695ffd83dbSDimitry Andric       {PPC::V24, -128},  \
1705ffd83dbSDimitry Andric       {PPC::V23, -144},  \
1715ffd83dbSDimitry Andric       {PPC::V22, -160},  \
1725ffd83dbSDimitry Andric       {PPC::V21, -176},  \
1735ffd83dbSDimitry Andric       {PPC::V20, -192}
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric   // Note that the offsets here overlap, but this is fixed up in
176*0b57cec5SDimitry Andric   // processFunctionBeforeFrameFinalized.
177*0b57cec5SDimitry Andric 
1785ffd83dbSDimitry Andric   static const SpillSlot ELFOffsets32[] = {
1795ffd83dbSDimitry Andric       CALLEE_SAVED_FPRS,
1805ffd83dbSDimitry Andric       CALLEE_SAVED_GPRS32,
181*0b57cec5SDimitry Andric 
182*0b57cec5SDimitry Andric       // CR save area offset.  We map each of the nonvolatile CR fields
183*0b57cec5SDimitry Andric       // to the slot for CR2, which is the first of the nonvolatile CR
184*0b57cec5SDimitry Andric       // fields to be assigned, so that we only allocate one save slot.
185*0b57cec5SDimitry Andric       // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
186*0b57cec5SDimitry Andric       {PPC::CR2, -4},
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric       // VRSAVE save area offset.
189*0b57cec5SDimitry Andric       {PPC::VRSAVE, -4},
190*0b57cec5SDimitry Andric 
1915ffd83dbSDimitry Andric       CALLEE_SAVED_VRS,
192*0b57cec5SDimitry Andric 
193*0b57cec5SDimitry Andric       // SPE register save area (overlaps Vector save area).
194*0b57cec5SDimitry Andric       {PPC::S31, -8},
195*0b57cec5SDimitry Andric       {PPC::S30, -16},
196*0b57cec5SDimitry Andric       {PPC::S29, -24},
197*0b57cec5SDimitry Andric       {PPC::S28, -32},
198*0b57cec5SDimitry Andric       {PPC::S27, -40},
199*0b57cec5SDimitry Andric       {PPC::S26, -48},
200*0b57cec5SDimitry Andric       {PPC::S25, -56},
201*0b57cec5SDimitry Andric       {PPC::S24, -64},
202*0b57cec5SDimitry Andric       {PPC::S23, -72},
203*0b57cec5SDimitry Andric       {PPC::S22, -80},
204*0b57cec5SDimitry Andric       {PPC::S21, -88},
205*0b57cec5SDimitry Andric       {PPC::S20, -96},
206*0b57cec5SDimitry Andric       {PPC::S19, -104},
207*0b57cec5SDimitry Andric       {PPC::S18, -112},
208*0b57cec5SDimitry Andric       {PPC::S17, -120},
209*0b57cec5SDimitry Andric       {PPC::S16, -128},
210*0b57cec5SDimitry Andric       {PPC::S15, -136},
211*0b57cec5SDimitry Andric       {PPC::S14, -144}};
212*0b57cec5SDimitry Andric 
2135ffd83dbSDimitry Andric   static const SpillSlot ELFOffsets64[] = {
2145ffd83dbSDimitry Andric       CALLEE_SAVED_FPRS,
2155ffd83dbSDimitry Andric       CALLEE_SAVED_GPRS64,
216*0b57cec5SDimitry Andric 
217*0b57cec5SDimitry Andric       // VRSAVE save area offset.
218*0b57cec5SDimitry Andric       {PPC::VRSAVE, -4},
2195ffd83dbSDimitry Andric       CALLEE_SAVED_VRS
2205ffd83dbSDimitry Andric   };
221*0b57cec5SDimitry Andric 
222e8d8bef9SDimitry Andric   static const SpillSlot AIXOffsets32[] = {CALLEE_SAVED_FPRS,
2235ffd83dbSDimitry Andric                                            CALLEE_SAVED_GPRS32,
2245ffd83dbSDimitry Andric                                            // Add AIX's extra CSR.
2255ffd83dbSDimitry Andric                                            {PPC::R13, -76},
226e8d8bef9SDimitry Andric                                            CALLEE_SAVED_VRS};
2275ffd83dbSDimitry Andric 
2285ffd83dbSDimitry Andric   static const SpillSlot AIXOffsets64[] = {
229e8d8bef9SDimitry Andric       CALLEE_SAVED_FPRS, CALLEE_SAVED_GPRS64, CALLEE_SAVED_VRS};
2305ffd83dbSDimitry Andric 
2315ffd83dbSDimitry Andric   if (Subtarget.is64BitELFABI()) {
232bdd1243dSDimitry Andric     NumEntries = std::size(ELFOffsets64);
2335ffd83dbSDimitry Andric     return ELFOffsets64;
2345ffd83dbSDimitry Andric   }
2355ffd83dbSDimitry Andric 
2365ffd83dbSDimitry Andric   if (Subtarget.is32BitELFABI()) {
237bdd1243dSDimitry Andric     NumEntries = std::size(ELFOffsets32);
2385ffd83dbSDimitry Andric     return ELFOffsets32;
2395ffd83dbSDimitry Andric   }
2405ffd83dbSDimitry Andric 
2415ffd83dbSDimitry Andric   assert(Subtarget.isAIXABI() && "Unexpected ABI.");
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric   if (Subtarget.isPPC64()) {
244bdd1243dSDimitry Andric     NumEntries = std::size(AIXOffsets64);
2455ffd83dbSDimitry Andric     return AIXOffsets64;
246*0b57cec5SDimitry Andric   }
2475ffd83dbSDimitry Andric 
248bdd1243dSDimitry Andric   NumEntries = std::size(AIXOffsets32);
2495ffd83dbSDimitry Andric   return AIXOffsets32;
250*0b57cec5SDimitry Andric }
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric static bool spillsCR(const MachineFunction &MF) {
253*0b57cec5SDimitry Andric   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
254*0b57cec5SDimitry Andric   return FuncInfo->isCRSpilled();
255*0b57cec5SDimitry Andric }
256*0b57cec5SDimitry Andric 
257*0b57cec5SDimitry Andric static bool hasSpills(const MachineFunction &MF) {
258*0b57cec5SDimitry Andric   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
259*0b57cec5SDimitry Andric   return FuncInfo->hasSpills();
260*0b57cec5SDimitry Andric }
261*0b57cec5SDimitry Andric 
262*0b57cec5SDimitry Andric static bool hasNonRISpills(const MachineFunction &MF) {
263*0b57cec5SDimitry Andric   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
264*0b57cec5SDimitry Andric   return FuncInfo->hasNonRISpills();
265*0b57cec5SDimitry Andric }
266*0b57cec5SDimitry Andric 
267*0b57cec5SDimitry Andric /// MustSaveLR - Return true if this function requires that we save the LR
268*0b57cec5SDimitry Andric /// register onto the stack in the prolog and restore it in the epilog of the
269*0b57cec5SDimitry Andric /// function.
270*0b57cec5SDimitry Andric static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
271*0b57cec5SDimitry Andric   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
272*0b57cec5SDimitry Andric 
273*0b57cec5SDimitry Andric   // We need a save/restore of LR if there is any def of LR (which is
274*0b57cec5SDimitry Andric   // defined by calls, including the PIC setup sequence), or if there is
275*0b57cec5SDimitry Andric   // some use of the LR stack slot (e.g. for builtin_return_address).
276*0b57cec5SDimitry Andric   // (LR comes in 32 and 64 bit versions.)
277*0b57cec5SDimitry Andric   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
278*0b57cec5SDimitry Andric   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
279*0b57cec5SDimitry Andric }
280*0b57cec5SDimitry Andric 
281*0b57cec5SDimitry Andric /// determineFrameLayoutAndUpdate - Determine the size of the frame and maximum
282*0b57cec5SDimitry Andric /// call frame size. Update the MachineFunction object with the stack size.
283349cc55cSDimitry Andric uint64_t
284*0b57cec5SDimitry Andric PPCFrameLowering::determineFrameLayoutAndUpdate(MachineFunction &MF,
285*0b57cec5SDimitry Andric                                                 bool UseEstimate) const {
286*0b57cec5SDimitry Andric   unsigned NewMaxCallFrameSize = 0;
287349cc55cSDimitry Andric   uint64_t FrameSize = determineFrameLayout(MF, UseEstimate,
288*0b57cec5SDimitry Andric                                             &NewMaxCallFrameSize);
289*0b57cec5SDimitry Andric   MF.getFrameInfo().setStackSize(FrameSize);
290*0b57cec5SDimitry Andric   MF.getFrameInfo().setMaxCallFrameSize(NewMaxCallFrameSize);
291*0b57cec5SDimitry Andric   return FrameSize;
292*0b57cec5SDimitry Andric }
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric /// determineFrameLayout - Determine the size of the frame and maximum call
295*0b57cec5SDimitry Andric /// frame size.
296349cc55cSDimitry Andric uint64_t
297*0b57cec5SDimitry Andric PPCFrameLowering::determineFrameLayout(const MachineFunction &MF,
298*0b57cec5SDimitry Andric                                        bool UseEstimate,
299*0b57cec5SDimitry Andric                                        unsigned *NewMaxCallFrameSize) const {
300*0b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
301*0b57cec5SDimitry Andric   const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
302*0b57cec5SDimitry Andric 
303*0b57cec5SDimitry Andric   // Get the number of bytes to allocate from the FrameInfo
304349cc55cSDimitry Andric   uint64_t FrameSize =
305*0b57cec5SDimitry Andric     UseEstimate ? MFI.estimateStackSize(MF) : MFI.getStackSize();
306*0b57cec5SDimitry Andric 
307*0b57cec5SDimitry Andric   // Get stack alignments. The frame must be aligned to the greatest of these:
3085ffd83dbSDimitry Andric   Align TargetAlign = getStackAlign(); // alignment required per the ABI
3095ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign();  // algmt required by data in frame
3105ffd83dbSDimitry Andric   Align Alignment = std::max(TargetAlign, MaxAlign);
311*0b57cec5SDimitry Andric 
312*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric   unsigned LR = RegInfo->getRARegister();
315*0b57cec5SDimitry Andric   bool DisableRedZone = MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
316*0b57cec5SDimitry Andric   bool CanUseRedZone = !MFI.hasVarSizedObjects() && // No dynamic alloca.
317*0b57cec5SDimitry Andric                        !MFI.adjustsStack() &&       // No calls.
318*0b57cec5SDimitry Andric                        !MustSaveLR(MF, LR) &&       // No need to save LR.
319*0b57cec5SDimitry Andric                        !FI->mustSaveTOC() &&        // No need to save TOC.
320*0b57cec5SDimitry Andric                        !RegInfo->hasBasePointer(MF); // No special alignment.
321*0b57cec5SDimitry Andric 
322e8d8bef9SDimitry Andric   // Note: for PPC32 SVR4ABI, we can still generate stackless
323*0b57cec5SDimitry Andric   // code if all local vars are reg-allocated.
324*0b57cec5SDimitry Andric   bool FitsInRedZone = FrameSize <= Subtarget.getRedZoneSize();
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   // Check whether we can skip adjusting the stack pointer (by using red zone)
327*0b57cec5SDimitry Andric   if (!DisableRedZone && CanUseRedZone && FitsInRedZone) {
328*0b57cec5SDimitry Andric     // No need for frame
329*0b57cec5SDimitry Andric     return 0;
330*0b57cec5SDimitry Andric   }
331*0b57cec5SDimitry Andric 
332*0b57cec5SDimitry Andric   // Get the maximum call frame size of all the calls.
333*0b57cec5SDimitry Andric   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric   // Maximum call frame needs to be at least big enough for linkage area.
336*0b57cec5SDimitry Andric   unsigned minCallFrameSize = getLinkageSize();
337*0b57cec5SDimitry Andric   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
338*0b57cec5SDimitry Andric 
339*0b57cec5SDimitry Andric   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
340*0b57cec5SDimitry Andric   // that allocations will be aligned.
341*0b57cec5SDimitry Andric   if (MFI.hasVarSizedObjects())
3425ffd83dbSDimitry Andric     maxCallFrameSize = alignTo(maxCallFrameSize, Alignment);
343*0b57cec5SDimitry Andric 
344*0b57cec5SDimitry Andric   // Update the new max call frame size if the caller passes in a valid pointer.
345*0b57cec5SDimitry Andric   if (NewMaxCallFrameSize)
346*0b57cec5SDimitry Andric     *NewMaxCallFrameSize = maxCallFrameSize;
347*0b57cec5SDimitry Andric 
348*0b57cec5SDimitry Andric   // Include call frame size in total.
349*0b57cec5SDimitry Andric   FrameSize += maxCallFrameSize;
350*0b57cec5SDimitry Andric 
351*0b57cec5SDimitry Andric   // Make sure the frame is aligned.
3525ffd83dbSDimitry Andric   FrameSize = alignTo(FrameSize, Alignment);
353*0b57cec5SDimitry Andric 
354*0b57cec5SDimitry Andric   return FrameSize;
355*0b57cec5SDimitry Andric }
356*0b57cec5SDimitry Andric 
357*0b57cec5SDimitry Andric // hasFP - Return true if the specified function actually has a dedicated frame
358*0b57cec5SDimitry Andric // pointer register.
359*0b57cec5SDimitry Andric bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
360*0b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
361*0b57cec5SDimitry Andric   // FIXME: This is pretty much broken by design: hasFP() might be called really
362*0b57cec5SDimitry Andric   // early, before the stack layout was calculated and thus hasFP() might return
363*0b57cec5SDimitry Andric   // true or false here depending on the time of call.
364*0b57cec5SDimitry Andric   return (MFI.getStackSize()) && needsFP(MF);
365*0b57cec5SDimitry Andric }
366*0b57cec5SDimitry Andric 
367*0b57cec5SDimitry Andric // needsFP - Return true if the specified function should have a dedicated frame
368*0b57cec5SDimitry Andric // pointer register.  This is true if the function has variable sized allocas or
369*0b57cec5SDimitry Andric // if frame pointer elimination is disabled.
370*0b57cec5SDimitry Andric bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
371*0b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
372*0b57cec5SDimitry Andric 
373*0b57cec5SDimitry Andric   // Naked functions have no stack frame pushed, so we don't have a frame
374*0b57cec5SDimitry Andric   // pointer.
375*0b57cec5SDimitry Andric   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
376*0b57cec5SDimitry Andric     return false;
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
379*0b57cec5SDimitry Andric          MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint() ||
380e8d8bef9SDimitry Andric          MF.exposesReturnsTwice() ||
381*0b57cec5SDimitry Andric          (MF.getTarget().Options.GuaranteedTailCallOpt &&
382*0b57cec5SDimitry Andric           MF.getInfo<PPCFunctionInfo>()->hasFastCall());
383*0b57cec5SDimitry Andric }
384*0b57cec5SDimitry Andric 
385*0b57cec5SDimitry Andric void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
386*0b57cec5SDimitry Andric   bool is31 = needsFP(MF);
387*0b57cec5SDimitry Andric   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
388*0b57cec5SDimitry Andric   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
389*0b57cec5SDimitry Andric 
390*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
391*0b57cec5SDimitry Andric   bool HasBP = RegInfo->hasBasePointer(MF);
392*0b57cec5SDimitry Andric   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
393*0b57cec5SDimitry Andric   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FP8Reg;
394*0b57cec5SDimitry Andric 
3954824e7fdSDimitry Andric   for (MachineBasicBlock &MBB : MF)
3964824e7fdSDimitry Andric     for (MachineBasicBlock::iterator MBBI = MBB.end(); MBBI != MBB.begin();) {
397*0b57cec5SDimitry Andric       --MBBI;
398*0b57cec5SDimitry Andric       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
399*0b57cec5SDimitry Andric         MachineOperand &MO = MBBI->getOperand(I);
400*0b57cec5SDimitry Andric         if (!MO.isReg())
401*0b57cec5SDimitry Andric           continue;
402*0b57cec5SDimitry Andric 
403*0b57cec5SDimitry Andric         switch (MO.getReg()) {
404*0b57cec5SDimitry Andric         case PPC::FP:
405*0b57cec5SDimitry Andric           MO.setReg(FPReg);
406*0b57cec5SDimitry Andric           break;
407*0b57cec5SDimitry Andric         case PPC::FP8:
408*0b57cec5SDimitry Andric           MO.setReg(FP8Reg);
409*0b57cec5SDimitry Andric           break;
410*0b57cec5SDimitry Andric         case PPC::BP:
411*0b57cec5SDimitry Andric           MO.setReg(BPReg);
412*0b57cec5SDimitry Andric           break;
413*0b57cec5SDimitry Andric         case PPC::BP8:
414*0b57cec5SDimitry Andric           MO.setReg(BP8Reg);
415*0b57cec5SDimitry Andric           break;
416*0b57cec5SDimitry Andric 
417*0b57cec5SDimitry Andric         }
418*0b57cec5SDimitry Andric       }
419*0b57cec5SDimitry Andric     }
420*0b57cec5SDimitry Andric }
421*0b57cec5SDimitry Andric 
422*0b57cec5SDimitry Andric /*  This function will do the following:
423*0b57cec5SDimitry Andric     - If MBB is an entry or exit block, set SR1 and SR2 to R0 and R12
424*0b57cec5SDimitry Andric       respectively (defaults recommended by the ABI) and return true
425*0b57cec5SDimitry Andric     - If MBB is not an entry block, initialize the register scavenger and look
426*0b57cec5SDimitry Andric       for available registers.
427*0b57cec5SDimitry Andric     - If the defaults (R0/R12) are available, return true
428*0b57cec5SDimitry Andric     - If TwoUniqueRegsRequired is set to true, it looks for two unique
429*0b57cec5SDimitry Andric       registers. Otherwise, look for a single available register.
430*0b57cec5SDimitry Andric       - If the required registers are found, set SR1 and SR2 and return true.
431*0b57cec5SDimitry Andric       - If the required registers are not found, set SR2 or both SR1 and SR2 to
432*0b57cec5SDimitry Andric         PPC::NoRegister and return false.
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric     Note that if both SR1 and SR2 are valid parameters and TwoUniqueRegsRequired
435*0b57cec5SDimitry Andric     is not set, this function will attempt to find two different registers, but
436*0b57cec5SDimitry Andric     still return true if only one register is available (and set SR1 == SR2).
437*0b57cec5SDimitry Andric */
438*0b57cec5SDimitry Andric bool
439*0b57cec5SDimitry Andric PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
440*0b57cec5SDimitry Andric                                       bool UseAtEnd,
441*0b57cec5SDimitry Andric                                       bool TwoUniqueRegsRequired,
4425ffd83dbSDimitry Andric                                       Register *SR1,
4435ffd83dbSDimitry Andric                                       Register *SR2) const {
444*0b57cec5SDimitry Andric   RegScavenger RS;
4455ffd83dbSDimitry Andric   Register R0 =  Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
4465ffd83dbSDimitry Andric   Register R12 = Subtarget.isPPC64() ? PPC::X12 : PPC::R12;
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric   // Set the defaults for the two scratch registers.
449*0b57cec5SDimitry Andric   if (SR1)
450*0b57cec5SDimitry Andric     *SR1 = R0;
451*0b57cec5SDimitry Andric 
452*0b57cec5SDimitry Andric   if (SR2) {
453*0b57cec5SDimitry Andric     assert (SR1 && "Asking for the second scratch register but not the first?");
454*0b57cec5SDimitry Andric     *SR2 = R12;
455*0b57cec5SDimitry Andric   }
456*0b57cec5SDimitry Andric 
457*0b57cec5SDimitry Andric   // If MBB is an entry or exit block, use R0 and R12 as the scratch registers.
458*0b57cec5SDimitry Andric   if ((UseAtEnd && MBB->isReturnBlock()) ||
459*0b57cec5SDimitry Andric       (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
460*0b57cec5SDimitry Andric     return true;
461*0b57cec5SDimitry Andric 
462*0b57cec5SDimitry Andric   RS.enterBasicBlock(*MBB);
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric   if (UseAtEnd && !MBB->empty()) {
465*0b57cec5SDimitry Andric     // The scratch register will be used at the end of the block, so must
466*0b57cec5SDimitry Andric     // consider all registers used within the block
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric     MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
469*0b57cec5SDimitry Andric     // If no terminator, back iterator up to previous instruction.
470*0b57cec5SDimitry Andric     if (MBBI == MBB->end())
471*0b57cec5SDimitry Andric       MBBI = std::prev(MBBI);
472*0b57cec5SDimitry Andric 
473*0b57cec5SDimitry Andric     if (MBBI != MBB->begin())
474*0b57cec5SDimitry Andric       RS.forward(MBBI);
475*0b57cec5SDimitry Andric   }
476*0b57cec5SDimitry Andric 
477*0b57cec5SDimitry Andric   // If the two registers are available, we're all good.
478*0b57cec5SDimitry Andric   // Note that we only return here if both R0 and R12 are available because
479*0b57cec5SDimitry Andric   // although the function may not require two unique registers, it may benefit
480*0b57cec5SDimitry Andric   // from having two so we should try to provide them.
481*0b57cec5SDimitry Andric   if (!RS.isRegUsed(R0) && !RS.isRegUsed(R12))
482*0b57cec5SDimitry Andric     return true;
483*0b57cec5SDimitry Andric 
484*0b57cec5SDimitry Andric   // Get the list of callee-saved registers for the target.
485*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
486*0b57cec5SDimitry Andric   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MBB->getParent());
487*0b57cec5SDimitry Andric 
488*0b57cec5SDimitry Andric   // Get all the available registers in the block.
489*0b57cec5SDimitry Andric   BitVector BV = RS.getRegsAvailable(Subtarget.isPPC64() ? &PPC::G8RCRegClass :
490*0b57cec5SDimitry Andric                                      &PPC::GPRCRegClass);
491*0b57cec5SDimitry Andric 
492*0b57cec5SDimitry Andric   // We shouldn't use callee-saved registers as scratch registers as they may be
493*0b57cec5SDimitry Andric   // available when looking for a candidate block for shrink wrapping but not
494*0b57cec5SDimitry Andric   // available when the actual prologue/epilogue is being emitted because they
495*0b57cec5SDimitry Andric   // were added as live-in to the prologue block by PrologueEpilogueInserter.
496*0b57cec5SDimitry Andric   for (int i = 0; CSRegs[i]; ++i)
497*0b57cec5SDimitry Andric     BV.reset(CSRegs[i]);
498*0b57cec5SDimitry Andric 
499*0b57cec5SDimitry Andric   // Set the first scratch register to the first available one.
500*0b57cec5SDimitry Andric   if (SR1) {
501*0b57cec5SDimitry Andric     int FirstScratchReg = BV.find_first();
502*0b57cec5SDimitry Andric     *SR1 = FirstScratchReg == -1 ? (unsigned)PPC::NoRegister : FirstScratchReg;
503*0b57cec5SDimitry Andric   }
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric   // If there is another one available, set the second scratch register to that.
506*0b57cec5SDimitry Andric   // Otherwise, set it to either PPC::NoRegister if this function requires two
507*0b57cec5SDimitry Andric   // or to whatever SR1 is set to if this function doesn't require two.
508*0b57cec5SDimitry Andric   if (SR2) {
509*0b57cec5SDimitry Andric     int SecondScratchReg = BV.find_next(*SR1);
510*0b57cec5SDimitry Andric     if (SecondScratchReg != -1)
511*0b57cec5SDimitry Andric       *SR2 = SecondScratchReg;
512*0b57cec5SDimitry Andric     else
5135ffd83dbSDimitry Andric       *SR2 = TwoUniqueRegsRequired ? Register() : *SR1;
514*0b57cec5SDimitry Andric   }
515*0b57cec5SDimitry Andric 
516*0b57cec5SDimitry Andric   // Now that we've done our best to provide both registers, double check
517*0b57cec5SDimitry Andric   // whether we were unable to provide enough.
518*0b57cec5SDimitry Andric   if (BV.count() < (TwoUniqueRegsRequired ? 2U : 1U))
519*0b57cec5SDimitry Andric     return false;
520*0b57cec5SDimitry Andric 
521*0b57cec5SDimitry Andric   return true;
522*0b57cec5SDimitry Andric }
523*0b57cec5SDimitry Andric 
524*0b57cec5SDimitry Andric // We need a scratch register for spilling LR and for spilling CR. By default,
525*0b57cec5SDimitry Andric // we use two scratch registers to hide latency. However, if only one scratch
526*0b57cec5SDimitry Andric // register is available, we can adjust for that by not overlapping the spill
527*0b57cec5SDimitry Andric // code. However, if we need to realign the stack (i.e. have a base pointer)
528*0b57cec5SDimitry Andric // and the stack frame is large, we need two scratch registers.
529e8d8bef9SDimitry Andric // Also, stack probe requires two scratch registers, one for old sp, one for
530e8d8bef9SDimitry Andric // large frame and large probe size.
531*0b57cec5SDimitry Andric bool
532*0b57cec5SDimitry Andric PPCFrameLowering::twoUniqueScratchRegsRequired(MachineBasicBlock *MBB) const {
533*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
534*0b57cec5SDimitry Andric   MachineFunction &MF = *(MBB->getParent());
535*0b57cec5SDimitry Andric   bool HasBP = RegInfo->hasBasePointer(MF);
536*0b57cec5SDimitry Andric   unsigned FrameSize = determineFrameLayout(MF);
537*0b57cec5SDimitry Andric   int NegFrameSize = -FrameSize;
538*0b57cec5SDimitry Andric   bool IsLargeFrame = !isInt<16>(NegFrameSize);
539*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
5405ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign();
541*0b57cec5SDimitry Andric   bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
542e8d8bef9SDimitry Andric   const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
543*0b57cec5SDimitry Andric 
544e8d8bef9SDimitry Andric   return ((IsLargeFrame || !HasRedZone) && HasBP && MaxAlign > 1) ||
545e8d8bef9SDimitry Andric          TLI.hasInlineStackProbe(MF);
546*0b57cec5SDimitry Andric }
547*0b57cec5SDimitry Andric 
548*0b57cec5SDimitry Andric bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
549*0b57cec5SDimitry Andric   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
550*0b57cec5SDimitry Andric 
551*0b57cec5SDimitry Andric   return findScratchRegister(TmpMBB, false,
552*0b57cec5SDimitry Andric                              twoUniqueScratchRegsRequired(TmpMBB));
553*0b57cec5SDimitry Andric }
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
556*0b57cec5SDimitry Andric   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
557*0b57cec5SDimitry Andric 
558*0b57cec5SDimitry Andric   return findScratchRegister(TmpMBB, true);
559*0b57cec5SDimitry Andric }
560*0b57cec5SDimitry Andric 
561*0b57cec5SDimitry Andric bool PPCFrameLowering::stackUpdateCanBeMoved(MachineFunction &MF) const {
562*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
563*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
564*0b57cec5SDimitry Andric 
565*0b57cec5SDimitry Andric   // Abort if there is no register info or function info.
566*0b57cec5SDimitry Andric   if (!RegInfo || !FI)
567*0b57cec5SDimitry Andric     return false;
568*0b57cec5SDimitry Andric 
569*0b57cec5SDimitry Andric   // Only move the stack update on ELFv2 ABI and PPC64.
570*0b57cec5SDimitry Andric   if (!Subtarget.isELFv2ABI() || !Subtarget.isPPC64())
571*0b57cec5SDimitry Andric     return false;
572*0b57cec5SDimitry Andric 
573*0b57cec5SDimitry Andric   // Check the frame size first and return false if it does not fit the
574*0b57cec5SDimitry Andric   // requirements.
575*0b57cec5SDimitry Andric   // We need a non-zero frame size as well as a frame that will fit in the red
576*0b57cec5SDimitry Andric   // zone. This is because by moving the stack pointer update we are now storing
577*0b57cec5SDimitry Andric   // to the red zone until the stack pointer is updated. If we get an interrupt
578*0b57cec5SDimitry Andric   // inside the prologue but before the stack update we now have a number of
579*0b57cec5SDimitry Andric   // stores to the red zone and those stores must all fit.
580*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
581*0b57cec5SDimitry Andric   unsigned FrameSize = MFI.getStackSize();
582*0b57cec5SDimitry Andric   if (!FrameSize || FrameSize > Subtarget.getRedZoneSize())
583*0b57cec5SDimitry Andric     return false;
584*0b57cec5SDimitry Andric 
585*0b57cec5SDimitry Andric   // Frame pointers and base pointers complicate matters so don't do anything
586*0b57cec5SDimitry Andric   // if we have them. For example having a frame pointer will sometimes require
587*0b57cec5SDimitry Andric   // a copy of r1 into r31 and that makes keeping track of updates to r1 more
588e8d8bef9SDimitry Andric   // difficult. Similar situation exists with setjmp.
589e8d8bef9SDimitry Andric   if (hasFP(MF) || RegInfo->hasBasePointer(MF) || MF.exposesReturnsTwice())
590*0b57cec5SDimitry Andric     return false;
591*0b57cec5SDimitry Andric 
592*0b57cec5SDimitry Andric   // Calls to fast_cc functions use different rules for passing parameters on
593*0b57cec5SDimitry Andric   // the stack from the ABI and using PIC base in the function imposes
594*0b57cec5SDimitry Andric   // similar restrictions to using the base pointer. It is not generally safe
595*0b57cec5SDimitry Andric   // to move the stack pointer update in these situations.
596*0b57cec5SDimitry Andric   if (FI->hasFastCall() || FI->usesPICBase())
597*0b57cec5SDimitry Andric     return false;
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric   // Finally we can move the stack update if we do not require register
600*0b57cec5SDimitry Andric   // scavenging. Register scavenging can introduce more spills and so
601*0b57cec5SDimitry Andric   // may make the frame size larger than we have computed.
602*0b57cec5SDimitry Andric   return !RegInfo->requiresFrameIndexScavenging(MF);
603*0b57cec5SDimitry Andric }
604*0b57cec5SDimitry Andric 
605*0b57cec5SDimitry Andric void PPCFrameLowering::emitPrologue(MachineFunction &MF,
606*0b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
607*0b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
608*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
609*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
610*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
6115ffd83dbSDimitry Andric   const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
612*0b57cec5SDimitry Andric 
613*0b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
614*0b57cec5SDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
615*0b57cec5SDimitry Andric   DebugLoc dl;
6165ffd83dbSDimitry Andric   // AIX assembler does not support cfi directives.
6175ffd83dbSDimitry Andric   const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
618*0b57cec5SDimitry Andric 
619bdd1243dSDimitry Andric   const bool HasFastMFLR = Subtarget.hasFastMFLR();
620bdd1243dSDimitry Andric 
621*0b57cec5SDimitry Andric   // Get processor type.
622*0b57cec5SDimitry Andric   bool isPPC64 = Subtarget.isPPC64();
623*0b57cec5SDimitry Andric   // Get the ABI.
624*0b57cec5SDimitry Andric   bool isSVR4ABI = Subtarget.isSVR4ABI();
625*0b57cec5SDimitry Andric   bool isELFv2ABI = Subtarget.isELFv2ABI();
626e8d8bef9SDimitry Andric   assert((isSVR4ABI || Subtarget.isAIXABI()) && "Unsupported PPC ABI.");
627*0b57cec5SDimitry Andric 
628*0b57cec5SDimitry Andric   // Work out frame sizes.
629349cc55cSDimitry Andric   uint64_t FrameSize = determineFrameLayoutAndUpdate(MF);
630349cc55cSDimitry Andric   int64_t NegFrameSize = -FrameSize;
63181ad6265SDimitry Andric   if (!isPPC64 && (!isInt<32>(FrameSize) || !isInt<32>(NegFrameSize)))
632*0b57cec5SDimitry Andric     llvm_unreachable("Unhandled stack size!");
633*0b57cec5SDimitry Andric 
634*0b57cec5SDimitry Andric   if (MFI.isFrameAddressTaken())
635*0b57cec5SDimitry Andric     replaceFPWithRealFP(MF);
636*0b57cec5SDimitry Andric 
637*0b57cec5SDimitry Andric   // Check if the link register (LR) must be saved.
638*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
639*0b57cec5SDimitry Andric   bool MustSaveLR = FI->mustSaveLR();
640*0b57cec5SDimitry Andric   bool MustSaveTOC = FI->mustSaveTOC();
6415ffd83dbSDimitry Andric   const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
642*0b57cec5SDimitry Andric   bool MustSaveCR = !MustSaveCRs.empty();
643*0b57cec5SDimitry Andric   // Do we have a frame pointer and/or base pointer for this function?
644*0b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
645*0b57cec5SDimitry Andric   bool HasBP = RegInfo->hasBasePointer(MF);
646*0b57cec5SDimitry Andric   bool HasRedZone = isPPC64 || !isSVR4ABI;
647fe6060f1SDimitry Andric   bool HasROPProtect = Subtarget.hasROPProtect();
648fe6060f1SDimitry Andric   bool HasPrivileged = Subtarget.hasPrivileged();
649*0b57cec5SDimitry Andric 
6505ffd83dbSDimitry Andric   Register SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
6518bcb0991SDimitry Andric   Register BPReg = RegInfo->getBaseRegister(MF);
6525ffd83dbSDimitry Andric   Register FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
6535ffd83dbSDimitry Andric   Register LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
6545ffd83dbSDimitry Andric   Register TOCReg      = isPPC64 ? PPC::X2 :  PPC::R2;
6555ffd83dbSDimitry Andric   Register ScratchReg;
6565ffd83dbSDimitry Andric   Register TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
657*0b57cec5SDimitry Andric   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
658*0b57cec5SDimitry Andric   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
659*0b57cec5SDimitry Andric                                                 : PPC::MFLR );
660*0b57cec5SDimitry Andric   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
661*0b57cec5SDimitry Andric                                                  : PPC::STW );
662*0b57cec5SDimitry Andric   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
663*0b57cec5SDimitry Andric                                                      : PPC::STWU );
664*0b57cec5SDimitry Andric   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
665*0b57cec5SDimitry Andric                                                         : PPC::STWUX);
666*0b57cec5SDimitry Andric   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
667*0b57cec5SDimitry Andric                                               : PPC::OR );
668*0b57cec5SDimitry Andric   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
669*0b57cec5SDimitry Andric                                                             : PPC::SUBFC);
670*0b57cec5SDimitry Andric   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
671*0b57cec5SDimitry Andric                                                                : PPC::SUBFIC);
6725ffd83dbSDimitry Andric   const MCInstrDesc &MoveFromCondRegInst = TII.get(isPPC64 ? PPC::MFCR8
6735ffd83dbSDimitry Andric                                                            : PPC::MFCR);
6745ffd83dbSDimitry Andric   const MCInstrDesc &StoreWordInst = TII.get(isPPC64 ? PPC::STW8 : PPC::STW);
675fe6060f1SDimitry Andric   const MCInstrDesc &HashST =
67604eeddc0SDimitry Andric       TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHSTP8 : PPC::HASHST8)
67704eeddc0SDimitry Andric                       : (HasPrivileged ? PPC::HASHSTP : PPC::HASHST));
678*0b57cec5SDimitry Andric 
679*0b57cec5SDimitry Andric   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
680*0b57cec5SDimitry Andric   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
681*0b57cec5SDimitry Andric   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
682*0b57cec5SDimitry Andric   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
683*0b57cec5SDimitry Andric   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
684*0b57cec5SDimitry Andric          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
685*0b57cec5SDimitry Andric 
686*0b57cec5SDimitry Andric   // Using the same bool variable as below to suppress compiler warnings.
6875ffd83dbSDimitry Andric   bool SingleScratchReg = findScratchRegister(
688e8d8bef9SDimitry Andric       &MBB, false, twoUniqueScratchRegsRequired(&MBB), &ScratchReg, &TempReg);
689*0b57cec5SDimitry Andric   assert(SingleScratchReg &&
690*0b57cec5SDimitry Andric          "Required number of registers not available in this block");
691*0b57cec5SDimitry Andric 
692*0b57cec5SDimitry Andric   SingleScratchReg = ScratchReg == TempReg;
693*0b57cec5SDimitry Andric 
694349cc55cSDimitry Andric   int64_t LROffset = getReturnSaveOffset();
695*0b57cec5SDimitry Andric 
696349cc55cSDimitry Andric   int64_t FPOffset = 0;
697*0b57cec5SDimitry Andric   if (HasFP) {
698*0b57cec5SDimitry Andric     MachineFrameInfo &MFI = MF.getFrameInfo();
699*0b57cec5SDimitry Andric     int FPIndex = FI->getFramePointerSaveIndex();
700*0b57cec5SDimitry Andric     assert(FPIndex && "No Frame Pointer Save Slot!");
701*0b57cec5SDimitry Andric     FPOffset = MFI.getObjectOffset(FPIndex);
702*0b57cec5SDimitry Andric   }
703*0b57cec5SDimitry Andric 
704349cc55cSDimitry Andric   int64_t BPOffset = 0;
705*0b57cec5SDimitry Andric   if (HasBP) {
706*0b57cec5SDimitry Andric     MachineFrameInfo &MFI = MF.getFrameInfo();
707*0b57cec5SDimitry Andric     int BPIndex = FI->getBasePointerSaveIndex();
708*0b57cec5SDimitry Andric     assert(BPIndex && "No Base Pointer Save Slot!");
709*0b57cec5SDimitry Andric     BPOffset = MFI.getObjectOffset(BPIndex);
710*0b57cec5SDimitry Andric   }
711*0b57cec5SDimitry Andric 
712349cc55cSDimitry Andric   int64_t PBPOffset = 0;
713*0b57cec5SDimitry Andric   if (FI->usesPICBase()) {
714*0b57cec5SDimitry Andric     MachineFrameInfo &MFI = MF.getFrameInfo();
715*0b57cec5SDimitry Andric     int PBPIndex = FI->getPICBasePointerSaveIndex();
716*0b57cec5SDimitry Andric     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
717*0b57cec5SDimitry Andric     PBPOffset = MFI.getObjectOffset(PBPIndex);
718*0b57cec5SDimitry Andric   }
719*0b57cec5SDimitry Andric 
720*0b57cec5SDimitry Andric   // Get stack alignments.
7215ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign();
722*0b57cec5SDimitry Andric   if (HasBP && MaxAlign > 1)
7235ffd83dbSDimitry Andric     assert(Log2(MaxAlign) < 16 && "Invalid alignment!");
724*0b57cec5SDimitry Andric 
725*0b57cec5SDimitry Andric   // Frames of 32KB & larger require special handling because they cannot be
726*0b57cec5SDimitry Andric   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
727*0b57cec5SDimitry Andric   bool isLargeFrame = !isInt<16>(NegFrameSize);
728*0b57cec5SDimitry Andric 
729*0b57cec5SDimitry Andric   // Check if we can move the stack update instruction (stdu) down the prologue
730*0b57cec5SDimitry Andric   // past the callee saves. Hopefully this will avoid the situation where the
731*0b57cec5SDimitry Andric   // saves are waiting for the update on the store with update to complete.
732*0b57cec5SDimitry Andric   MachineBasicBlock::iterator StackUpdateLoc = MBBI;
733*0b57cec5SDimitry Andric   bool MovingStackUpdateDown = false;
734*0b57cec5SDimitry Andric 
735*0b57cec5SDimitry Andric   // Check if we can move the stack update.
736*0b57cec5SDimitry Andric   if (stackUpdateCanBeMoved(MF)) {
737*0b57cec5SDimitry Andric     const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
738*0b57cec5SDimitry Andric     for (CalleeSavedInfo CSI : Info) {
739fe6060f1SDimitry Andric       // If the callee saved register is spilled to a register instead of the
740fe6060f1SDimitry Andric       // stack then the spill no longer uses the stack pointer.
741fe6060f1SDimitry Andric       // This can lead to two consequences:
742fe6060f1SDimitry Andric       // 1) We no longer need to update the stack because the function does not
743fe6060f1SDimitry Andric       //    spill any callee saved registers to stack.
744fe6060f1SDimitry Andric       // 2) We have a situation where we still have to update the stack pointer
745fe6060f1SDimitry Andric       //    even though some registers are spilled to other registers. In
746fe6060f1SDimitry Andric       //    this case the current code moves the stack update to an incorrect
747fe6060f1SDimitry Andric       //    position.
748fe6060f1SDimitry Andric       // In either case we should abort moving the stack update operation.
749fe6060f1SDimitry Andric       if (CSI.isSpilledToReg()) {
750fe6060f1SDimitry Andric         StackUpdateLoc = MBBI;
751fe6060f1SDimitry Andric         MovingStackUpdateDown = false;
752fe6060f1SDimitry Andric         break;
753fe6060f1SDimitry Andric       }
754fe6060f1SDimitry Andric 
755*0b57cec5SDimitry Andric       int FrIdx = CSI.getFrameIdx();
756*0b57cec5SDimitry Andric       // If the frame index is not negative the callee saved info belongs to a
757*0b57cec5SDimitry Andric       // stack object that is not a fixed stack object. We ignore non-fixed
758*0b57cec5SDimitry Andric       // stack objects because we won't move the stack update pointer past them.
759*0b57cec5SDimitry Andric       if (FrIdx >= 0)
760*0b57cec5SDimitry Andric         continue;
761*0b57cec5SDimitry Andric 
762*0b57cec5SDimitry Andric       if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0) {
763*0b57cec5SDimitry Andric         StackUpdateLoc++;
764*0b57cec5SDimitry Andric         MovingStackUpdateDown = true;
765*0b57cec5SDimitry Andric       } else {
766*0b57cec5SDimitry Andric         // We need all of the Frame Indices to meet these conditions.
767*0b57cec5SDimitry Andric         // If they do not, abort the whole operation.
768*0b57cec5SDimitry Andric         StackUpdateLoc = MBBI;
769*0b57cec5SDimitry Andric         MovingStackUpdateDown = false;
770*0b57cec5SDimitry Andric         break;
771*0b57cec5SDimitry Andric       }
772*0b57cec5SDimitry Andric     }
773*0b57cec5SDimitry Andric 
774*0b57cec5SDimitry Andric     // If the operation was not aborted then update the object offset.
775*0b57cec5SDimitry Andric     if (MovingStackUpdateDown) {
776*0b57cec5SDimitry Andric       for (CalleeSavedInfo CSI : Info) {
777*0b57cec5SDimitry Andric         int FrIdx = CSI.getFrameIdx();
778*0b57cec5SDimitry Andric         if (FrIdx < 0)
779*0b57cec5SDimitry Andric           MFI.setObjectOffset(FrIdx, MFI.getObjectOffset(FrIdx) + NegFrameSize);
780*0b57cec5SDimitry Andric       }
781*0b57cec5SDimitry Andric     }
782*0b57cec5SDimitry Andric   }
783*0b57cec5SDimitry Andric 
7845ffd83dbSDimitry Andric   // Where in the prologue we move the CR fields depends on how many scratch
7855ffd83dbSDimitry Andric   // registers we have, and if we need to save the link register or not. This
7865ffd83dbSDimitry Andric   // lambda is to avoid duplicating the logic in 2 places.
7875ffd83dbSDimitry Andric   auto BuildMoveFromCR = [&]() {
7885ffd83dbSDimitry Andric     if (isELFv2ABI && MustSaveCRs.size() == 1) {
7895ffd83dbSDimitry Andric     // In the ELFv2 ABI, we are not required to save all CR fields.
7905ffd83dbSDimitry Andric     // If only one CR field is clobbered, it is more efficient to use
7915ffd83dbSDimitry Andric     // mfocrf to selectively save just that field, because mfocrf has short
7925ffd83dbSDimitry Andric     // latency compares to mfcr.
7935ffd83dbSDimitry Andric       assert(isPPC64 && "V2 ABI is 64-bit only.");
7945ffd83dbSDimitry Andric       MachineInstrBuilder MIB =
7955ffd83dbSDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::MFOCRF8), TempReg);
7965ffd83dbSDimitry Andric       MIB.addReg(MustSaveCRs[0], RegState::Kill);
7975ffd83dbSDimitry Andric     } else {
7985ffd83dbSDimitry Andric       MachineInstrBuilder MIB =
7995ffd83dbSDimitry Andric           BuildMI(MBB, MBBI, dl, MoveFromCondRegInst, TempReg);
8005ffd83dbSDimitry Andric       for (unsigned CRfield : MustSaveCRs)
8015ffd83dbSDimitry Andric         MIB.addReg(CRfield, RegState::ImplicitKill);
8025ffd83dbSDimitry Andric     }
8035ffd83dbSDimitry Andric   };
8045ffd83dbSDimitry Andric 
805*0b57cec5SDimitry Andric   // If we need to spill the CR and the LR but we don't have two separate
806*0b57cec5SDimitry Andric   // registers available, we must spill them one at a time
807*0b57cec5SDimitry Andric   if (MustSaveCR && SingleScratchReg && MustSaveLR) {
8085ffd83dbSDimitry Andric     BuildMoveFromCR();
8095ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, dl, StoreWordInst)
810*0b57cec5SDimitry Andric         .addReg(TempReg, getKillRegState(true))
8115ffd83dbSDimitry Andric         .addImm(CRSaveOffset)
812*0b57cec5SDimitry Andric         .addReg(SPReg);
813*0b57cec5SDimitry Andric   }
814*0b57cec5SDimitry Andric 
815*0b57cec5SDimitry Andric   if (MustSaveLR)
816*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
817*0b57cec5SDimitry Andric 
8185ffd83dbSDimitry Andric   if (MustSaveCR && !(SingleScratchReg && MustSaveLR))
8195ffd83dbSDimitry Andric     BuildMoveFromCR();
820*0b57cec5SDimitry Andric 
821*0b57cec5SDimitry Andric   if (HasRedZone) {
822*0b57cec5SDimitry Andric     if (HasFP)
823*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, StoreInst)
824*0b57cec5SDimitry Andric         .addReg(FPReg)
825*0b57cec5SDimitry Andric         .addImm(FPOffset)
826*0b57cec5SDimitry Andric         .addReg(SPReg);
827*0b57cec5SDimitry Andric     if (FI->usesPICBase())
828*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, StoreInst)
829*0b57cec5SDimitry Andric         .addReg(PPC::R30)
830*0b57cec5SDimitry Andric         .addImm(PBPOffset)
831*0b57cec5SDimitry Andric         .addReg(SPReg);
832*0b57cec5SDimitry Andric     if (HasBP)
833*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, StoreInst)
834*0b57cec5SDimitry Andric         .addReg(BPReg)
835*0b57cec5SDimitry Andric         .addImm(BPOffset)
836*0b57cec5SDimitry Andric         .addReg(SPReg);
837*0b57cec5SDimitry Andric   }
838*0b57cec5SDimitry Andric 
839fe6060f1SDimitry Andric   // Generate the instruction to store the LR. In the case where ROP protection
840fe6060f1SDimitry Andric   // is required the register holding the LR should not be killed as it will be
841fe6060f1SDimitry Andric   // used by the hash store instruction.
842bdd1243dSDimitry Andric   auto SaveLR = [&](int64_t Offset) {
843bdd1243dSDimitry Andric     assert(MustSaveLR && "LR is not required to be saved!");
844*0b57cec5SDimitry Andric     BuildMI(MBB, StackUpdateLoc, dl, StoreInst)
845fe6060f1SDimitry Andric         .addReg(ScratchReg, getKillRegState(!HasROPProtect))
846bdd1243dSDimitry Andric         .addImm(Offset)
847*0b57cec5SDimitry Andric         .addReg(SPReg);
848*0b57cec5SDimitry Andric 
849fe6060f1SDimitry Andric     // Add the ROP protection Hash Store instruction.
850fe6060f1SDimitry Andric     // NOTE: This is technically a violation of the ABI. The hash can be saved
851fe6060f1SDimitry Andric     // up to 512 bytes into the Protected Zone. This can be outside of the
852fe6060f1SDimitry Andric     // initial 288 byte volatile program storage region in the Protected Zone.
853fe6060f1SDimitry Andric     // However, this restriction will be removed in an upcoming revision of the
854fe6060f1SDimitry Andric     // ABI.
855fe6060f1SDimitry Andric     if (HasROPProtect) {
856fe6060f1SDimitry Andric       const int SaveIndex = FI->getROPProtectionHashSaveIndex();
857349cc55cSDimitry Andric       const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
858fe6060f1SDimitry Andric       assert((ImmOffset <= -8 && ImmOffset >= -512) &&
859fe6060f1SDimitry Andric              "ROP hash save offset out of range.");
860fe6060f1SDimitry Andric       assert(((ImmOffset & 0x7) == 0) &&
861fe6060f1SDimitry Andric              "ROP hash save offset must be 8 byte aligned.");
862fe6060f1SDimitry Andric       BuildMI(MBB, StackUpdateLoc, dl, HashST)
863fe6060f1SDimitry Andric           .addReg(ScratchReg, getKillRegState(true))
864fe6060f1SDimitry Andric           .addImm(ImmOffset)
865fe6060f1SDimitry Andric           .addReg(SPReg);
866fe6060f1SDimitry Andric     }
867bdd1243dSDimitry Andric   };
868bdd1243dSDimitry Andric 
869bdd1243dSDimitry Andric   if (MustSaveLR && HasFastMFLR)
870bdd1243dSDimitry Andric       SaveLR(LROffset);
871fe6060f1SDimitry Andric 
872*0b57cec5SDimitry Andric   if (MustSaveCR &&
8735ffd83dbSDimitry Andric       !(SingleScratchReg && MustSaveLR)) {
874*0b57cec5SDimitry Andric     assert(HasRedZone && "A red zone is always available on PPC64");
8755ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, dl, StoreWordInst)
876*0b57cec5SDimitry Andric       .addReg(TempReg, getKillRegState(true))
8775ffd83dbSDimitry Andric       .addImm(CRSaveOffset)
878*0b57cec5SDimitry Andric       .addReg(SPReg);
879*0b57cec5SDimitry Andric   }
880*0b57cec5SDimitry Andric 
881*0b57cec5SDimitry Andric   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
882bdd1243dSDimitry Andric   if (!FrameSize) {
883bdd1243dSDimitry Andric     if (MustSaveLR && !HasFastMFLR)
884bdd1243dSDimitry Andric       SaveLR(LROffset);
885*0b57cec5SDimitry Andric     return;
886bdd1243dSDimitry Andric   }
887*0b57cec5SDimitry Andric 
888*0b57cec5SDimitry Andric   // Adjust stack pointer: r1 += NegFrameSize.
889*0b57cec5SDimitry Andric   // If there is a preferred stack alignment, align R1 now
890*0b57cec5SDimitry Andric 
891*0b57cec5SDimitry Andric   if (HasBP && HasRedZone) {
892*0b57cec5SDimitry Andric     // Save a copy of r1 as the base pointer.
893*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
894*0b57cec5SDimitry Andric       .addReg(SPReg)
895*0b57cec5SDimitry Andric       .addReg(SPReg);
896*0b57cec5SDimitry Andric   }
897*0b57cec5SDimitry Andric 
898*0b57cec5SDimitry Andric   // Have we generated a STUX instruction to claim stack frame? If so,
899*0b57cec5SDimitry Andric   // the negated frame size will be placed in ScratchReg.
900bdd1243dSDimitry Andric   bool HasSTUX =
901bdd1243dSDimitry Andric       (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) ||
902bdd1243dSDimitry Andric       (HasBP && MaxAlign > 1) || isLargeFrame;
903bdd1243dSDimitry Andric 
904bdd1243dSDimitry Andric   // If we use STUX to update the stack pointer, we need the two scratch
905bdd1243dSDimitry Andric   // registers TempReg and ScratchReg, we have to save LR here which is stored
906bdd1243dSDimitry Andric   // in ScratchReg.
907bdd1243dSDimitry Andric   // If the offset can not be encoded into the store instruction, we also have
908bdd1243dSDimitry Andric   // to save LR here.
909bdd1243dSDimitry Andric   if (MustSaveLR && !HasFastMFLR &&
910bdd1243dSDimitry Andric       (HasSTUX || !isInt<16>(FrameSize + LROffset)))
911bdd1243dSDimitry Andric     SaveLR(LROffset);
912*0b57cec5SDimitry Andric 
9135ffd83dbSDimitry Andric   // If FrameSize <= TLI.getStackProbeSize(MF), as POWER ABI requires backchain
9145ffd83dbSDimitry Andric   // pointer is always stored at SP, we will get a free probe due to an essential
9155ffd83dbSDimitry Andric   // STU(X) instruction.
9165ffd83dbSDimitry Andric   if (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) {
9175ffd83dbSDimitry Andric     // To be consistent with other targets, a pseudo instruction is emitted and
9185ffd83dbSDimitry Andric     // will be later expanded in `inlineStackProbe`.
9195ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, dl,
9205ffd83dbSDimitry Andric             TII.get(isPPC64 ? PPC::PROBED_STACKALLOC_64
9215ffd83dbSDimitry Andric                             : PPC::PROBED_STACKALLOC_32))
92223408297SDimitry Andric         .addDef(TempReg)
92323408297SDimitry Andric         .addDef(ScratchReg) // ScratchReg stores the old sp.
9245ffd83dbSDimitry Andric         .addImm(NegFrameSize);
9255ffd83dbSDimitry Andric     // FIXME: HasSTUX is only read if HasRedZone is not set, in such case, we
9265ffd83dbSDimitry Andric     // update the ScratchReg to meet the assumption that ScratchReg contains
9275ffd83dbSDimitry Andric     // the NegFrameSize. This solution is rather tricky.
9285ffd83dbSDimitry Andric     if (!HasRedZone) {
9295ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
93023408297SDimitry Andric           .addReg(ScratchReg)
9315ffd83dbSDimitry Andric           .addReg(SPReg);
9325ffd83dbSDimitry Andric     }
9335ffd83dbSDimitry Andric   } else {
934*0b57cec5SDimitry Andric     // This condition must be kept in sync with canUseAsPrologue.
935*0b57cec5SDimitry Andric     if (HasBP && MaxAlign > 1) {
936*0b57cec5SDimitry Andric       if (isPPC64)
937*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
938*0b57cec5SDimitry Andric             .addReg(SPReg)
939*0b57cec5SDimitry Andric             .addImm(0)
9405ffd83dbSDimitry Andric             .addImm(64 - Log2(MaxAlign));
941*0b57cec5SDimitry Andric       else // PPC32...
942*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
943*0b57cec5SDimitry Andric             .addReg(SPReg)
944*0b57cec5SDimitry Andric             .addImm(0)
9455ffd83dbSDimitry Andric             .addImm(32 - Log2(MaxAlign))
946*0b57cec5SDimitry Andric             .addImm(31);
947*0b57cec5SDimitry Andric       if (!isLargeFrame) {
948*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
949*0b57cec5SDimitry Andric             .addReg(ScratchReg, RegState::Kill)
950*0b57cec5SDimitry Andric             .addImm(NegFrameSize);
951*0b57cec5SDimitry Andric       } else {
952*0b57cec5SDimitry Andric         assert(!SingleScratchReg && "Only a single scratch reg available");
95381ad6265SDimitry Andric         TII.materializeImmPostRA(MBB, MBBI, dl, TempReg, NegFrameSize);
954*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
955*0b57cec5SDimitry Andric             .addReg(ScratchReg, RegState::Kill)
956*0b57cec5SDimitry Andric             .addReg(TempReg, RegState::Kill);
957*0b57cec5SDimitry Andric       }
958*0b57cec5SDimitry Andric 
959*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
960*0b57cec5SDimitry Andric           .addReg(SPReg, RegState::Kill)
961*0b57cec5SDimitry Andric           .addReg(SPReg)
962*0b57cec5SDimitry Andric           .addReg(ScratchReg);
963*0b57cec5SDimitry Andric     } else if (!isLargeFrame) {
964*0b57cec5SDimitry Andric       BuildMI(MBB, StackUpdateLoc, dl, StoreUpdtInst, SPReg)
965*0b57cec5SDimitry Andric           .addReg(SPReg)
966*0b57cec5SDimitry Andric           .addImm(NegFrameSize)
967*0b57cec5SDimitry Andric           .addReg(SPReg);
968*0b57cec5SDimitry Andric     } else {
96981ad6265SDimitry Andric       TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, NegFrameSize);
970*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
971*0b57cec5SDimitry Andric           .addReg(SPReg, RegState::Kill)
972*0b57cec5SDimitry Andric           .addReg(SPReg)
973*0b57cec5SDimitry Andric           .addReg(ScratchReg);
974*0b57cec5SDimitry Andric     }
9755ffd83dbSDimitry Andric   }
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric   // Save the TOC register after the stack pointer update if a prologue TOC
978*0b57cec5SDimitry Andric   // save is required for the function.
979*0b57cec5SDimitry Andric   if (MustSaveTOC) {
980*0b57cec5SDimitry Andric     assert(isELFv2ABI && "TOC saves in the prologue only supported on ELFv2");
981*0b57cec5SDimitry Andric     BuildMI(MBB, StackUpdateLoc, dl, TII.get(PPC::STD))
982*0b57cec5SDimitry Andric       .addReg(TOCReg, getKillRegState(true))
983*0b57cec5SDimitry Andric       .addImm(TOCSaveOffset)
984*0b57cec5SDimitry Andric       .addReg(SPReg);
985*0b57cec5SDimitry Andric   }
986*0b57cec5SDimitry Andric 
987*0b57cec5SDimitry Andric   if (!HasRedZone) {
988*0b57cec5SDimitry Andric     assert(!isPPC64 && "A red zone is always available on PPC64");
989*0b57cec5SDimitry Andric     if (HasSTUX) {
990*0b57cec5SDimitry Andric       // The negated frame size is in ScratchReg, and the SPReg has been
991*0b57cec5SDimitry Andric       // decremented by the frame size: SPReg = old SPReg + ScratchReg.
992*0b57cec5SDimitry Andric       // Since FPOffset, PBPOffset, etc. are relative to the beginning of
993*0b57cec5SDimitry Andric       // the stack frame (i.e. the old SP), ideally, we would put the old
994*0b57cec5SDimitry Andric       // SP into a register and use it as the base for the stores. The
995*0b57cec5SDimitry Andric       // problem is that the only available register may be ScratchReg,
996*0b57cec5SDimitry Andric       // which could be R0, and R0 cannot be used as a base address.
997*0b57cec5SDimitry Andric 
998*0b57cec5SDimitry Andric       // First, set ScratchReg to the old SP. This may need to be modified
999*0b57cec5SDimitry Andric       // later.
1000*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
1001*0b57cec5SDimitry Andric         .addReg(ScratchReg, RegState::Kill)
1002*0b57cec5SDimitry Andric         .addReg(SPReg);
1003*0b57cec5SDimitry Andric 
1004*0b57cec5SDimitry Andric       if (ScratchReg == PPC::R0) {
1005*0b57cec5SDimitry Andric         // R0 cannot be used as a base register, but it can be used as an
1006*0b57cec5SDimitry Andric         // index in a store-indexed.
1007*0b57cec5SDimitry Andric         int LastOffset = 0;
1008*0b57cec5SDimitry Andric         if (HasFP)  {
1009*0b57cec5SDimitry Andric           // R0 += (FPOffset-LastOffset).
1010*0b57cec5SDimitry Andric           // Need addic, since addi treats R0 as 0.
1011*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1012*0b57cec5SDimitry Andric             .addReg(ScratchReg)
1013*0b57cec5SDimitry Andric             .addImm(FPOffset-LastOffset);
1014*0b57cec5SDimitry Andric           LastOffset = FPOffset;
1015*0b57cec5SDimitry Andric           // Store FP into *R0.
1016*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1017*0b57cec5SDimitry Andric             .addReg(FPReg, RegState::Kill)  // Save FP.
1018*0b57cec5SDimitry Andric             .addReg(PPC::ZERO)
1019*0b57cec5SDimitry Andric             .addReg(ScratchReg);  // This will be the index (R0 is ok here).
1020*0b57cec5SDimitry Andric         }
1021*0b57cec5SDimitry Andric         if (FI->usesPICBase()) {
1022*0b57cec5SDimitry Andric           // R0 += (PBPOffset-LastOffset).
1023*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1024*0b57cec5SDimitry Andric             .addReg(ScratchReg)
1025*0b57cec5SDimitry Andric             .addImm(PBPOffset-LastOffset);
1026*0b57cec5SDimitry Andric           LastOffset = PBPOffset;
1027*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1028*0b57cec5SDimitry Andric             .addReg(PPC::R30, RegState::Kill)  // Save PIC base pointer.
1029*0b57cec5SDimitry Andric             .addReg(PPC::ZERO)
1030*0b57cec5SDimitry Andric             .addReg(ScratchReg);  // This will be the index (R0 is ok here).
1031*0b57cec5SDimitry Andric         }
1032*0b57cec5SDimitry Andric         if (HasBP) {
1033*0b57cec5SDimitry Andric           // R0 += (BPOffset-LastOffset).
1034*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
1035*0b57cec5SDimitry Andric             .addReg(ScratchReg)
1036*0b57cec5SDimitry Andric             .addImm(BPOffset-LastOffset);
1037*0b57cec5SDimitry Andric           LastOffset = BPOffset;
1038*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
1039*0b57cec5SDimitry Andric             .addReg(BPReg, RegState::Kill)  // Save BP.
1040*0b57cec5SDimitry Andric             .addReg(PPC::ZERO)
1041*0b57cec5SDimitry Andric             .addReg(ScratchReg);  // This will be the index (R0 is ok here).
1042*0b57cec5SDimitry Andric           // BP = R0-LastOffset
1043*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), BPReg)
1044*0b57cec5SDimitry Andric             .addReg(ScratchReg, RegState::Kill)
1045*0b57cec5SDimitry Andric             .addImm(-LastOffset);
1046*0b57cec5SDimitry Andric         }
1047*0b57cec5SDimitry Andric       } else {
1048*0b57cec5SDimitry Andric         // ScratchReg is not R0, so use it as the base register. It is
1049*0b57cec5SDimitry Andric         // already set to the old SP, so we can use the offsets directly.
1050*0b57cec5SDimitry Andric 
1051*0b57cec5SDimitry Andric         // Now that the stack frame has been allocated, save all the necessary
1052*0b57cec5SDimitry Andric         // registers using ScratchReg as the base address.
1053*0b57cec5SDimitry Andric         if (HasFP)
1054*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, StoreInst)
1055*0b57cec5SDimitry Andric             .addReg(FPReg)
1056*0b57cec5SDimitry Andric             .addImm(FPOffset)
1057*0b57cec5SDimitry Andric             .addReg(ScratchReg);
1058*0b57cec5SDimitry Andric         if (FI->usesPICBase())
1059*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, StoreInst)
1060*0b57cec5SDimitry Andric             .addReg(PPC::R30)
1061*0b57cec5SDimitry Andric             .addImm(PBPOffset)
1062*0b57cec5SDimitry Andric             .addReg(ScratchReg);
1063*0b57cec5SDimitry Andric         if (HasBP) {
1064*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, StoreInst)
1065*0b57cec5SDimitry Andric             .addReg(BPReg)
1066*0b57cec5SDimitry Andric             .addImm(BPOffset)
1067*0b57cec5SDimitry Andric             .addReg(ScratchReg);
1068*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, OrInst, BPReg)
1069*0b57cec5SDimitry Andric             .addReg(ScratchReg, RegState::Kill)
1070*0b57cec5SDimitry Andric             .addReg(ScratchReg);
1071*0b57cec5SDimitry Andric         }
1072*0b57cec5SDimitry Andric       }
1073*0b57cec5SDimitry Andric     } else {
1074*0b57cec5SDimitry Andric       // The frame size is a known 16-bit constant (fitting in the immediate
1075*0b57cec5SDimitry Andric       // field of STWU). To be here we have to be compiling for PPC32.
1076*0b57cec5SDimitry Andric       // Since the SPReg has been decreased by FrameSize, add it back to each
1077*0b57cec5SDimitry Andric       // offset.
1078*0b57cec5SDimitry Andric       if (HasFP)
1079*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, StoreInst)
1080*0b57cec5SDimitry Andric           .addReg(FPReg)
1081*0b57cec5SDimitry Andric           .addImm(FrameSize + FPOffset)
1082*0b57cec5SDimitry Andric           .addReg(SPReg);
1083*0b57cec5SDimitry Andric       if (FI->usesPICBase())
1084*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, StoreInst)
1085*0b57cec5SDimitry Andric           .addReg(PPC::R30)
1086*0b57cec5SDimitry Andric           .addImm(FrameSize + PBPOffset)
1087*0b57cec5SDimitry Andric           .addReg(SPReg);
1088*0b57cec5SDimitry Andric       if (HasBP) {
1089*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, StoreInst)
1090*0b57cec5SDimitry Andric           .addReg(BPReg)
1091*0b57cec5SDimitry Andric           .addImm(FrameSize + BPOffset)
1092*0b57cec5SDimitry Andric           .addReg(SPReg);
1093*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), BPReg)
1094*0b57cec5SDimitry Andric           .addReg(SPReg)
1095*0b57cec5SDimitry Andric           .addImm(FrameSize);
1096*0b57cec5SDimitry Andric       }
1097*0b57cec5SDimitry Andric     }
1098*0b57cec5SDimitry Andric   }
1099*0b57cec5SDimitry Andric 
1100bdd1243dSDimitry Andric   // Save the LR now.
1101bdd1243dSDimitry Andric   if (!HasSTUX && MustSaveLR && !HasFastMFLR && isInt<16>(FrameSize + LROffset))
1102bdd1243dSDimitry Andric     SaveLR(LROffset + FrameSize);
1103bdd1243dSDimitry Andric 
1104*0b57cec5SDimitry Andric   // Add Call Frame Information for the instructions we generated above.
1105*0b57cec5SDimitry Andric   if (needsCFI) {
1106*0b57cec5SDimitry Andric     unsigned CFIIndex;
1107*0b57cec5SDimitry Andric 
1108*0b57cec5SDimitry Andric     if (HasBP) {
1109*0b57cec5SDimitry Andric       // Define CFA in terms of BP. Do this in preference to using FP/SP,
1110*0b57cec5SDimitry Andric       // because if the stack needed aligning then CFA won't be at a fixed
1111*0b57cec5SDimitry Andric       // offset from FP/SP.
1112*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
1113*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
1114*0b57cec5SDimitry Andric           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1115*0b57cec5SDimitry Andric     } else {
1116*0b57cec5SDimitry Andric       // Adjust the definition of CFA to account for the change in SP.
1117*0b57cec5SDimitry Andric       assert(NegFrameSize);
1118*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
11195ffd83dbSDimitry Andric           MCCFIInstruction::cfiDefCfaOffset(nullptr, -NegFrameSize));
1120*0b57cec5SDimitry Andric     }
1121*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1122*0b57cec5SDimitry Andric         .addCFIIndex(CFIIndex);
1123*0b57cec5SDimitry Andric 
1124*0b57cec5SDimitry Andric     if (HasFP) {
1125*0b57cec5SDimitry Andric       // Describe where FP was saved, at a fixed offset from CFA.
1126*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
1127*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
1128*0b57cec5SDimitry Andric           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
1129*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1130*0b57cec5SDimitry Andric           .addCFIIndex(CFIIndex);
1131*0b57cec5SDimitry Andric     }
1132*0b57cec5SDimitry Andric 
1133*0b57cec5SDimitry Andric     if (FI->usesPICBase()) {
1134*0b57cec5SDimitry Andric       // Describe where FP was saved, at a fixed offset from CFA.
1135*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
1136*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
1137*0b57cec5SDimitry Andric           MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
1138*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1139*0b57cec5SDimitry Andric           .addCFIIndex(CFIIndex);
1140*0b57cec5SDimitry Andric     }
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric     if (HasBP) {
1143*0b57cec5SDimitry Andric       // Describe where BP was saved, at a fixed offset from CFA.
1144*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
1145*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
1146*0b57cec5SDimitry Andric           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
1147*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1148*0b57cec5SDimitry Andric           .addCFIIndex(CFIIndex);
1149*0b57cec5SDimitry Andric     }
1150*0b57cec5SDimitry Andric 
1151*0b57cec5SDimitry Andric     if (MustSaveLR) {
1152*0b57cec5SDimitry Andric       // Describe where LR was saved, at a fixed offset from CFA.
1153*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
1154*0b57cec5SDimitry Andric       CFIIndex = MF.addFrameInst(
1155*0b57cec5SDimitry Andric           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
1156*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1157*0b57cec5SDimitry Andric           .addCFIIndex(CFIIndex);
1158*0b57cec5SDimitry Andric     }
1159*0b57cec5SDimitry Andric   }
1160*0b57cec5SDimitry Andric 
1161*0b57cec5SDimitry Andric   // If there is a frame pointer, copy R1 into R31
1162*0b57cec5SDimitry Andric   if (HasFP) {
1163*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
1164*0b57cec5SDimitry Andric       .addReg(SPReg)
1165*0b57cec5SDimitry Andric       .addReg(SPReg);
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric     if (!HasBP && needsCFI) {
1168*0b57cec5SDimitry Andric       // Change the definition of CFA from SP+offset to FP+offset, because SP
1169*0b57cec5SDimitry Andric       // will change at every alloca.
1170*0b57cec5SDimitry Andric       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
1171*0b57cec5SDimitry Andric       unsigned CFIIndex = MF.addFrameInst(
1172*0b57cec5SDimitry Andric           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1175*0b57cec5SDimitry Andric           .addCFIIndex(CFIIndex);
1176*0b57cec5SDimitry Andric     }
1177*0b57cec5SDimitry Andric   }
1178*0b57cec5SDimitry Andric 
1179*0b57cec5SDimitry Andric   if (needsCFI) {
1180*0b57cec5SDimitry Andric     // Describe where callee saved registers were saved, at fixed offsets from
1181*0b57cec5SDimitry Andric     // CFA.
1182*0b57cec5SDimitry Andric     const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
11834824e7fdSDimitry Andric     for (const CalleeSavedInfo &I : CSI) {
118404eeddc0SDimitry Andric       Register Reg = I.getReg();
1185*0b57cec5SDimitry Andric       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
1186*0b57cec5SDimitry Andric 
1187*0b57cec5SDimitry Andric       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
1188*0b57cec5SDimitry Andric       // subregisters of CR2. We just need to emit a move of CR2.
1189*0b57cec5SDimitry Andric       if (PPC::CRBITRCRegClass.contains(Reg))
1190*0b57cec5SDimitry Andric         continue;
1191*0b57cec5SDimitry Andric 
1192*0b57cec5SDimitry Andric       if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
1193*0b57cec5SDimitry Andric         continue;
1194*0b57cec5SDimitry Andric 
1195*0b57cec5SDimitry Andric       // For SVR4, don't emit a move for the CR spill slot if we haven't
1196*0b57cec5SDimitry Andric       // spilled CRs.
1197*0b57cec5SDimitry Andric       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
1198*0b57cec5SDimitry Andric           && !MustSaveCR)
1199*0b57cec5SDimitry Andric         continue;
1200*0b57cec5SDimitry Andric 
1201*0b57cec5SDimitry Andric       // For 64-bit SVR4 when we have spilled CRs, the spill location
1202*0b57cec5SDimitry Andric       // is SP+8, not a frame-relative slot.
1203*0b57cec5SDimitry Andric       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1204*0b57cec5SDimitry Andric         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
1205*0b57cec5SDimitry Andric         // the whole CR word.  In the ELFv2 ABI, every CR that was
1206*0b57cec5SDimitry Andric         // actually saved gets its own CFI record.
120704eeddc0SDimitry Andric         Register CRReg = isELFv2ABI? Reg : PPC::CR2;
1208*0b57cec5SDimitry Andric         unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
12095ffd83dbSDimitry Andric             nullptr, MRI->getDwarfRegNum(CRReg, true), CRSaveOffset));
1210*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1211*0b57cec5SDimitry Andric             .addCFIIndex(CFIIndex);
1212*0b57cec5SDimitry Andric         continue;
1213*0b57cec5SDimitry Andric       }
1214*0b57cec5SDimitry Andric 
12154824e7fdSDimitry Andric       if (I.isSpilledToReg()) {
12164824e7fdSDimitry Andric         unsigned SpilledReg = I.getDstReg();
1217*0b57cec5SDimitry Andric         unsigned CFIRegister = MF.addFrameInst(MCCFIInstruction::createRegister(
1218*0b57cec5SDimitry Andric             nullptr, MRI->getDwarfRegNum(Reg, true),
1219*0b57cec5SDimitry Andric             MRI->getDwarfRegNum(SpilledReg, true)));
1220*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1221*0b57cec5SDimitry Andric           .addCFIIndex(CFIRegister);
1222*0b57cec5SDimitry Andric       } else {
12234824e7fdSDimitry Andric         int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
1224*0b57cec5SDimitry Andric         // We have changed the object offset above but we do not want to change
1225*0b57cec5SDimitry Andric         // the actual offsets in the CFI instruction so we have to undo the
1226*0b57cec5SDimitry Andric         // offset change here.
1227*0b57cec5SDimitry Andric         if (MovingStackUpdateDown)
1228*0b57cec5SDimitry Andric           Offset -= NegFrameSize;
1229*0b57cec5SDimitry Andric 
1230*0b57cec5SDimitry Andric         unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
1231*0b57cec5SDimitry Andric             nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
1232*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
1233*0b57cec5SDimitry Andric             .addCFIIndex(CFIIndex);
1234*0b57cec5SDimitry Andric       }
1235*0b57cec5SDimitry Andric     }
1236*0b57cec5SDimitry Andric   }
1237*0b57cec5SDimitry Andric }
1238*0b57cec5SDimitry Andric 
12395ffd83dbSDimitry Andric void PPCFrameLowering::inlineStackProbe(MachineFunction &MF,
12405ffd83dbSDimitry Andric                                         MachineBasicBlock &PrologMBB) const {
12415ffd83dbSDimitry Andric   bool isPPC64 = Subtarget.isPPC64();
12425ffd83dbSDimitry Andric   const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
12435ffd83dbSDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
12445ffd83dbSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
12455ffd83dbSDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
12465ffd83dbSDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
12475ffd83dbSDimitry Andric   // AIX assembler does not support cfi directives.
12485ffd83dbSDimitry Andric   const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
12495ffd83dbSDimitry Andric   auto StackAllocMIPos = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
12505ffd83dbSDimitry Andric     int Opc = MI.getOpcode();
12515ffd83dbSDimitry Andric     return Opc == PPC::PROBED_STACKALLOC_64 || Opc == PPC::PROBED_STACKALLOC_32;
12525ffd83dbSDimitry Andric   });
12535ffd83dbSDimitry Andric   if (StackAllocMIPos == PrologMBB.end())
12545ffd83dbSDimitry Andric     return;
12555ffd83dbSDimitry Andric   const BasicBlock *ProbedBB = PrologMBB.getBasicBlock();
1256e8d8bef9SDimitry Andric   MachineBasicBlock *CurrentMBB = &PrologMBB;
12575ffd83dbSDimitry Andric   DebugLoc DL = PrologMBB.findDebugLoc(StackAllocMIPos);
12585ffd83dbSDimitry Andric   MachineInstr &MI = *StackAllocMIPos;
12595ffd83dbSDimitry Andric   int64_t NegFrameSize = MI.getOperand(2).getImm();
1260e8d8bef9SDimitry Andric   unsigned ProbeSize = TLI.getStackProbeSize(MF);
1261e8d8bef9SDimitry Andric   int64_t NegProbeSize = -(int64_t)ProbeSize;
12625ffd83dbSDimitry Andric   assert(isInt<32>(NegProbeSize) && "Unhandled probe size");
12635ffd83dbSDimitry Andric   int64_t NumBlocks = NegFrameSize / NegProbeSize;
12645ffd83dbSDimitry Andric   int64_t NegResidualSize = NegFrameSize % NegProbeSize;
12655ffd83dbSDimitry Andric   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12665ffd83dbSDimitry Andric   Register ScratchReg = MI.getOperand(0).getReg();
12675ffd83dbSDimitry Andric   Register FPReg = MI.getOperand(1).getReg();
12685ffd83dbSDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
12695ffd83dbSDimitry Andric   bool HasBP = RegInfo->hasBasePointer(MF);
1270e8d8bef9SDimitry Andric   Register BPReg = RegInfo->getBaseRegister(MF);
12715ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign();
127223408297SDimitry Andric   bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
12735ffd83dbSDimitry Andric   const MCInstrDesc &CopyInst = TII.get(isPPC64 ? PPC::OR8 : PPC::OR);
12745ffd83dbSDimitry Andric   // Subroutines to generate .cfi_* directives.
12755ffd83dbSDimitry Andric   auto buildDefCFAReg = [&](MachineBasicBlock &MBB,
12765ffd83dbSDimitry Andric                             MachineBasicBlock::iterator MBBI, Register Reg) {
12775ffd83dbSDimitry Andric     unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
12785ffd83dbSDimitry Andric     unsigned CFIIndex = MF.addFrameInst(
12795ffd83dbSDimitry Andric         MCCFIInstruction::createDefCfaRegister(nullptr, RegNum));
12805ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
12815ffd83dbSDimitry Andric         .addCFIIndex(CFIIndex);
12825ffd83dbSDimitry Andric   };
12835ffd83dbSDimitry Andric   auto buildDefCFA = [&](MachineBasicBlock &MBB,
12845ffd83dbSDimitry Andric                          MachineBasicBlock::iterator MBBI, Register Reg,
12855ffd83dbSDimitry Andric                          int Offset) {
12865ffd83dbSDimitry Andric     unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
12875ffd83dbSDimitry Andric     unsigned CFIIndex = MBB.getParent()->addFrameInst(
12885ffd83dbSDimitry Andric         MCCFIInstruction::cfiDefCfa(nullptr, RegNum, Offset));
12895ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
12905ffd83dbSDimitry Andric         .addCFIIndex(CFIIndex);
12915ffd83dbSDimitry Andric   };
12925ffd83dbSDimitry Andric   // Subroutine to determine if we can use the Imm as part of d-form.
12935ffd83dbSDimitry Andric   auto CanUseDForm = [](int64_t Imm) { return isInt<16>(Imm) && Imm % 4 == 0; };
12945ffd83dbSDimitry Andric   // Subroutine to materialize the Imm into TempReg.
12955ffd83dbSDimitry Andric   auto MaterializeImm = [&](MachineBasicBlock &MBB,
12965ffd83dbSDimitry Andric                             MachineBasicBlock::iterator MBBI, int64_t Imm,
12975ffd83dbSDimitry Andric                             Register &TempReg) {
12985ffd83dbSDimitry Andric     assert(isInt<32>(Imm) && "Unhandled imm");
12995ffd83dbSDimitry Andric     if (isInt<16>(Imm))
13005ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LI8 : PPC::LI), TempReg)
13015ffd83dbSDimitry Andric           .addImm(Imm);
13025ffd83dbSDimitry Andric     else {
13035ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
13045ffd83dbSDimitry Andric           .addImm(Imm >> 16);
13055ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::ORI8 : PPC::ORI), TempReg)
13065ffd83dbSDimitry Andric           .addReg(TempReg)
13075ffd83dbSDimitry Andric           .addImm(Imm & 0xFFFF);
13085ffd83dbSDimitry Andric     }
13095ffd83dbSDimitry Andric   };
13105ffd83dbSDimitry Andric   // Subroutine to store frame pointer and decrease stack pointer by probe size.
13115ffd83dbSDimitry Andric   auto allocateAndProbe = [&](MachineBasicBlock &MBB,
13125ffd83dbSDimitry Andric                               MachineBasicBlock::iterator MBBI, int64_t NegSize,
1313e8d8bef9SDimitry Andric                               Register NegSizeReg, bool UseDForm,
1314e8d8bef9SDimitry Andric                               Register StoreReg) {
13155ffd83dbSDimitry Andric     if (UseDForm)
13165ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDU : PPC::STWU), SPReg)
1317e8d8bef9SDimitry Andric           .addReg(StoreReg)
13185ffd83dbSDimitry Andric           .addImm(NegSize)
13195ffd83dbSDimitry Andric           .addReg(SPReg);
13205ffd83dbSDimitry Andric     else
13215ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
1322e8d8bef9SDimitry Andric           .addReg(StoreReg)
13235ffd83dbSDimitry Andric           .addReg(SPReg)
13245ffd83dbSDimitry Andric           .addReg(NegSizeReg);
13255ffd83dbSDimitry Andric   };
132623408297SDimitry Andric   // Used to probe stack when realignment is required.
132723408297SDimitry Andric   // Note that, according to ABI's requirement, *sp must always equals the
132823408297SDimitry Andric   // value of back-chain pointer, only st(w|d)u(x) can be used to update sp.
132923408297SDimitry Andric   // Following is pseudo code:
133023408297SDimitry Andric   // final_sp = (sp & align) + negframesize;
133123408297SDimitry Andric   // neg_gap = final_sp - sp;
133223408297SDimitry Andric   // while (neg_gap < negprobesize) {
133323408297SDimitry Andric   //   stdu fp, negprobesize(sp);
133423408297SDimitry Andric   //   neg_gap -= negprobesize;
133523408297SDimitry Andric   // }
133623408297SDimitry Andric   // stdux fp, sp, neg_gap
133723408297SDimitry Andric   //
133823408297SDimitry Andric   // When HasBP & HasRedzone, back-chain pointer is already saved in BPReg
133923408297SDimitry Andric   // before probe code, we don't need to save it, so we get one additional reg
134023408297SDimitry Andric   // that can be used to materialize the probeside if needed to use xform.
134123408297SDimitry Andric   // Otherwise, we can NOT materialize probeside, so we can only use Dform for
134223408297SDimitry Andric   // now.
134323408297SDimitry Andric   //
134423408297SDimitry Andric   // The allocations are:
134523408297SDimitry Andric   // if (HasBP && HasRedzone) {
134623408297SDimitry Andric   //   r0: materialize the probesize if needed so that we can use xform.
134723408297SDimitry Andric   //   r12: `neg_gap`
134823408297SDimitry Andric   // } else {
134923408297SDimitry Andric   //   r0: back-chain pointer
135023408297SDimitry Andric   //   r12: `neg_gap`.
135123408297SDimitry Andric   // }
135223408297SDimitry Andric   auto probeRealignedStack = [&](MachineBasicBlock &MBB,
135323408297SDimitry Andric                                  MachineBasicBlock::iterator MBBI,
135423408297SDimitry Andric                                  Register ScratchReg, Register TempReg) {
135523408297SDimitry Andric     assert(HasBP && "The function is supposed to have base pointer when its "
135623408297SDimitry Andric                     "stack is realigned.");
1357e8d8bef9SDimitry Andric     assert(isPowerOf2_64(ProbeSize) && "Probe size should be power of 2");
135823408297SDimitry Andric 
135923408297SDimitry Andric     // FIXME: We can eliminate this limitation if we get more infomation about
136023408297SDimitry Andric     // which part of redzone are already used. Used redzone can be treated
136123408297SDimitry Andric     // probed. But there might be `holes' in redzone probed, this could
136223408297SDimitry Andric     // complicate the implementation.
136323408297SDimitry Andric     assert(ProbeSize >= Subtarget.getRedZoneSize() &&
136423408297SDimitry Andric            "Probe size should be larger or equal to the size of red-zone so "
136523408297SDimitry Andric            "that red-zone is not clobbered by probing.");
136623408297SDimitry Andric 
136723408297SDimitry Andric     Register &FinalStackPtr = TempReg;
136823408297SDimitry Andric     // FIXME: We only support NegProbeSize materializable by DForm currently.
136923408297SDimitry Andric     // When HasBP && HasRedzone, we can use xform if we have an additional idle
137023408297SDimitry Andric     // register.
137123408297SDimitry Andric     NegProbeSize = std::max(NegProbeSize, -((int64_t)1 << 15));
137223408297SDimitry Andric     assert(isInt<16>(NegProbeSize) &&
137323408297SDimitry Andric            "NegProbeSize should be materializable by DForm");
1374e8d8bef9SDimitry Andric     Register CRReg = PPC::CR0;
137523408297SDimitry Andric     // Layout of output assembly kinda like:
1376e8d8bef9SDimitry Andric     // bb.0:
1377e8d8bef9SDimitry Andric     //   ...
137823408297SDimitry Andric     //   sub $scratchreg, $finalsp, r1
137923408297SDimitry Andric     //   cmpdi $scratchreg, <negprobesize>
138023408297SDimitry Andric     //   bge bb.2
138123408297SDimitry Andric     // bb.1:
138223408297SDimitry Andric     //   stdu <backchain>, <negprobesize>(r1)
138323408297SDimitry Andric     //   sub $scratchreg, $scratchreg, negprobesize
138423408297SDimitry Andric     //   cmpdi $scratchreg, <negprobesize>
138523408297SDimitry Andric     //   blt bb.1
1386e8d8bef9SDimitry Andric     // bb.2:
138723408297SDimitry Andric     //   stdux <backchain>, r1, $scratchreg
1388e8d8bef9SDimitry Andric     MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
1389e8d8bef9SDimitry Andric     MachineBasicBlock *ProbeLoopBodyMBB = MF.CreateMachineBasicBlock(ProbedBB);
1390e8d8bef9SDimitry Andric     MF.insert(MBBInsertPoint, ProbeLoopBodyMBB);
1391e8d8bef9SDimitry Andric     MachineBasicBlock *ProbeExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
1392e8d8bef9SDimitry Andric     MF.insert(MBBInsertPoint, ProbeExitMBB);
139323408297SDimitry Andric     // bb.2
139423408297SDimitry Andric     {
139523408297SDimitry Andric       Register BackChainPointer = HasRedZone ? BPReg : TempReg;
139623408297SDimitry Andric       allocateAndProbe(*ProbeExitMBB, ProbeExitMBB->end(), 0, ScratchReg, false,
139723408297SDimitry Andric                        BackChainPointer);
139823408297SDimitry Andric       if (HasRedZone)
139923408297SDimitry Andric         // PROBED_STACKALLOC_64 assumes Operand(1) stores the old sp, copy BPReg
140023408297SDimitry Andric         // to TempReg to satisfy it.
140123408297SDimitry Andric         BuildMI(*ProbeExitMBB, ProbeExitMBB->end(), DL, CopyInst, TempReg)
140223408297SDimitry Andric             .addReg(BPReg)
140323408297SDimitry Andric             .addReg(BPReg);
1404e8d8bef9SDimitry Andric       ProbeExitMBB->splice(ProbeExitMBB->end(), &MBB, MBBI, MBB.end());
1405e8d8bef9SDimitry Andric       ProbeExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);
140623408297SDimitry Andric     }
1407e8d8bef9SDimitry Andric     // bb.0
140823408297SDimitry Andric     {
140923408297SDimitry Andric       BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), ScratchReg)
1410e8d8bef9SDimitry Andric           .addReg(SPReg)
141123408297SDimitry Andric           .addReg(FinalStackPtr);
141223408297SDimitry Andric       if (!HasRedZone)
141323408297SDimitry Andric         BuildMI(&MBB, DL, CopyInst, TempReg).addReg(SPReg).addReg(SPReg);
141423408297SDimitry Andric       BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI), CRReg)
141523408297SDimitry Andric           .addReg(ScratchReg)
141623408297SDimitry Andric           .addImm(NegProbeSize);
141723408297SDimitry Andric       BuildMI(&MBB, DL, TII.get(PPC::BCC))
141823408297SDimitry Andric           .addImm(PPC::PRED_GE)
1419e8d8bef9SDimitry Andric           .addReg(CRReg)
1420e8d8bef9SDimitry Andric           .addMBB(ProbeExitMBB);
142123408297SDimitry Andric       MBB.addSuccessor(ProbeLoopBodyMBB);
142223408297SDimitry Andric       MBB.addSuccessor(ProbeExitMBB);
142323408297SDimitry Andric     }
142423408297SDimitry Andric     // bb.1
142523408297SDimitry Andric     {
142623408297SDimitry Andric       Register BackChainPointer = HasRedZone ? BPReg : TempReg;
142723408297SDimitry Andric       allocateAndProbe(*ProbeLoopBodyMBB, ProbeLoopBodyMBB->end(), NegProbeSize,
142823408297SDimitry Andric                        0, true /*UseDForm*/, BackChainPointer);
142923408297SDimitry Andric       BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::ADDI8 : PPC::ADDI),
143023408297SDimitry Andric               ScratchReg)
143123408297SDimitry Andric           .addReg(ScratchReg)
143223408297SDimitry Andric           .addImm(-NegProbeSize);
143323408297SDimitry Andric       BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI),
143423408297SDimitry Andric               CRReg)
143523408297SDimitry Andric           .addReg(ScratchReg)
143623408297SDimitry Andric           .addImm(NegProbeSize);
1437e8d8bef9SDimitry Andric       BuildMI(ProbeLoopBodyMBB, DL, TII.get(PPC::BCC))
143823408297SDimitry Andric           .addImm(PPC::PRED_LT)
1439e8d8bef9SDimitry Andric           .addReg(CRReg)
1440e8d8bef9SDimitry Andric           .addMBB(ProbeLoopBodyMBB);
1441e8d8bef9SDimitry Andric       ProbeLoopBodyMBB->addSuccessor(ProbeExitMBB);
1442e8d8bef9SDimitry Andric       ProbeLoopBodyMBB->addSuccessor(ProbeLoopBodyMBB);
144323408297SDimitry Andric     }
1444e8d8bef9SDimitry Andric     // Update liveins.
1445e8d8bef9SDimitry Andric     recomputeLiveIns(*ProbeLoopBodyMBB);
1446e8d8bef9SDimitry Andric     recomputeLiveIns(*ProbeExitMBB);
1447e8d8bef9SDimitry Andric     return ProbeExitMBB;
1448e8d8bef9SDimitry Andric   };
1449e8d8bef9SDimitry Andric   // For case HasBP && MaxAlign > 1, we have to realign the SP by performing
145023408297SDimitry Andric   // SP = SP - SP % MaxAlign, thus make the probe more like dynamic probe since
145123408297SDimitry Andric   // the offset subtracted from SP is determined by SP's runtime value.
1452e8d8bef9SDimitry Andric   if (HasBP && MaxAlign > 1) {
145323408297SDimitry Andric     // Calculate final stack pointer.
145423408297SDimitry Andric     if (isPPC64)
145523408297SDimitry Andric       BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLDICL), ScratchReg)
1456e8d8bef9SDimitry Andric           .addReg(SPReg)
145723408297SDimitry Andric           .addImm(0)
145823408297SDimitry Andric           .addImm(64 - Log2(MaxAlign));
145923408297SDimitry Andric     else
1460e8d8bef9SDimitry Andric       BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLWINM), ScratchReg)
146123408297SDimitry Andric           .addReg(SPReg)
14625ffd83dbSDimitry Andric           .addImm(0)
14635ffd83dbSDimitry Andric           .addImm(32 - Log2(MaxAlign))
14645ffd83dbSDimitry Andric           .addImm(31);
146523408297SDimitry Andric     BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF),
146623408297SDimitry Andric             FPReg)
1467590d96feSDimitry Andric         .addReg(ScratchReg)
1468590d96feSDimitry Andric         .addReg(SPReg);
146923408297SDimitry Andric     MaterializeImm(*CurrentMBB, {MI}, NegFrameSize, ScratchReg);
147023408297SDimitry Andric     BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
147123408297SDimitry Andric             FPReg)
147223408297SDimitry Andric         .addReg(ScratchReg)
147323408297SDimitry Andric         .addReg(FPReg);
147423408297SDimitry Andric     CurrentMBB = probeRealignedStack(*CurrentMBB, {MI}, ScratchReg, FPReg);
147523408297SDimitry Andric     if (needsCFI)
147623408297SDimitry Andric       buildDefCFAReg(*CurrentMBB, {MI}, FPReg);
1477e8d8bef9SDimitry Andric   } else {
1478e8d8bef9SDimitry Andric     // Initialize current frame pointer.
1479e8d8bef9SDimitry Andric     BuildMI(*CurrentMBB, {MI}, DL, CopyInst, FPReg).addReg(SPReg).addReg(SPReg);
1480e8d8bef9SDimitry Andric     // Use FPReg to calculate CFA.
1481e8d8bef9SDimitry Andric     if (needsCFI)
1482e8d8bef9SDimitry Andric       buildDefCFA(*CurrentMBB, {MI}, FPReg, 0);
14835ffd83dbSDimitry Andric     // Probe residual part.
14845ffd83dbSDimitry Andric     if (NegResidualSize) {
14855ffd83dbSDimitry Andric       bool ResidualUseDForm = CanUseDForm(NegResidualSize);
14865ffd83dbSDimitry Andric       if (!ResidualUseDForm)
1487e8d8bef9SDimitry Andric         MaterializeImm(*CurrentMBB, {MI}, NegResidualSize, ScratchReg);
1488e8d8bef9SDimitry Andric       allocateAndProbe(*CurrentMBB, {MI}, NegResidualSize, ScratchReg,
1489e8d8bef9SDimitry Andric                        ResidualUseDForm, FPReg);
14905ffd83dbSDimitry Andric     }
14915ffd83dbSDimitry Andric     bool UseDForm = CanUseDForm(NegProbeSize);
14925ffd83dbSDimitry Andric     // If number of blocks is small, just probe them directly.
14935ffd83dbSDimitry Andric     if (NumBlocks < 3) {
14945ffd83dbSDimitry Andric       if (!UseDForm)
1495e8d8bef9SDimitry Andric         MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
14965ffd83dbSDimitry Andric       for (int i = 0; i < NumBlocks; ++i)
1497e8d8bef9SDimitry Andric         allocateAndProbe(*CurrentMBB, {MI}, NegProbeSize, ScratchReg, UseDForm,
1498e8d8bef9SDimitry Andric                          FPReg);
14995ffd83dbSDimitry Andric       if (needsCFI) {
15005ffd83dbSDimitry Andric         // Restore using SPReg to calculate CFA.
1501e8d8bef9SDimitry Andric         buildDefCFAReg(*CurrentMBB, {MI}, SPReg);
15025ffd83dbSDimitry Andric       }
15035ffd83dbSDimitry Andric     } else {
15045ffd83dbSDimitry Andric       // Since CTR is a volatile register and current shrinkwrap implementation
15055ffd83dbSDimitry Andric       // won't choose an MBB in a loop as the PrologMBB, it's safe to synthesize a
15065ffd83dbSDimitry Andric       // CTR loop to probe.
15075ffd83dbSDimitry Andric       // Calculate trip count and stores it in CTRReg.
1508e8d8bef9SDimitry Andric       MaterializeImm(*CurrentMBB, {MI}, NumBlocks, ScratchReg);
1509e8d8bef9SDimitry Andric       BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::MTCTR8 : PPC::MTCTR))
15105ffd83dbSDimitry Andric           .addReg(ScratchReg, RegState::Kill);
15115ffd83dbSDimitry Andric       if (!UseDForm)
1512e8d8bef9SDimitry Andric         MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
15135ffd83dbSDimitry Andric       // Create MBBs of the loop.
15145ffd83dbSDimitry Andric       MachineFunction::iterator MBBInsertPoint =
1515e8d8bef9SDimitry Andric           std::next(CurrentMBB->getIterator());
15165ffd83dbSDimitry Andric       MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(ProbedBB);
15175ffd83dbSDimitry Andric       MF.insert(MBBInsertPoint, LoopMBB);
15185ffd83dbSDimitry Andric       MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
15195ffd83dbSDimitry Andric       MF.insert(MBBInsertPoint, ExitMBB);
15205ffd83dbSDimitry Andric       // Synthesize the loop body.
15215ffd83dbSDimitry Andric       allocateAndProbe(*LoopMBB, LoopMBB->end(), NegProbeSize, ScratchReg,
1522e8d8bef9SDimitry Andric                        UseDForm, FPReg);
15235ffd83dbSDimitry Andric       BuildMI(LoopMBB, DL, TII.get(isPPC64 ? PPC::BDNZ8 : PPC::BDNZ))
15245ffd83dbSDimitry Andric           .addMBB(LoopMBB);
15255ffd83dbSDimitry Andric       LoopMBB->addSuccessor(ExitMBB);
15265ffd83dbSDimitry Andric       LoopMBB->addSuccessor(LoopMBB);
15275ffd83dbSDimitry Andric       // Synthesize the exit MBB.
1528e8d8bef9SDimitry Andric       ExitMBB->splice(ExitMBB->end(), CurrentMBB,
15295ffd83dbSDimitry Andric                       std::next(MachineBasicBlock::iterator(MI)),
1530e8d8bef9SDimitry Andric                       CurrentMBB->end());
1531e8d8bef9SDimitry Andric       ExitMBB->transferSuccessorsAndUpdatePHIs(CurrentMBB);
1532e8d8bef9SDimitry Andric       CurrentMBB->addSuccessor(LoopMBB);
15335ffd83dbSDimitry Andric       if (needsCFI) {
15345ffd83dbSDimitry Andric         // Restore using SPReg to calculate CFA.
15355ffd83dbSDimitry Andric         buildDefCFAReg(*ExitMBB, ExitMBB->begin(), SPReg);
15365ffd83dbSDimitry Andric       }
15375ffd83dbSDimitry Andric       // Update liveins.
15385ffd83dbSDimitry Andric       recomputeLiveIns(*LoopMBB);
15395ffd83dbSDimitry Andric       recomputeLiveIns(*ExitMBB);
15405ffd83dbSDimitry Andric     }
154123408297SDimitry Andric   }
15425ffd83dbSDimitry Andric   ++NumPrologProbed;
15435ffd83dbSDimitry Andric   MI.eraseFromParent();
15445ffd83dbSDimitry Andric }
15455ffd83dbSDimitry Andric 
1546*0b57cec5SDimitry Andric void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
1547*0b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
1548*0b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1549*0b57cec5SDimitry Andric   DebugLoc dl;
1550*0b57cec5SDimitry Andric 
1551*0b57cec5SDimitry Andric   if (MBBI != MBB.end())
1552*0b57cec5SDimitry Andric     dl = MBBI->getDebugLoc();
1553*0b57cec5SDimitry Andric 
1554*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1555*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1556*0b57cec5SDimitry Andric 
1557*0b57cec5SDimitry Andric   // Get alignment info so we know how to restore the SP.
1558*0b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
1559*0b57cec5SDimitry Andric 
1560*0b57cec5SDimitry Andric   // Get the number of bytes allocated from the FrameInfo.
1561349cc55cSDimitry Andric   int64_t FrameSize = MFI.getStackSize();
1562*0b57cec5SDimitry Andric 
1563*0b57cec5SDimitry Andric   // Get processor type.
1564*0b57cec5SDimitry Andric   bool isPPC64 = Subtarget.isPPC64();
1565*0b57cec5SDimitry Andric 
1566*0b57cec5SDimitry Andric   // Check if the link register (LR) has been saved.
1567*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1568*0b57cec5SDimitry Andric   bool MustSaveLR = FI->mustSaveLR();
15695ffd83dbSDimitry Andric   const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
1570*0b57cec5SDimitry Andric   bool MustSaveCR = !MustSaveCRs.empty();
1571*0b57cec5SDimitry Andric   // Do we have a frame pointer and/or base pointer for this function?
1572*0b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
1573*0b57cec5SDimitry Andric   bool HasBP = RegInfo->hasBasePointer(MF);
1574*0b57cec5SDimitry Andric   bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
1575fe6060f1SDimitry Andric   bool HasROPProtect = Subtarget.hasROPProtect();
1576fe6060f1SDimitry Andric   bool HasPrivileged = Subtarget.hasPrivileged();
1577*0b57cec5SDimitry Andric 
15785ffd83dbSDimitry Andric   Register SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
15798bcb0991SDimitry Andric   Register BPReg = RegInfo->getBaseRegister(MF);
15805ffd83dbSDimitry Andric   Register FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
15815ffd83dbSDimitry Andric   Register ScratchReg;
15825ffd83dbSDimitry Andric   Register TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
1583*0b57cec5SDimitry Andric   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
1584*0b57cec5SDimitry Andric                                                  : PPC::MTLR );
1585*0b57cec5SDimitry Andric   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
1586*0b57cec5SDimitry Andric                                                  : PPC::LWZ );
1587*0b57cec5SDimitry Andric   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
1588*0b57cec5SDimitry Andric                                                            : PPC::LIS );
1589*0b57cec5SDimitry Andric   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
1590*0b57cec5SDimitry Andric                                               : PPC::OR );
1591*0b57cec5SDimitry Andric   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
1592*0b57cec5SDimitry Andric                                                   : PPC::ORI );
1593*0b57cec5SDimitry Andric   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
1594*0b57cec5SDimitry Andric                                                    : PPC::ADDI );
1595*0b57cec5SDimitry Andric   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
1596*0b57cec5SDimitry Andric                                                 : PPC::ADD4 );
15975ffd83dbSDimitry Andric   const MCInstrDesc& LoadWordInst = TII.get( isPPC64 ? PPC::LWZ8
15985ffd83dbSDimitry Andric                                                      : PPC::LWZ);
15995ffd83dbSDimitry Andric   const MCInstrDesc& MoveToCRInst = TII.get( isPPC64 ? PPC::MTOCRF8
16005ffd83dbSDimitry Andric                                                      : PPC::MTOCRF);
1601fe6060f1SDimitry Andric   const MCInstrDesc &HashChk =
160204eeddc0SDimitry Andric       TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHCHKP8 : PPC::HASHCHK8)
160304eeddc0SDimitry Andric                       : (HasPrivileged ? PPC::HASHCHKP : PPC::HASHCHK));
1604349cc55cSDimitry Andric   int64_t LROffset = getReturnSaveOffset();
1605*0b57cec5SDimitry Andric 
1606349cc55cSDimitry Andric   int64_t FPOffset = 0;
1607*0b57cec5SDimitry Andric 
1608*0b57cec5SDimitry Andric   // Using the same bool variable as below to suppress compiler warnings.
1609*0b57cec5SDimitry Andric   bool SingleScratchReg = findScratchRegister(&MBB, true, false, &ScratchReg,
1610*0b57cec5SDimitry Andric                                               &TempReg);
1611*0b57cec5SDimitry Andric   assert(SingleScratchReg &&
1612*0b57cec5SDimitry Andric          "Could not find an available scratch register");
1613*0b57cec5SDimitry Andric 
1614*0b57cec5SDimitry Andric   SingleScratchReg = ScratchReg == TempReg;
1615*0b57cec5SDimitry Andric 
1616*0b57cec5SDimitry Andric   if (HasFP) {
1617*0b57cec5SDimitry Andric     int FPIndex = FI->getFramePointerSaveIndex();
1618*0b57cec5SDimitry Andric     assert(FPIndex && "No Frame Pointer Save Slot!");
1619*0b57cec5SDimitry Andric     FPOffset = MFI.getObjectOffset(FPIndex);
1620*0b57cec5SDimitry Andric   }
1621*0b57cec5SDimitry Andric 
1622349cc55cSDimitry Andric   int64_t BPOffset = 0;
1623*0b57cec5SDimitry Andric   if (HasBP) {
1624*0b57cec5SDimitry Andric       int BPIndex = FI->getBasePointerSaveIndex();
1625*0b57cec5SDimitry Andric       assert(BPIndex && "No Base Pointer Save Slot!");
1626*0b57cec5SDimitry Andric       BPOffset = MFI.getObjectOffset(BPIndex);
1627*0b57cec5SDimitry Andric   }
1628*0b57cec5SDimitry Andric 
1629349cc55cSDimitry Andric   int64_t PBPOffset = 0;
1630*0b57cec5SDimitry Andric   if (FI->usesPICBase()) {
1631*0b57cec5SDimitry Andric     int PBPIndex = FI->getPICBasePointerSaveIndex();
1632*0b57cec5SDimitry Andric     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1633*0b57cec5SDimitry Andric     PBPOffset = MFI.getObjectOffset(PBPIndex);
1634*0b57cec5SDimitry Andric   }
1635*0b57cec5SDimitry Andric 
1636*0b57cec5SDimitry Andric   bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
1637*0b57cec5SDimitry Andric 
1638*0b57cec5SDimitry Andric   if (IsReturnBlock) {
1639*0b57cec5SDimitry Andric     unsigned RetOpcode = MBBI->getOpcode();
1640*0b57cec5SDimitry Andric     bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
1641*0b57cec5SDimitry Andric                       RetOpcode == PPC::TCRETURNdi ||
1642*0b57cec5SDimitry Andric                       RetOpcode == PPC::TCRETURNai ||
1643*0b57cec5SDimitry Andric                       RetOpcode == PPC::TCRETURNri8 ||
1644*0b57cec5SDimitry Andric                       RetOpcode == PPC::TCRETURNdi8 ||
1645*0b57cec5SDimitry Andric                       RetOpcode == PPC::TCRETURNai8;
1646*0b57cec5SDimitry Andric 
1647*0b57cec5SDimitry Andric     if (UsesTCRet) {
1648*0b57cec5SDimitry Andric       int MaxTCRetDelta = FI->getTailCallSPDelta();
1649*0b57cec5SDimitry Andric       MachineOperand &StackAdjust = MBBI->getOperand(1);
1650*0b57cec5SDimitry Andric       assert(StackAdjust.isImm() && "Expecting immediate value.");
1651*0b57cec5SDimitry Andric       // Adjust stack pointer.
1652*0b57cec5SDimitry Andric       int StackAdj = StackAdjust.getImm();
1653*0b57cec5SDimitry Andric       int Delta = StackAdj - MaxTCRetDelta;
1654*0b57cec5SDimitry Andric       assert((Delta >= 0) && "Delta must be positive");
1655*0b57cec5SDimitry Andric       if (MaxTCRetDelta>0)
1656*0b57cec5SDimitry Andric         FrameSize += (StackAdj +Delta);
1657*0b57cec5SDimitry Andric       else
1658*0b57cec5SDimitry Andric         FrameSize += StackAdj;
1659*0b57cec5SDimitry Andric     }
1660*0b57cec5SDimitry Andric   }
1661*0b57cec5SDimitry Andric 
1662*0b57cec5SDimitry Andric   // Frames of 32KB & larger require special handling because they cannot be
1663*0b57cec5SDimitry Andric   // indexed into with a simple LD/LWZ immediate offset operand.
1664*0b57cec5SDimitry Andric   bool isLargeFrame = !isInt<16>(FrameSize);
1665*0b57cec5SDimitry Andric 
1666*0b57cec5SDimitry Andric   // On targets without red zone, the SP needs to be restored last, so that
1667*0b57cec5SDimitry Andric   // all live contents of the stack frame are upwards of the SP. This means
1668*0b57cec5SDimitry Andric   // that we cannot restore SP just now, since there may be more registers
1669*0b57cec5SDimitry Andric   // to restore from the stack frame (e.g. R31). If the frame size is not
1670*0b57cec5SDimitry Andric   // a simple immediate value, we will need a spare register to hold the
1671*0b57cec5SDimitry Andric   // restored SP. If the frame size is known and small, we can simply adjust
1672*0b57cec5SDimitry Andric   // the offsets of the registers to be restored, and still use SP to restore
1673*0b57cec5SDimitry Andric   // them. In such case, the final update of SP will be to add the frame
1674*0b57cec5SDimitry Andric   // size to it.
1675*0b57cec5SDimitry Andric   // To simplify the code, set RBReg to the base register used to restore
1676*0b57cec5SDimitry Andric   // values from the stack, and set SPAdd to the value that needs to be added
1677*0b57cec5SDimitry Andric   // to the SP at the end. The default values are as if red zone was present.
1678*0b57cec5SDimitry Andric   unsigned RBReg = SPReg;
167981ad6265SDimitry Andric   uint64_t SPAdd = 0;
1680*0b57cec5SDimitry Andric 
1681*0b57cec5SDimitry Andric   // Check if we can move the stack update instruction up the epilogue
1682*0b57cec5SDimitry Andric   // past the callee saves. This will allow the move to LR instruction
1683*0b57cec5SDimitry Andric   // to be executed before the restores of the callee saves which means
1684*0b57cec5SDimitry Andric   // that the callee saves can hide the latency from the MTLR instrcution.
1685*0b57cec5SDimitry Andric   MachineBasicBlock::iterator StackUpdateLoc = MBBI;
1686*0b57cec5SDimitry Andric   if (stackUpdateCanBeMoved(MF)) {
1687*0b57cec5SDimitry Andric     const std::vector<CalleeSavedInfo> & Info = MFI.getCalleeSavedInfo();
1688*0b57cec5SDimitry Andric     for (CalleeSavedInfo CSI : Info) {
1689fe6060f1SDimitry Andric       // If the callee saved register is spilled to another register abort the
1690fe6060f1SDimitry Andric       // stack update movement.
1691fe6060f1SDimitry Andric       if (CSI.isSpilledToReg()) {
1692fe6060f1SDimitry Andric         StackUpdateLoc = MBBI;
1693fe6060f1SDimitry Andric         break;
1694fe6060f1SDimitry Andric       }
1695*0b57cec5SDimitry Andric       int FrIdx = CSI.getFrameIdx();
1696*0b57cec5SDimitry Andric       // If the frame index is not negative the callee saved info belongs to a
1697*0b57cec5SDimitry Andric       // stack object that is not a fixed stack object. We ignore non-fixed
1698*0b57cec5SDimitry Andric       // stack objects because we won't move the update of the stack pointer
1699*0b57cec5SDimitry Andric       // past them.
1700*0b57cec5SDimitry Andric       if (FrIdx >= 0)
1701*0b57cec5SDimitry Andric         continue;
1702*0b57cec5SDimitry Andric 
1703*0b57cec5SDimitry Andric       if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0)
1704*0b57cec5SDimitry Andric         StackUpdateLoc--;
1705*0b57cec5SDimitry Andric       else {
1706*0b57cec5SDimitry Andric         // Abort the operation as we can't update all CSR restores.
1707*0b57cec5SDimitry Andric         StackUpdateLoc = MBBI;
1708*0b57cec5SDimitry Andric         break;
1709*0b57cec5SDimitry Andric       }
1710*0b57cec5SDimitry Andric     }
1711*0b57cec5SDimitry Andric   }
1712*0b57cec5SDimitry Andric 
1713*0b57cec5SDimitry Andric   if (FrameSize) {
1714*0b57cec5SDimitry Andric     // In the prologue, the loaded (or persistent) stack pointer value is
1715*0b57cec5SDimitry Andric     // offset by the STDU/STDUX/STWU/STWUX instruction. For targets with red
1716*0b57cec5SDimitry Andric     // zone add this offset back now.
1717*0b57cec5SDimitry Andric 
1718e8d8bef9SDimitry Andric     // If the function has a base pointer, the stack pointer has been copied
1719e8d8bef9SDimitry Andric     // to it so we can restore it by copying in the other direction.
1720e8d8bef9SDimitry Andric     if (HasRedZone && HasBP) {
1721e8d8bef9SDimitry Andric       BuildMI(MBB, MBBI, dl, OrInst, RBReg).
1722e8d8bef9SDimitry Andric         addReg(BPReg).
1723e8d8bef9SDimitry Andric         addReg(BPReg);
1724e8d8bef9SDimitry Andric     }
1725*0b57cec5SDimitry Andric     // If this function contained a fastcc call and GuaranteedTailCallOpt is
1726*0b57cec5SDimitry Andric     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1727*0b57cec5SDimitry Andric     // call which invalidates the stack pointer value in SP(0). So we use the
1728e8d8bef9SDimitry Andric     // value of R31 in this case. Similar situation exists with setjmp.
1729e8d8bef9SDimitry Andric     else if (FI->hasFastCall() || MF.exposesReturnsTwice()) {
1730*0b57cec5SDimitry Andric       assert(HasFP && "Expecting a valid frame pointer.");
1731*0b57cec5SDimitry Andric       if (!HasRedZone)
1732*0b57cec5SDimitry Andric         RBReg = FPReg;
1733*0b57cec5SDimitry Andric       if (!isLargeFrame) {
1734*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, AddImmInst, RBReg)
1735*0b57cec5SDimitry Andric           .addReg(FPReg).addImm(FrameSize);
1736*0b57cec5SDimitry Andric       } else {
173781ad6265SDimitry Andric         TII.materializeImmPostRA(MBB, MBBI, dl, ScratchReg, FrameSize);
1738*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, AddInst)
1739*0b57cec5SDimitry Andric           .addReg(RBReg)
1740*0b57cec5SDimitry Andric           .addReg(FPReg)
1741*0b57cec5SDimitry Andric           .addReg(ScratchReg);
1742*0b57cec5SDimitry Andric       }
1743*0b57cec5SDimitry Andric     } else if (!isLargeFrame && !HasBP && !MFI.hasVarSizedObjects()) {
1744*0b57cec5SDimitry Andric       if (HasRedZone) {
1745*0b57cec5SDimitry Andric         BuildMI(MBB, StackUpdateLoc, dl, AddImmInst, SPReg)
1746*0b57cec5SDimitry Andric           .addReg(SPReg)
1747*0b57cec5SDimitry Andric           .addImm(FrameSize);
1748*0b57cec5SDimitry Andric       } else {
1749*0b57cec5SDimitry Andric         // Make sure that adding FrameSize will not overflow the max offset
1750*0b57cec5SDimitry Andric         // size.
1751*0b57cec5SDimitry Andric         assert(FPOffset <= 0 && BPOffset <= 0 && PBPOffset <= 0 &&
1752*0b57cec5SDimitry Andric                "Local offsets should be negative");
1753*0b57cec5SDimitry Andric         SPAdd = FrameSize;
1754*0b57cec5SDimitry Andric         FPOffset += FrameSize;
1755*0b57cec5SDimitry Andric         BPOffset += FrameSize;
1756*0b57cec5SDimitry Andric         PBPOffset += FrameSize;
1757*0b57cec5SDimitry Andric       }
1758*0b57cec5SDimitry Andric     } else {
1759*0b57cec5SDimitry Andric       // We don't want to use ScratchReg as a base register, because it
1760*0b57cec5SDimitry Andric       // could happen to be R0. Use FP instead, but make sure to preserve it.
1761*0b57cec5SDimitry Andric       if (!HasRedZone) {
1762*0b57cec5SDimitry Andric         // If FP is not saved, copy it to ScratchReg.
1763*0b57cec5SDimitry Andric         if (!HasFP)
1764*0b57cec5SDimitry Andric           BuildMI(MBB, MBBI, dl, OrInst, ScratchReg)
1765*0b57cec5SDimitry Andric             .addReg(FPReg)
1766*0b57cec5SDimitry Andric             .addReg(FPReg);
1767*0b57cec5SDimitry Andric         RBReg = FPReg;
1768*0b57cec5SDimitry Andric       }
1769*0b57cec5SDimitry Andric       BuildMI(MBB, StackUpdateLoc, dl, LoadInst, RBReg)
1770*0b57cec5SDimitry Andric         .addImm(0)
1771*0b57cec5SDimitry Andric         .addReg(SPReg);
1772*0b57cec5SDimitry Andric     }
1773*0b57cec5SDimitry Andric   }
1774*0b57cec5SDimitry Andric   assert(RBReg != ScratchReg && "Should have avoided ScratchReg");
1775*0b57cec5SDimitry Andric   // If there is no red zone, ScratchReg may be needed for holding a useful
1776*0b57cec5SDimitry Andric   // value (although not the base register). Make sure it is not overwritten
1777*0b57cec5SDimitry Andric   // too early.
1778*0b57cec5SDimitry Andric 
1779*0b57cec5SDimitry Andric   // If we need to restore both the LR and the CR and we only have one
1780*0b57cec5SDimitry Andric   // available scratch register, we must do them one at a time.
1781*0b57cec5SDimitry Andric   if (MustSaveCR && SingleScratchReg && MustSaveLR) {
1782*0b57cec5SDimitry Andric     // Here TempReg == ScratchReg, and in the absence of red zone ScratchReg
1783*0b57cec5SDimitry Andric     // is live here.
1784*0b57cec5SDimitry Andric     assert(HasRedZone && "Expecting red zone");
17855ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
17865ffd83dbSDimitry Andric       .addImm(CRSaveOffset)
1787*0b57cec5SDimitry Andric       .addReg(SPReg);
1788*0b57cec5SDimitry Andric     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
17895ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])
1790*0b57cec5SDimitry Andric         .addReg(TempReg, getKillRegState(i == e-1));
1791*0b57cec5SDimitry Andric   }
1792*0b57cec5SDimitry Andric 
1793*0b57cec5SDimitry Andric   // Delay restoring of the LR if ScratchReg is needed. This is ok, since
1794*0b57cec5SDimitry Andric   // LR is stored in the caller's stack frame. ScratchReg will be needed
1795*0b57cec5SDimitry Andric   // if RBReg is anything other than SP. We shouldn't use ScratchReg as
1796*0b57cec5SDimitry Andric   // a base register anyway, because it may happen to be R0.
1797*0b57cec5SDimitry Andric   bool LoadedLR = false;
1798*0b57cec5SDimitry Andric   if (MustSaveLR && RBReg == SPReg && isInt<16>(LROffset+SPAdd)) {
1799*0b57cec5SDimitry Andric     BuildMI(MBB, StackUpdateLoc, dl, LoadInst, ScratchReg)
1800*0b57cec5SDimitry Andric       .addImm(LROffset+SPAdd)
1801*0b57cec5SDimitry Andric       .addReg(RBReg);
1802*0b57cec5SDimitry Andric     LoadedLR = true;
1803*0b57cec5SDimitry Andric   }
1804*0b57cec5SDimitry Andric 
1805*0b57cec5SDimitry Andric   if (MustSaveCR && !(SingleScratchReg && MustSaveLR)) {
1806*0b57cec5SDimitry Andric     assert(RBReg == SPReg && "Should be using SP as a base register");
18075ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
18085ffd83dbSDimitry Andric       .addImm(CRSaveOffset)
1809*0b57cec5SDimitry Andric       .addReg(RBReg);
1810*0b57cec5SDimitry Andric   }
1811*0b57cec5SDimitry Andric 
1812*0b57cec5SDimitry Andric   if (HasFP) {
1813*0b57cec5SDimitry Andric     // If there is red zone, restore FP directly, since SP has already been
1814*0b57cec5SDimitry Andric     // restored. Otherwise, restore the value of FP into ScratchReg.
1815*0b57cec5SDimitry Andric     if (HasRedZone || RBReg == SPReg)
1816*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1817*0b57cec5SDimitry Andric         .addImm(FPOffset)
1818*0b57cec5SDimitry Andric         .addReg(SPReg);
1819*0b57cec5SDimitry Andric     else
1820*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1821*0b57cec5SDimitry Andric         .addImm(FPOffset)
1822*0b57cec5SDimitry Andric         .addReg(RBReg);
1823*0b57cec5SDimitry Andric   }
1824*0b57cec5SDimitry Andric 
1825*0b57cec5SDimitry Andric   if (FI->usesPICBase())
1826*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, LoadInst, PPC::R30)
1827*0b57cec5SDimitry Andric       .addImm(PBPOffset)
1828*0b57cec5SDimitry Andric       .addReg(RBReg);
1829*0b57cec5SDimitry Andric 
1830*0b57cec5SDimitry Andric   if (HasBP)
1831*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1832*0b57cec5SDimitry Andric       .addImm(BPOffset)
1833*0b57cec5SDimitry Andric       .addReg(RBReg);
1834*0b57cec5SDimitry Andric 
1835*0b57cec5SDimitry Andric   // There is nothing more to be loaded from the stack, so now we can
1836*0b57cec5SDimitry Andric   // restore SP: SP = RBReg + SPAdd.
1837*0b57cec5SDimitry Andric   if (RBReg != SPReg || SPAdd != 0) {
1838*0b57cec5SDimitry Andric     assert(!HasRedZone && "This should not happen with red zone");
1839*0b57cec5SDimitry Andric     // If SPAdd is 0, generate a copy.
1840*0b57cec5SDimitry Andric     if (SPAdd == 0)
1841*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, OrInst, SPReg)
1842*0b57cec5SDimitry Andric         .addReg(RBReg)
1843*0b57cec5SDimitry Andric         .addReg(RBReg);
1844*0b57cec5SDimitry Andric     else
1845*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1846*0b57cec5SDimitry Andric         .addReg(RBReg)
1847*0b57cec5SDimitry Andric         .addImm(SPAdd);
1848*0b57cec5SDimitry Andric 
1849*0b57cec5SDimitry Andric     assert(RBReg != ScratchReg && "Should be using FP or SP as base register");
1850*0b57cec5SDimitry Andric     if (RBReg == FPReg)
1851*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, OrInst, FPReg)
1852*0b57cec5SDimitry Andric         .addReg(ScratchReg)
1853*0b57cec5SDimitry Andric         .addReg(ScratchReg);
1854*0b57cec5SDimitry Andric 
1855*0b57cec5SDimitry Andric     // Now load the LR from the caller's stack frame.
1856*0b57cec5SDimitry Andric     if (MustSaveLR && !LoadedLR)
1857*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1858*0b57cec5SDimitry Andric         .addImm(LROffset)
1859*0b57cec5SDimitry Andric         .addReg(SPReg);
1860*0b57cec5SDimitry Andric   }
1861*0b57cec5SDimitry Andric 
1862*0b57cec5SDimitry Andric   if (MustSaveCR &&
18635ffd83dbSDimitry Andric       !(SingleScratchReg && MustSaveLR))
1864*0b57cec5SDimitry Andric     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
18655ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])
1866*0b57cec5SDimitry Andric         .addReg(TempReg, getKillRegState(i == e-1));
1867*0b57cec5SDimitry Andric 
1868fe6060f1SDimitry Andric   if (MustSaveLR) {
1869fe6060f1SDimitry Andric     // If ROP protection is required, an extra instruction is added to compute a
1870fe6060f1SDimitry Andric     // hash and then compare it to the hash stored in the prologue.
1871fe6060f1SDimitry Andric     if (HasROPProtect) {
1872fe6060f1SDimitry Andric       const int SaveIndex = FI->getROPProtectionHashSaveIndex();
1873349cc55cSDimitry Andric       const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
1874fe6060f1SDimitry Andric       assert((ImmOffset <= -8 && ImmOffset >= -512) &&
1875fe6060f1SDimitry Andric              "ROP hash check location offset out of range.");
1876fe6060f1SDimitry Andric       assert(((ImmOffset & 0x7) == 0) &&
1877fe6060f1SDimitry Andric              "ROP hash check location offset must be 8 byte aligned.");
1878fe6060f1SDimitry Andric       BuildMI(MBB, StackUpdateLoc, dl, HashChk)
1879fe6060f1SDimitry Andric           .addReg(ScratchReg)
1880fe6060f1SDimitry Andric           .addImm(ImmOffset)
1881fe6060f1SDimitry Andric           .addReg(SPReg);
1882fe6060f1SDimitry Andric     }
1883*0b57cec5SDimitry Andric     BuildMI(MBB, StackUpdateLoc, dl, MTLRInst).addReg(ScratchReg);
1884fe6060f1SDimitry Andric   }
1885*0b57cec5SDimitry Andric 
1886*0b57cec5SDimitry Andric   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1887*0b57cec5SDimitry Andric   // call optimization
1888*0b57cec5SDimitry Andric   if (IsReturnBlock) {
1889*0b57cec5SDimitry Andric     unsigned RetOpcode = MBBI->getOpcode();
1890*0b57cec5SDimitry Andric     if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1891*0b57cec5SDimitry Andric         (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1892*0b57cec5SDimitry Andric         MF.getFunction().getCallingConv() == CallingConv::Fast) {
1893*0b57cec5SDimitry Andric       PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1894*0b57cec5SDimitry Andric       unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1895*0b57cec5SDimitry Andric 
1896*0b57cec5SDimitry Andric       if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1897*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1898*0b57cec5SDimitry Andric           .addReg(SPReg).addImm(CallerAllocatedAmt);
1899*0b57cec5SDimitry Andric       } else {
1900*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1901*0b57cec5SDimitry Andric           .addImm(CallerAllocatedAmt >> 16);
1902*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1903*0b57cec5SDimitry Andric           .addReg(ScratchReg, RegState::Kill)
1904*0b57cec5SDimitry Andric           .addImm(CallerAllocatedAmt & 0xFFFF);
1905*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, AddInst)
1906*0b57cec5SDimitry Andric           .addReg(SPReg)
1907*0b57cec5SDimitry Andric           .addReg(FPReg)
1908*0b57cec5SDimitry Andric           .addReg(ScratchReg);
1909*0b57cec5SDimitry Andric       }
1910*0b57cec5SDimitry Andric     } else {
1911*0b57cec5SDimitry Andric       createTailCallBranchInstr(MBB);
1912*0b57cec5SDimitry Andric     }
1913*0b57cec5SDimitry Andric   }
1914*0b57cec5SDimitry Andric }
1915*0b57cec5SDimitry Andric 
1916*0b57cec5SDimitry Andric void PPCFrameLowering::createTailCallBranchInstr(MachineBasicBlock &MBB) const {
1917*0b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1918*0b57cec5SDimitry Andric 
1919*0b57cec5SDimitry Andric   // If we got this far a first terminator should exist.
1920*0b57cec5SDimitry Andric   assert(MBBI != MBB.end() && "Failed to find the first terminator.");
1921*0b57cec5SDimitry Andric 
1922*0b57cec5SDimitry Andric   DebugLoc dl = MBBI->getDebugLoc();
1923*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1924*0b57cec5SDimitry Andric 
19255ffd83dbSDimitry Andric   // Create branch instruction for pseudo tail call return instruction.
19265ffd83dbSDimitry Andric   // The TCRETURNdi variants are direct calls. Valid targets for those are
19275ffd83dbSDimitry Andric   // MO_GlobalAddress operands as well as MO_ExternalSymbol with PC-Rel
19285ffd83dbSDimitry Andric   // since we can tail call external functions with PC-Rel (i.e. we don't need
19295ffd83dbSDimitry Andric   // to worry about different TOC pointers). Some of the external functions will
19305ffd83dbSDimitry Andric   // be MO_GlobalAddress while others like memcpy for example, are going to
19315ffd83dbSDimitry Andric   // be MO_ExternalSymbol.
1932*0b57cec5SDimitry Andric   unsigned RetOpcode = MBBI->getOpcode();
1933*0b57cec5SDimitry Andric   if (RetOpcode == PPC::TCRETURNdi) {
1934*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1935*0b57cec5SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
19365ffd83dbSDimitry Andric     if (JumpTarget.isGlobal())
1937*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1938*0b57cec5SDimitry Andric         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
19395ffd83dbSDimitry Andric     else if (JumpTarget.isSymbol())
19405ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
19415ffd83dbSDimitry Andric         addExternalSymbol(JumpTarget.getSymbolName());
19425ffd83dbSDimitry Andric     else
19435ffd83dbSDimitry Andric       llvm_unreachable("Expecting Global or External Symbol");
1944*0b57cec5SDimitry Andric   } else if (RetOpcode == PPC::TCRETURNri) {
1945*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1946*0b57cec5SDimitry Andric     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1947*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1948*0b57cec5SDimitry Andric   } else if (RetOpcode == PPC::TCRETURNai) {
1949*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1950*0b57cec5SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
1951*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1952*0b57cec5SDimitry Andric   } else if (RetOpcode == PPC::TCRETURNdi8) {
1953*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1954*0b57cec5SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
19555ffd83dbSDimitry Andric     if (JumpTarget.isGlobal())
1956*0b57cec5SDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1957*0b57cec5SDimitry Andric         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
19585ffd83dbSDimitry Andric     else if (JumpTarget.isSymbol())
19595ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
19605ffd83dbSDimitry Andric         addExternalSymbol(JumpTarget.getSymbolName());
19615ffd83dbSDimitry Andric     else
19625ffd83dbSDimitry Andric       llvm_unreachable("Expecting Global or External Symbol");
1963*0b57cec5SDimitry Andric   } else if (RetOpcode == PPC::TCRETURNri8) {
1964*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1965*0b57cec5SDimitry Andric     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1966*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1967*0b57cec5SDimitry Andric   } else if (RetOpcode == PPC::TCRETURNai8) {
1968*0b57cec5SDimitry Andric     MBBI = MBB.getLastNonDebugInstr();
1969*0b57cec5SDimitry Andric     MachineOperand &JumpTarget = MBBI->getOperand(0);
1970*0b57cec5SDimitry Andric     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1971*0b57cec5SDimitry Andric   }
1972*0b57cec5SDimitry Andric }
1973*0b57cec5SDimitry Andric 
1974*0b57cec5SDimitry Andric void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,
1975*0b57cec5SDimitry Andric                                             BitVector &SavedRegs,
1976*0b57cec5SDimitry Andric                                             RegScavenger *RS) const {
1977*0b57cec5SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1978*0b57cec5SDimitry Andric 
1979*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1980*0b57cec5SDimitry Andric 
198181ad6265SDimitry Andric   // Do not explicitly save the callee saved VSRp registers.
198281ad6265SDimitry Andric   // The individual VSR subregisters will be saved instead.
198381ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp26);
198481ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp27);
198581ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp28);
198681ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp29);
198781ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp30);
198881ad6265SDimitry Andric   SavedRegs.reset(PPC::VSRp31);
198981ad6265SDimitry Andric 
1990*0b57cec5SDimitry Andric   //  Save and clear the LR state.
1991*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1992*0b57cec5SDimitry Andric   unsigned LR = RegInfo->getRARegister();
1993*0b57cec5SDimitry Andric   FI->setMustSaveLR(MustSaveLR(MF, LR));
1994*0b57cec5SDimitry Andric   SavedRegs.reset(LR);
1995*0b57cec5SDimitry Andric 
1996*0b57cec5SDimitry Andric   //  Save R31 if necessary
1997*0b57cec5SDimitry Andric   int FPSI = FI->getFramePointerSaveIndex();
19988bcb0991SDimitry Andric   const bool isPPC64 = Subtarget.isPPC64();
1999*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
2000*0b57cec5SDimitry Andric 
2001*0b57cec5SDimitry Andric   // If the frame pointer save index hasn't been defined yet.
2002*0b57cec5SDimitry Andric   if (!FPSI && needsFP(MF)) {
2003*0b57cec5SDimitry Andric     // Find out what the fix offset of the frame pointer save area.
2004*0b57cec5SDimitry Andric     int FPOffset = getFramePointerSaveOffset();
2005*0b57cec5SDimitry Andric     // Allocate the frame index for frame pointer save area.
2006*0b57cec5SDimitry Andric     FPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
2007*0b57cec5SDimitry Andric     // Save the result.
2008*0b57cec5SDimitry Andric     FI->setFramePointerSaveIndex(FPSI);
2009*0b57cec5SDimitry Andric   }
2010*0b57cec5SDimitry Andric 
2011*0b57cec5SDimitry Andric   int BPSI = FI->getBasePointerSaveIndex();
2012*0b57cec5SDimitry Andric   if (!BPSI && RegInfo->hasBasePointer(MF)) {
2013*0b57cec5SDimitry Andric     int BPOffset = getBasePointerSaveOffset();
2014*0b57cec5SDimitry Andric     // Allocate the frame index for the base pointer save area.
2015*0b57cec5SDimitry Andric     BPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
2016*0b57cec5SDimitry Andric     // Save the result.
2017*0b57cec5SDimitry Andric     FI->setBasePointerSaveIndex(BPSI);
2018*0b57cec5SDimitry Andric   }
2019*0b57cec5SDimitry Andric 
2020*0b57cec5SDimitry Andric   // Reserve stack space for the PIC Base register (R30).
2021*0b57cec5SDimitry Andric   // Only used in SVR4 32-bit.
2022*0b57cec5SDimitry Andric   if (FI->usesPICBase()) {
2023*0b57cec5SDimitry Andric     int PBPSI = MFI.CreateFixedObject(4, -8, true);
2024*0b57cec5SDimitry Andric     FI->setPICBasePointerSaveIndex(PBPSI);
2025*0b57cec5SDimitry Andric   }
2026*0b57cec5SDimitry Andric 
2027*0b57cec5SDimitry Andric   // Make sure we don't explicitly spill r31, because, for example, we have
2028*0b57cec5SDimitry Andric   // some inline asm which explicitly clobbers it, when we otherwise have a
2029*0b57cec5SDimitry Andric   // frame pointer and are using r31's spill slot for the prologue/epilogue
2030*0b57cec5SDimitry Andric   // code. Same goes for the base pointer and the PIC base register.
2031*0b57cec5SDimitry Andric   if (needsFP(MF))
2032*0b57cec5SDimitry Andric     SavedRegs.reset(isPPC64 ? PPC::X31 : PPC::R31);
2033*0b57cec5SDimitry Andric   if (RegInfo->hasBasePointer(MF))
2034*0b57cec5SDimitry Andric     SavedRegs.reset(RegInfo->getBaseRegister(MF));
2035*0b57cec5SDimitry Andric   if (FI->usesPICBase())
2036*0b57cec5SDimitry Andric     SavedRegs.reset(PPC::R30);
2037*0b57cec5SDimitry Andric 
2038*0b57cec5SDimitry Andric   // Reserve stack space to move the linkage area to in case of a tail call.
2039*0b57cec5SDimitry Andric   int TCSPDelta = 0;
2040*0b57cec5SDimitry Andric   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2041*0b57cec5SDimitry Andric       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
2042*0b57cec5SDimitry Andric     MFI.CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
2043*0b57cec5SDimitry Andric   }
2044*0b57cec5SDimitry Andric 
20455ffd83dbSDimitry Andric   // Allocate the nonvolatile CR spill slot iff the function uses CR 2, 3, or 4.
20465ffd83dbSDimitry Andric   // For 64-bit SVR4, and all flavors of AIX we create a FixedStack
20475ffd83dbSDimitry Andric   // object at the offset of the CR-save slot in the linkage area. The actual
20485ffd83dbSDimitry Andric   // save and restore of the condition register will be created as part of the
20495ffd83dbSDimitry Andric   // prologue and epilogue insertion, but the FixedStack object is needed to
20505ffd83dbSDimitry Andric   // keep the CalleSavedInfo valid.
20515ffd83dbSDimitry Andric   if ((SavedRegs.test(PPC::CR2) || SavedRegs.test(PPC::CR3) ||
2052*0b57cec5SDimitry Andric        SavedRegs.test(PPC::CR4))) {
20535ffd83dbSDimitry Andric     const uint64_t SpillSize = 4; // Condition register is always 4 bytes.
20545ffd83dbSDimitry Andric     const int64_t SpillOffset =
20555ffd83dbSDimitry Andric         Subtarget.isPPC64() ? 8 : Subtarget.isAIXABI() ? 4 : -4;
20565ffd83dbSDimitry Andric     int FrameIdx =
20575ffd83dbSDimitry Andric         MFI.CreateFixedObject(SpillSize, SpillOffset,
20585ffd83dbSDimitry Andric                               /* IsImmutable */ true, /* IsAliased */ false);
2059*0b57cec5SDimitry Andric     FI->setCRSpillFrameIndex(FrameIdx);
2060*0b57cec5SDimitry Andric   }
2061*0b57cec5SDimitry Andric }
2062*0b57cec5SDimitry Andric 
2063*0b57cec5SDimitry Andric void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
2064*0b57cec5SDimitry Andric                                                        RegScavenger *RS) const {
2065*0b57cec5SDimitry Andric   // Get callee saved register information.
2066*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
2067*0b57cec5SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2068*0b57cec5SDimitry Andric 
2069*0b57cec5SDimitry Andric   // If the function is shrink-wrapped, and if the function has a tail call, the
2070*0b57cec5SDimitry Andric   // tail call might not be in the new RestoreBlock, so real branch instruction
2071*0b57cec5SDimitry Andric   // won't be generated by emitEpilogue(), because shrink-wrap has chosen new
2072*0b57cec5SDimitry Andric   // RestoreBlock. So we handle this case here.
2073*0b57cec5SDimitry Andric   if (MFI.getSavePoint() && MFI.hasTailCall()) {
2074*0b57cec5SDimitry Andric     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
2075*0b57cec5SDimitry Andric     for (MachineBasicBlock &MBB : MF) {
2076*0b57cec5SDimitry Andric       if (MBB.isReturnBlock() && (&MBB) != RestoreBlock)
2077*0b57cec5SDimitry Andric         createTailCallBranchInstr(MBB);
2078*0b57cec5SDimitry Andric     }
2079*0b57cec5SDimitry Andric   }
2080*0b57cec5SDimitry Andric 
2081*0b57cec5SDimitry Andric   // Early exit if no callee saved registers are modified!
2082*0b57cec5SDimitry Andric   if (CSI.empty() && !needsFP(MF)) {
2083*0b57cec5SDimitry Andric     addScavengingSpillSlot(MF, RS);
2084*0b57cec5SDimitry Andric     return;
2085*0b57cec5SDimitry Andric   }
2086*0b57cec5SDimitry Andric 
2087*0b57cec5SDimitry Andric   unsigned MinGPR = PPC::R31;
2088*0b57cec5SDimitry Andric   unsigned MinG8R = PPC::X31;
2089*0b57cec5SDimitry Andric   unsigned MinFPR = PPC::F31;
2090*0b57cec5SDimitry Andric   unsigned MinVR = Subtarget.hasSPE() ? PPC::S31 : PPC::V31;
2091*0b57cec5SDimitry Andric 
2092*0b57cec5SDimitry Andric   bool HasGPSaveArea = false;
2093*0b57cec5SDimitry Andric   bool HasG8SaveArea = false;
2094*0b57cec5SDimitry Andric   bool HasFPSaveArea = false;
2095*0b57cec5SDimitry Andric   bool HasVRSaveArea = false;
2096*0b57cec5SDimitry Andric 
2097*0b57cec5SDimitry Andric   SmallVector<CalleeSavedInfo, 18> GPRegs;
2098*0b57cec5SDimitry Andric   SmallVector<CalleeSavedInfo, 18> G8Regs;
2099*0b57cec5SDimitry Andric   SmallVector<CalleeSavedInfo, 18> FPRegs;
2100*0b57cec5SDimitry Andric   SmallVector<CalleeSavedInfo, 18> VRegs;
2101*0b57cec5SDimitry Andric 
21024824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
210304eeddc0SDimitry Andric     Register Reg = I.getReg();
2104*0b57cec5SDimitry Andric     assert((!MF.getInfo<PPCFunctionInfo>()->mustSaveTOC() ||
2105*0b57cec5SDimitry Andric             (Reg != PPC::X2 && Reg != PPC::R2)) &&
2106*0b57cec5SDimitry Andric            "Not expecting to try to spill R2 in a function that must save TOC");
21078bcb0991SDimitry Andric     if (PPC::GPRCRegClass.contains(Reg)) {
2108*0b57cec5SDimitry Andric       HasGPSaveArea = true;
2109*0b57cec5SDimitry Andric 
21104824e7fdSDimitry Andric       GPRegs.push_back(I);
2111*0b57cec5SDimitry Andric 
2112*0b57cec5SDimitry Andric       if (Reg < MinGPR) {
2113*0b57cec5SDimitry Andric         MinGPR = Reg;
2114*0b57cec5SDimitry Andric       }
2115*0b57cec5SDimitry Andric     } else if (PPC::G8RCRegClass.contains(Reg)) {
2116*0b57cec5SDimitry Andric       HasG8SaveArea = true;
2117*0b57cec5SDimitry Andric 
21184824e7fdSDimitry Andric       G8Regs.push_back(I);
2119*0b57cec5SDimitry Andric 
2120*0b57cec5SDimitry Andric       if (Reg < MinG8R) {
2121*0b57cec5SDimitry Andric         MinG8R = Reg;
2122*0b57cec5SDimitry Andric       }
2123*0b57cec5SDimitry Andric     } else if (PPC::F8RCRegClass.contains(Reg)) {
2124*0b57cec5SDimitry Andric       HasFPSaveArea = true;
2125*0b57cec5SDimitry Andric 
21264824e7fdSDimitry Andric       FPRegs.push_back(I);
2127*0b57cec5SDimitry Andric 
2128*0b57cec5SDimitry Andric       if (Reg < MinFPR) {
2129*0b57cec5SDimitry Andric         MinFPR = Reg;
2130*0b57cec5SDimitry Andric       }
2131*0b57cec5SDimitry Andric     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
2132*0b57cec5SDimitry Andric                PPC::CRRCRegClass.contains(Reg)) {
2133*0b57cec5SDimitry Andric       ; // do nothing, as we already know whether CRs are spilled
2134*0b57cec5SDimitry Andric     } else if (PPC::VRRCRegClass.contains(Reg) ||
2135*0b57cec5SDimitry Andric                PPC::SPERCRegClass.contains(Reg)) {
2136*0b57cec5SDimitry Andric       // Altivec and SPE are mutually exclusive, but have the same stack
2137*0b57cec5SDimitry Andric       // alignment requirements, so overload the save area for both cases.
2138*0b57cec5SDimitry Andric       HasVRSaveArea = true;
2139*0b57cec5SDimitry Andric 
21404824e7fdSDimitry Andric       VRegs.push_back(I);
2141*0b57cec5SDimitry Andric 
2142*0b57cec5SDimitry Andric       if (Reg < MinVR) {
2143*0b57cec5SDimitry Andric         MinVR = Reg;
2144*0b57cec5SDimitry Andric       }
2145*0b57cec5SDimitry Andric     } else {
2146*0b57cec5SDimitry Andric       llvm_unreachable("Unknown RegisterClass!");
2147*0b57cec5SDimitry Andric     }
2148*0b57cec5SDimitry Andric   }
2149*0b57cec5SDimitry Andric 
2150*0b57cec5SDimitry Andric   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
2151*0b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2152*0b57cec5SDimitry Andric 
2153*0b57cec5SDimitry Andric   int64_t LowerBound = 0;
2154*0b57cec5SDimitry Andric 
2155*0b57cec5SDimitry Andric   // Take into account stack space reserved for tail calls.
2156*0b57cec5SDimitry Andric   int TCSPDelta = 0;
2157*0b57cec5SDimitry Andric   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2158*0b57cec5SDimitry Andric       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
2159*0b57cec5SDimitry Andric     LowerBound = TCSPDelta;
2160*0b57cec5SDimitry Andric   }
2161*0b57cec5SDimitry Andric 
2162*0b57cec5SDimitry Andric   // The Floating-point register save area is right below the back chain word
2163*0b57cec5SDimitry Andric   // of the previous stack frame.
2164*0b57cec5SDimitry Andric   if (HasFPSaveArea) {
2165*0b57cec5SDimitry Andric     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
2166*0b57cec5SDimitry Andric       int FI = FPRegs[i].getFrameIdx();
2167*0b57cec5SDimitry Andric 
2168*0b57cec5SDimitry Andric       MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2169*0b57cec5SDimitry Andric     }
2170*0b57cec5SDimitry Andric 
2171*0b57cec5SDimitry Andric     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
2172*0b57cec5SDimitry Andric   }
2173*0b57cec5SDimitry Andric 
2174*0b57cec5SDimitry Andric   // Check whether the frame pointer register is allocated. If so, make sure it
2175*0b57cec5SDimitry Andric   // is spilled to the correct offset.
2176*0b57cec5SDimitry Andric   if (needsFP(MF)) {
2177*0b57cec5SDimitry Andric     int FI = PFI->getFramePointerSaveIndex();
2178*0b57cec5SDimitry Andric     assert(FI && "No Frame Pointer Save Slot!");
2179*0b57cec5SDimitry Andric     MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2180*0b57cec5SDimitry Andric     // FP is R31/X31, so no need to update MinGPR/MinG8R.
2181*0b57cec5SDimitry Andric     HasGPSaveArea = true;
2182*0b57cec5SDimitry Andric   }
2183*0b57cec5SDimitry Andric 
2184*0b57cec5SDimitry Andric   if (PFI->usesPICBase()) {
2185*0b57cec5SDimitry Andric     int FI = PFI->getPICBasePointerSaveIndex();
2186*0b57cec5SDimitry Andric     assert(FI && "No PIC Base Pointer Save Slot!");
2187*0b57cec5SDimitry Andric     MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2188*0b57cec5SDimitry Andric 
2189*0b57cec5SDimitry Andric     MinGPR = std::min<unsigned>(MinGPR, PPC::R30);
2190*0b57cec5SDimitry Andric     HasGPSaveArea = true;
2191*0b57cec5SDimitry Andric   }
2192*0b57cec5SDimitry Andric 
2193*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2194*0b57cec5SDimitry Andric   if (RegInfo->hasBasePointer(MF)) {
2195*0b57cec5SDimitry Andric     int FI = PFI->getBasePointerSaveIndex();
2196*0b57cec5SDimitry Andric     assert(FI && "No Base Pointer Save Slot!");
2197*0b57cec5SDimitry Andric     MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2198*0b57cec5SDimitry Andric 
21998bcb0991SDimitry Andric     Register BP = RegInfo->getBaseRegister(MF);
2200*0b57cec5SDimitry Andric     if (PPC::G8RCRegClass.contains(BP)) {
2201*0b57cec5SDimitry Andric       MinG8R = std::min<unsigned>(MinG8R, BP);
2202*0b57cec5SDimitry Andric       HasG8SaveArea = true;
2203*0b57cec5SDimitry Andric     } else if (PPC::GPRCRegClass.contains(BP)) {
2204*0b57cec5SDimitry Andric       MinGPR = std::min<unsigned>(MinGPR, BP);
2205*0b57cec5SDimitry Andric       HasGPSaveArea = true;
2206*0b57cec5SDimitry Andric     }
2207*0b57cec5SDimitry Andric   }
2208*0b57cec5SDimitry Andric 
2209*0b57cec5SDimitry Andric   // General register save area starts right below the Floating-point
2210*0b57cec5SDimitry Andric   // register save area.
2211*0b57cec5SDimitry Andric   if (HasGPSaveArea || HasG8SaveArea) {
2212*0b57cec5SDimitry Andric     // Move general register save area spill slots down, taking into account
2213*0b57cec5SDimitry Andric     // the size of the Floating-point register save area.
2214*0b57cec5SDimitry Andric     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
2215*0b57cec5SDimitry Andric       if (!GPRegs[i].isSpilledToReg()) {
2216*0b57cec5SDimitry Andric         int FI = GPRegs[i].getFrameIdx();
2217*0b57cec5SDimitry Andric         MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2218*0b57cec5SDimitry Andric       }
2219*0b57cec5SDimitry Andric     }
2220*0b57cec5SDimitry Andric 
2221*0b57cec5SDimitry Andric     // Move general register save area spill slots down, taking into account
2222*0b57cec5SDimitry Andric     // the size of the Floating-point register save area.
2223*0b57cec5SDimitry Andric     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
2224*0b57cec5SDimitry Andric       if (!G8Regs[i].isSpilledToReg()) {
2225*0b57cec5SDimitry Andric         int FI = G8Regs[i].getFrameIdx();
2226*0b57cec5SDimitry Andric         MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2227*0b57cec5SDimitry Andric       }
2228*0b57cec5SDimitry Andric     }
2229*0b57cec5SDimitry Andric 
2230*0b57cec5SDimitry Andric     unsigned MinReg =
2231*0b57cec5SDimitry Andric       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
2232*0b57cec5SDimitry Andric                          TRI->getEncodingValue(MinG8R));
2233*0b57cec5SDimitry Andric 
22345ffd83dbSDimitry Andric     const unsigned GPRegSize = Subtarget.isPPC64() ? 8 : 4;
22355ffd83dbSDimitry Andric     LowerBound -= (31 - MinReg + 1) * GPRegSize;
2236*0b57cec5SDimitry Andric   }
2237*0b57cec5SDimitry Andric 
2238*0b57cec5SDimitry Andric   // For 32-bit only, the CR save area is below the general register
2239*0b57cec5SDimitry Andric   // save area.  For 64-bit SVR4, the CR save area is addressed relative
2240*0b57cec5SDimitry Andric   // to the stack pointer and hence does not need an adjustment here.
2241*0b57cec5SDimitry Andric   // Only CR2 (the first nonvolatile spilled) has an associated frame
2242*0b57cec5SDimitry Andric   // index so that we have a single uniform save area.
22435ffd83dbSDimitry Andric   if (spillsCR(MF) && Subtarget.is32BitELFABI()) {
2244*0b57cec5SDimitry Andric     // Adjust the frame index of the CR spill slot.
22455ffd83dbSDimitry Andric     for (const auto &CSInfo : CSI) {
22465ffd83dbSDimitry Andric       if (CSInfo.getReg() == PPC::CR2) {
22475ffd83dbSDimitry Andric         int FI = CSInfo.getFrameIdx();
2248*0b57cec5SDimitry Andric         MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
22495ffd83dbSDimitry Andric         break;
2250*0b57cec5SDimitry Andric       }
2251*0b57cec5SDimitry Andric     }
2252*0b57cec5SDimitry Andric 
2253*0b57cec5SDimitry Andric     LowerBound -= 4; // The CR save area is always 4 bytes long.
2254*0b57cec5SDimitry Andric   }
2255*0b57cec5SDimitry Andric 
2256*0b57cec5SDimitry Andric   // Both Altivec and SPE have the same alignment and padding requirements
2257*0b57cec5SDimitry Andric   // within the stack frame.
2258*0b57cec5SDimitry Andric   if (HasVRSaveArea) {
2259*0b57cec5SDimitry Andric     // Insert alignment padding, we need 16-byte alignment. Note: for positive
2260*0b57cec5SDimitry Andric     // number the alignment formula is : y = (x + (n-1)) & (~(n-1)). But since
2261*0b57cec5SDimitry Andric     // we are using negative number here (the stack grows downward). We should
2262*0b57cec5SDimitry Andric     // use formula : y = x & (~(n-1)). Where x is the size before aligning, n
2263*0b57cec5SDimitry Andric     // is the alignment size ( n = 16 here) and y is the size after aligning.
2264*0b57cec5SDimitry Andric     assert(LowerBound <= 0 && "Expect LowerBound have a non-positive value!");
2265*0b57cec5SDimitry Andric     LowerBound &= ~(15);
2266*0b57cec5SDimitry Andric 
2267*0b57cec5SDimitry Andric     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
2268*0b57cec5SDimitry Andric       int FI = VRegs[i].getFrameIdx();
2269*0b57cec5SDimitry Andric 
2270*0b57cec5SDimitry Andric       MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
2271*0b57cec5SDimitry Andric     }
2272*0b57cec5SDimitry Andric   }
2273*0b57cec5SDimitry Andric 
2274*0b57cec5SDimitry Andric   addScavengingSpillSlot(MF, RS);
2275*0b57cec5SDimitry Andric }
2276*0b57cec5SDimitry Andric 
2277*0b57cec5SDimitry Andric void
2278*0b57cec5SDimitry Andric PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
2279*0b57cec5SDimitry Andric                                          RegScavenger *RS) const {
2280*0b57cec5SDimitry Andric   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
2281*0b57cec5SDimitry Andric   // a large stack, which will require scavenging a register to materialize a
2282*0b57cec5SDimitry Andric   // large offset.
2283*0b57cec5SDimitry Andric 
2284*0b57cec5SDimitry Andric   // We need to have a scavenger spill slot for spills if the frame size is
2285*0b57cec5SDimitry Andric   // large. In case there is no free register for large-offset addressing,
2286*0b57cec5SDimitry Andric   // this slot is used for the necessary emergency spill. Also, we need the
2287*0b57cec5SDimitry Andric   // slot for dynamic stack allocations.
2288*0b57cec5SDimitry Andric 
2289*0b57cec5SDimitry Andric   // The scavenger might be invoked if the frame offset does not fit into
2290*0b57cec5SDimitry Andric   // the 16-bit immediate. We don't know the complete frame size here
2291*0b57cec5SDimitry Andric   // because we've not yet computed callee-saved register spills or the
2292*0b57cec5SDimitry Andric   // needed alignment padding.
2293*0b57cec5SDimitry Andric   unsigned StackSize = determineFrameLayout(MF, true);
2294*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
2295e8d8bef9SDimitry Andric   if (MFI.hasVarSizedObjects() || spillsCR(MF) || hasNonRISpills(MF) ||
2296e8d8bef9SDimitry Andric       (hasSpills(MF) && !isInt<16>(StackSize))) {
2297*0b57cec5SDimitry Andric     const TargetRegisterClass &GPRC = PPC::GPRCRegClass;
2298*0b57cec5SDimitry Andric     const TargetRegisterClass &G8RC = PPC::G8RCRegClass;
2299*0b57cec5SDimitry Andric     const TargetRegisterClass &RC = Subtarget.isPPC64() ? G8RC : GPRC;
2300*0b57cec5SDimitry Andric     const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
2301*0b57cec5SDimitry Andric     unsigned Size = TRI.getSpillSize(RC);
23025ffd83dbSDimitry Andric     Align Alignment = TRI.getSpillAlign(RC);
23035ffd83dbSDimitry Andric     RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Alignment, false));
2304*0b57cec5SDimitry Andric 
2305*0b57cec5SDimitry Andric     // Might we have over-aligned allocas?
23065ffd83dbSDimitry Andric     bool HasAlVars =
23075ffd83dbSDimitry Andric         MFI.hasVarSizedObjects() && MFI.getMaxAlign() > getStackAlign();
2308*0b57cec5SDimitry Andric 
2309*0b57cec5SDimitry Andric     // These kinds of spills might need two registers.
2310e8d8bef9SDimitry Andric     if (spillsCR(MF) || HasAlVars)
23115ffd83dbSDimitry Andric       RS->addScavengingFrameIndex(
23125ffd83dbSDimitry Andric           MFI.CreateStackObject(Size, Alignment, false));
2313*0b57cec5SDimitry Andric   }
2314*0b57cec5SDimitry Andric }
2315*0b57cec5SDimitry Andric 
2316*0b57cec5SDimitry Andric // This function checks if a callee saved gpr can be spilled to a volatile
2317*0b57cec5SDimitry Andric // vector register. This occurs for leaf functions when the option
2318*0b57cec5SDimitry Andric // ppc-enable-pe-vector-spills is enabled. If there are any remaining registers
2319*0b57cec5SDimitry Andric // which were not spilled to vectors, return false so the target independent
2320*0b57cec5SDimitry Andric // code can handle them by assigning a FrameIdx to a stack slot.
2321*0b57cec5SDimitry Andric bool PPCFrameLowering::assignCalleeSavedSpillSlots(
2322*0b57cec5SDimitry Andric     MachineFunction &MF, const TargetRegisterInfo *TRI,
2323*0b57cec5SDimitry Andric     std::vector<CalleeSavedInfo> &CSI) const {
2324*0b57cec5SDimitry Andric 
2325*0b57cec5SDimitry Andric   if (CSI.empty())
2326*0b57cec5SDimitry Andric     return true; // Early exit if no callee saved registers are modified!
2327*0b57cec5SDimitry Andric 
2328*0b57cec5SDimitry Andric   // Early exit if cannot spill gprs to volatile vector registers.
2329*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
2330*0b57cec5SDimitry Andric   if (!EnablePEVectorSpills || MFI.hasCalls() || !Subtarget.hasP9Vector())
2331*0b57cec5SDimitry Andric     return false;
2332*0b57cec5SDimitry Andric 
2333*0b57cec5SDimitry Andric   // Build a BitVector of VSRs that can be used for spilling GPRs.
2334*0b57cec5SDimitry Andric   BitVector BVAllocatable = TRI->getAllocatableSet(MF);
2335*0b57cec5SDimitry Andric   BitVector BVCalleeSaved(TRI->getNumRegs());
2336*0b57cec5SDimitry Andric   const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2337*0b57cec5SDimitry Andric   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
2338*0b57cec5SDimitry Andric   for (unsigned i = 0; CSRegs[i]; ++i)
2339*0b57cec5SDimitry Andric     BVCalleeSaved.set(CSRegs[i]);
2340*0b57cec5SDimitry Andric 
2341*0b57cec5SDimitry Andric   for (unsigned Reg : BVAllocatable.set_bits()) {
2342fe6060f1SDimitry Andric     // Set to 0 if the register is not a volatile VSX register, or if it is
2343*0b57cec5SDimitry Andric     // used in the function.
2344fe6060f1SDimitry Andric     if (BVCalleeSaved[Reg] || !PPC::VSRCRegClass.contains(Reg) ||
2345fe6060f1SDimitry Andric         MF.getRegInfo().isPhysRegUsed(Reg))
2346*0b57cec5SDimitry Andric       BVAllocatable.reset(Reg);
2347*0b57cec5SDimitry Andric   }
2348*0b57cec5SDimitry Andric 
2349*0b57cec5SDimitry Andric   bool AllSpilledToReg = true;
2350fe6060f1SDimitry Andric   unsigned LastVSRUsedForSpill = 0;
2351*0b57cec5SDimitry Andric   for (auto &CS : CSI) {
2352*0b57cec5SDimitry Andric     if (BVAllocatable.none())
2353*0b57cec5SDimitry Andric       return false;
2354*0b57cec5SDimitry Andric 
235504eeddc0SDimitry Andric     Register Reg = CS.getReg();
2356fe6060f1SDimitry Andric 
2357fe6060f1SDimitry Andric     if (!PPC::G8RCRegClass.contains(Reg)) {
2358*0b57cec5SDimitry Andric       AllSpilledToReg = false;
2359*0b57cec5SDimitry Andric       continue;
2360*0b57cec5SDimitry Andric     }
2361*0b57cec5SDimitry Andric 
2362fe6060f1SDimitry Andric     // For P9, we can reuse LastVSRUsedForSpill to spill two GPRs
2363fe6060f1SDimitry Andric     // into one VSR using the mtvsrdd instruction.
2364fe6060f1SDimitry Andric     if (LastVSRUsedForSpill != 0) {
2365fe6060f1SDimitry Andric       CS.setDstReg(LastVSRUsedForSpill);
2366fe6060f1SDimitry Andric       BVAllocatable.reset(LastVSRUsedForSpill);
2367fe6060f1SDimitry Andric       LastVSRUsedForSpill = 0;
2368fe6060f1SDimitry Andric       continue;
2369fe6060f1SDimitry Andric     }
2370fe6060f1SDimitry Andric 
2371*0b57cec5SDimitry Andric     unsigned VolatileVFReg = BVAllocatable.find_first();
2372*0b57cec5SDimitry Andric     if (VolatileVFReg < BVAllocatable.size()) {
2373*0b57cec5SDimitry Andric       CS.setDstReg(VolatileVFReg);
2374fe6060f1SDimitry Andric       LastVSRUsedForSpill = VolatileVFReg;
2375*0b57cec5SDimitry Andric     } else {
2376*0b57cec5SDimitry Andric       AllSpilledToReg = false;
2377*0b57cec5SDimitry Andric     }
2378*0b57cec5SDimitry Andric   }
2379*0b57cec5SDimitry Andric   return AllSpilledToReg;
2380*0b57cec5SDimitry Andric }
2381*0b57cec5SDimitry Andric 
23825ffd83dbSDimitry Andric bool PPCFrameLowering::spillCalleeSavedRegisters(
23835ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
23845ffd83dbSDimitry Andric     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2385*0b57cec5SDimitry Andric 
2386*0b57cec5SDimitry Andric   MachineFunction *MF = MBB.getParent();
2387*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
2388*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2389*0b57cec5SDimitry Andric   bool MustSaveTOC = FI->mustSaveTOC();
2390*0b57cec5SDimitry Andric   DebugLoc DL;
2391*0b57cec5SDimitry Andric   bool CRSpilled = false;
2392*0b57cec5SDimitry Andric   MachineInstrBuilder CRMIB;
2393fe6060f1SDimitry Andric   BitVector Spilled(TRI->getNumRegs());
2394fe6060f1SDimitry Andric 
2395fe6060f1SDimitry Andric   VSRContainingGPRs.clear();
2396fe6060f1SDimitry Andric 
2397fe6060f1SDimitry Andric   // Map each VSR to GPRs to be spilled with into it. Single VSR can contain one
2398fe6060f1SDimitry Andric   // or two GPRs, so we need table to record information for later save/restore.
239981ad6265SDimitry Andric   for (const CalleeSavedInfo &Info : CSI) {
2400fe6060f1SDimitry Andric     if (Info.isSpilledToReg()) {
2401fe6060f1SDimitry Andric       auto &SpilledVSR =
2402fe6060f1SDimitry Andric           VSRContainingGPRs.FindAndConstruct(Info.getDstReg()).second;
2403fe6060f1SDimitry Andric       assert(SpilledVSR.second == 0 &&
2404fe6060f1SDimitry Andric              "Can't spill more than two GPRs into VSR!");
2405fe6060f1SDimitry Andric       if (SpilledVSR.first == 0)
2406fe6060f1SDimitry Andric         SpilledVSR.first = Info.getReg();
2407fe6060f1SDimitry Andric       else
2408fe6060f1SDimitry Andric         SpilledVSR.second = Info.getReg();
2409fe6060f1SDimitry Andric     }
241081ad6265SDimitry Andric   }
2411*0b57cec5SDimitry Andric 
24124824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
241304eeddc0SDimitry Andric     Register Reg = I.getReg();
2414*0b57cec5SDimitry Andric 
2415*0b57cec5SDimitry Andric     // CR2 through CR4 are the nonvolatile CR fields.
2416*0b57cec5SDimitry Andric     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
2417*0b57cec5SDimitry Andric 
2418*0b57cec5SDimitry Andric     // Add the callee-saved register as live-in; it's killed at the spill.
2419*0b57cec5SDimitry Andric     // Do not do this for callee-saved registers that are live-in to the
2420*0b57cec5SDimitry Andric     // function because they will already be marked live-in and this will be
2421*0b57cec5SDimitry Andric     // adding it for a second time. It is an error to add the same register
2422*0b57cec5SDimitry Andric     // to the set more than once.
2423*0b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF->getRegInfo();
2424*0b57cec5SDimitry Andric     bool IsLiveIn = MRI.isLiveIn(Reg);
2425*0b57cec5SDimitry Andric     if (!IsLiveIn)
2426*0b57cec5SDimitry Andric        MBB.addLiveIn(Reg);
2427*0b57cec5SDimitry Andric 
2428*0b57cec5SDimitry Andric     if (CRSpilled && IsCRField) {
2429*0b57cec5SDimitry Andric       CRMIB.addReg(Reg, RegState::ImplicitKill);
2430*0b57cec5SDimitry Andric       continue;
2431*0b57cec5SDimitry Andric     }
2432*0b57cec5SDimitry Andric 
2433*0b57cec5SDimitry Andric     // The actual spill will happen in the prologue.
2434*0b57cec5SDimitry Andric     if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
2435*0b57cec5SDimitry Andric       continue;
2436*0b57cec5SDimitry Andric 
2437*0b57cec5SDimitry Andric     // Insert the spill to the stack frame.
2438*0b57cec5SDimitry Andric     if (IsCRField) {
2439*0b57cec5SDimitry Andric       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
24405ffd83dbSDimitry Andric       if (!Subtarget.is32BitELFABI()) {
2441*0b57cec5SDimitry Andric         // The actual spill will happen at the start of the prologue.
2442*0b57cec5SDimitry Andric         FuncInfo->addMustSaveCR(Reg);
2443*0b57cec5SDimitry Andric       } else {
2444*0b57cec5SDimitry Andric         CRSpilled = true;
2445*0b57cec5SDimitry Andric         FuncInfo->setSpillsCR();
2446*0b57cec5SDimitry Andric 
2447*0b57cec5SDimitry Andric         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
2448*0b57cec5SDimitry Andric         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
2449*0b57cec5SDimitry Andric         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
2450*0b57cec5SDimitry Andric                   .addReg(Reg, RegState::ImplicitKill);
2451*0b57cec5SDimitry Andric 
2452*0b57cec5SDimitry Andric         MBB.insert(MI, CRMIB);
2453*0b57cec5SDimitry Andric         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
2454*0b57cec5SDimitry Andric                                          .addReg(PPC::R12,
2455*0b57cec5SDimitry Andric                                                  getKillRegState(true)),
24564824e7fdSDimitry Andric                                          I.getFrameIdx()));
2457*0b57cec5SDimitry Andric       }
2458*0b57cec5SDimitry Andric     } else {
24594824e7fdSDimitry Andric       if (I.isSpilledToReg()) {
24604824e7fdSDimitry Andric         unsigned Dst = I.getDstReg();
2461fe6060f1SDimitry Andric 
2462fe6060f1SDimitry Andric         if (Spilled[Dst])
2463fe6060f1SDimitry Andric           continue;
2464fe6060f1SDimitry Andric 
2465fe6060f1SDimitry Andric         if (VSRContainingGPRs[Dst].second != 0) {
2466fe6060f1SDimitry Andric           assert(Subtarget.hasP9Vector() &&
2467fe6060f1SDimitry Andric                  "mtvsrdd is unavailable on pre-P9 targets.");
2468fe6060f1SDimitry Andric 
2469fe6060f1SDimitry Andric           NumPESpillVSR += 2;
2470fe6060f1SDimitry Andric           BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRDD), Dst)
2471fe6060f1SDimitry Andric               .addReg(VSRContainingGPRs[Dst].first, getKillRegState(true))
2472fe6060f1SDimitry Andric               .addReg(VSRContainingGPRs[Dst].second, getKillRegState(true));
2473fe6060f1SDimitry Andric         } else if (VSRContainingGPRs[Dst].second == 0) {
2474fe6060f1SDimitry Andric           assert(Subtarget.hasP8Vector() &&
2475fe6060f1SDimitry Andric                  "Can't move GPR to VSR on pre-P8 targets.");
2476fe6060f1SDimitry Andric 
2477fe6060f1SDimitry Andric           ++NumPESpillVSR;
2478fe6060f1SDimitry Andric           BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRD),
2479fe6060f1SDimitry Andric                   TRI->getSubReg(Dst, PPC::sub_64))
2480fe6060f1SDimitry Andric               .addReg(VSRContainingGPRs[Dst].first, getKillRegState(true));
2481fe6060f1SDimitry Andric         } else {
2482fe6060f1SDimitry Andric           llvm_unreachable("More than two GPRs spilled to a VSR!");
2483fe6060f1SDimitry Andric         }
2484fe6060f1SDimitry Andric         Spilled.set(Dst);
2485*0b57cec5SDimitry Andric       } else {
2486*0b57cec5SDimitry Andric         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2487*0b57cec5SDimitry Andric         // Use !IsLiveIn for the kill flag.
2488*0b57cec5SDimitry Andric         // We do not want to kill registers that are live in this function
2489*0b57cec5SDimitry Andric         // before their use because they will become undefined registers.
24905ffd83dbSDimitry Andric         // Functions without NoUnwind need to preserve the order of elements in
24915ffd83dbSDimitry Andric         // saved vector registers.
24925ffd83dbSDimitry Andric         if (Subtarget.needsSwapsForVSXMemOps() &&
24935ffd83dbSDimitry Andric             !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
24945ffd83dbSDimitry Andric           TII.storeRegToStackSlotNoUpd(MBB, MI, Reg, !IsLiveIn,
24954824e7fdSDimitry Andric                                        I.getFrameIdx(), RC, TRI);
24965ffd83dbSDimitry Andric         else
2497bdd1243dSDimitry Andric           TII.storeRegToStackSlot(MBB, MI, Reg, !IsLiveIn, I.getFrameIdx(), RC,
2498bdd1243dSDimitry Andric                                   TRI, Register());
2499*0b57cec5SDimitry Andric       }
2500*0b57cec5SDimitry Andric     }
2501*0b57cec5SDimitry Andric   }
2502*0b57cec5SDimitry Andric   return true;
2503*0b57cec5SDimitry Andric }
2504*0b57cec5SDimitry Andric 
25055ffd83dbSDimitry Andric static void restoreCRs(bool is31, bool CR2Spilled, bool CR3Spilled,
25065ffd83dbSDimitry Andric                        bool CR4Spilled, MachineBasicBlock &MBB,
25075ffd83dbSDimitry Andric                        MachineBasicBlock::iterator MI,
25085ffd83dbSDimitry Andric                        ArrayRef<CalleeSavedInfo> CSI, unsigned CSIIndex) {
2509*0b57cec5SDimitry Andric 
2510*0b57cec5SDimitry Andric   MachineFunction *MF = MBB.getParent();
2511*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
2512*0b57cec5SDimitry Andric   DebugLoc DL;
25135ffd83dbSDimitry Andric   unsigned MoveReg = PPC::R12;
2514*0b57cec5SDimitry Andric 
2515*0b57cec5SDimitry Andric   // 32-bit:  FP-relative
25165ffd83dbSDimitry Andric   MBB.insert(MI,
25175ffd83dbSDimitry Andric              addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ), MoveReg),
2518*0b57cec5SDimitry Andric                                CSI[CSIIndex].getFrameIdx()));
2519*0b57cec5SDimitry Andric 
25205ffd83dbSDimitry Andric   unsigned RestoreOp = PPC::MTOCRF;
2521*0b57cec5SDimitry Andric   if (CR2Spilled)
2522*0b57cec5SDimitry Andric     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
2523*0b57cec5SDimitry Andric                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
2524*0b57cec5SDimitry Andric 
2525*0b57cec5SDimitry Andric   if (CR3Spilled)
2526*0b57cec5SDimitry Andric     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
2527*0b57cec5SDimitry Andric                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
2528*0b57cec5SDimitry Andric 
2529*0b57cec5SDimitry Andric   if (CR4Spilled)
2530*0b57cec5SDimitry Andric     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
2531*0b57cec5SDimitry Andric                .addReg(MoveReg, getKillRegState(true)));
2532*0b57cec5SDimitry Andric }
2533*0b57cec5SDimitry Andric 
2534*0b57cec5SDimitry Andric MachineBasicBlock::iterator PPCFrameLowering::
2535*0b57cec5SDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
2536*0b57cec5SDimitry Andric                               MachineBasicBlock::iterator I) const {
2537*0b57cec5SDimitry Andric   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2538*0b57cec5SDimitry Andric   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2539*0b57cec5SDimitry Andric       I->getOpcode() == PPC::ADJCALLSTACKUP) {
2540*0b57cec5SDimitry Andric     // Add (actually subtract) back the amount the callee popped on return.
2541*0b57cec5SDimitry Andric     if (int CalleeAmt =  I->getOperand(1).getImm()) {
2542*0b57cec5SDimitry Andric       bool is64Bit = Subtarget.isPPC64();
2543*0b57cec5SDimitry Andric       CalleeAmt *= -1;
2544*0b57cec5SDimitry Andric       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
2545*0b57cec5SDimitry Andric       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
2546*0b57cec5SDimitry Andric       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
2547*0b57cec5SDimitry Andric       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
2548*0b57cec5SDimitry Andric       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
2549*0b57cec5SDimitry Andric       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
2550*0b57cec5SDimitry Andric       const DebugLoc &dl = I->getDebugLoc();
2551*0b57cec5SDimitry Andric 
2552*0b57cec5SDimitry Andric       if (isInt<16>(CalleeAmt)) {
2553*0b57cec5SDimitry Andric         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
2554*0b57cec5SDimitry Andric           .addReg(StackReg, RegState::Kill)
2555*0b57cec5SDimitry Andric           .addImm(CalleeAmt);
2556*0b57cec5SDimitry Andric       } else {
2557*0b57cec5SDimitry Andric         MachineBasicBlock::iterator MBBI = I;
2558*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
2559*0b57cec5SDimitry Andric           .addImm(CalleeAmt >> 16);
2560*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
2561*0b57cec5SDimitry Andric           .addReg(TmpReg, RegState::Kill)
2562*0b57cec5SDimitry Andric           .addImm(CalleeAmt & 0xFFFF);
2563*0b57cec5SDimitry Andric         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
2564*0b57cec5SDimitry Andric           .addReg(StackReg, RegState::Kill)
2565*0b57cec5SDimitry Andric           .addReg(TmpReg);
2566*0b57cec5SDimitry Andric       }
2567*0b57cec5SDimitry Andric     }
2568*0b57cec5SDimitry Andric   }
2569*0b57cec5SDimitry Andric   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
2570*0b57cec5SDimitry Andric   return MBB.erase(I);
2571*0b57cec5SDimitry Andric }
2572*0b57cec5SDimitry Andric 
25735ffd83dbSDimitry Andric static bool isCalleeSavedCR(unsigned Reg) {
25745ffd83dbSDimitry Andric   return PPC::CR2 == Reg || Reg == PPC::CR3 || Reg == PPC::CR4;
25755ffd83dbSDimitry Andric }
2576*0b57cec5SDimitry Andric 
25775ffd83dbSDimitry Andric bool PPCFrameLowering::restoreCalleeSavedRegisters(
25785ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
25795ffd83dbSDimitry Andric     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2580*0b57cec5SDimitry Andric   MachineFunction *MF = MBB.getParent();
2581*0b57cec5SDimitry Andric   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
2582*0b57cec5SDimitry Andric   PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2583*0b57cec5SDimitry Andric   bool MustSaveTOC = FI->mustSaveTOC();
2584*0b57cec5SDimitry Andric   bool CR2Spilled = false;
2585*0b57cec5SDimitry Andric   bool CR3Spilled = false;
2586*0b57cec5SDimitry Andric   bool CR4Spilled = false;
2587*0b57cec5SDimitry Andric   unsigned CSIIndex = 0;
2588fe6060f1SDimitry Andric   BitVector Restored(TRI->getNumRegs());
2589*0b57cec5SDimitry Andric 
2590*0b57cec5SDimitry Andric   // Initialize insertion-point logic; we will be restoring in reverse
2591*0b57cec5SDimitry Andric   // order of spill.
2592*0b57cec5SDimitry Andric   MachineBasicBlock::iterator I = MI, BeforeI = I;
2593*0b57cec5SDimitry Andric   bool AtStart = I == MBB.begin();
2594*0b57cec5SDimitry Andric 
2595*0b57cec5SDimitry Andric   if (!AtStart)
2596*0b57cec5SDimitry Andric     --BeforeI;
2597*0b57cec5SDimitry Andric 
2598*0b57cec5SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
259904eeddc0SDimitry Andric     Register Reg = CSI[i].getReg();
2600*0b57cec5SDimitry Andric 
2601*0b57cec5SDimitry Andric     if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
2602*0b57cec5SDimitry Andric       continue;
2603*0b57cec5SDimitry Andric 
26045ffd83dbSDimitry Andric     // Restore of callee saved condition register field is handled during
26055ffd83dbSDimitry Andric     // epilogue insertion.
26065ffd83dbSDimitry Andric     if (isCalleeSavedCR(Reg) && !Subtarget.is32BitELFABI())
26075ffd83dbSDimitry Andric       continue;
26085ffd83dbSDimitry Andric 
2609*0b57cec5SDimitry Andric     if (Reg == PPC::CR2) {
2610*0b57cec5SDimitry Andric       CR2Spilled = true;
2611*0b57cec5SDimitry Andric       // The spill slot is associated only with CR2, which is the
2612*0b57cec5SDimitry Andric       // first nonvolatile spilled.  Save it here.
2613*0b57cec5SDimitry Andric       CSIIndex = i;
2614*0b57cec5SDimitry Andric       continue;
2615*0b57cec5SDimitry Andric     } else if (Reg == PPC::CR3) {
2616*0b57cec5SDimitry Andric       CR3Spilled = true;
2617*0b57cec5SDimitry Andric       continue;
2618*0b57cec5SDimitry Andric     } else if (Reg == PPC::CR4) {
2619*0b57cec5SDimitry Andric       CR4Spilled = true;
2620*0b57cec5SDimitry Andric       continue;
2621*0b57cec5SDimitry Andric     } else {
26225ffd83dbSDimitry Andric       // On 32-bit ELF when we first encounter a non-CR register after seeing at
2623*0b57cec5SDimitry Andric       // least one CR register, restore all spilled CRs together.
26245ffd83dbSDimitry Andric       if (CR2Spilled || CR3Spilled || CR4Spilled) {
2625*0b57cec5SDimitry Andric         bool is31 = needsFP(*MF);
26265ffd83dbSDimitry Andric         restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI,
26275ffd83dbSDimitry Andric                    CSIIndex);
2628*0b57cec5SDimitry Andric         CR2Spilled = CR3Spilled = CR4Spilled = false;
2629*0b57cec5SDimitry Andric       }
2630*0b57cec5SDimitry Andric 
2631*0b57cec5SDimitry Andric       if (CSI[i].isSpilledToReg()) {
2632*0b57cec5SDimitry Andric         DebugLoc DL;
2633fe6060f1SDimitry Andric         unsigned Dst = CSI[i].getDstReg();
2634fe6060f1SDimitry Andric 
2635fe6060f1SDimitry Andric         if (Restored[Dst])
2636fe6060f1SDimitry Andric           continue;
2637fe6060f1SDimitry Andric 
2638fe6060f1SDimitry Andric         if (VSRContainingGPRs[Dst].second != 0) {
2639fe6060f1SDimitry Andric           assert(Subtarget.hasP9Vector());
2640fe6060f1SDimitry Andric           NumPEReloadVSR += 2;
2641fe6060f1SDimitry Andric           BuildMI(MBB, I, DL, TII.get(PPC::MFVSRLD),
2642fe6060f1SDimitry Andric                   VSRContainingGPRs[Dst].second)
2643fe6060f1SDimitry Andric               .addReg(Dst);
2644fe6060f1SDimitry Andric           BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),
2645fe6060f1SDimitry Andric                   VSRContainingGPRs[Dst].first)
2646fe6060f1SDimitry Andric               .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
2647fe6060f1SDimitry Andric         } else if (VSRContainingGPRs[Dst].second == 0) {
2648fe6060f1SDimitry Andric           assert(Subtarget.hasP8Vector());
2649fe6060f1SDimitry Andric           ++NumPEReloadVSR;
2650fe6060f1SDimitry Andric           BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),
2651fe6060f1SDimitry Andric                   VSRContainingGPRs[Dst].first)
2652fe6060f1SDimitry Andric               .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
2653fe6060f1SDimitry Andric         } else {
2654fe6060f1SDimitry Andric           llvm_unreachable("More than two GPRs spilled to a VSR!");
2655fe6060f1SDimitry Andric         }
2656fe6060f1SDimitry Andric 
2657fe6060f1SDimitry Andric         Restored.set(Dst);
2658fe6060f1SDimitry Andric 
2659*0b57cec5SDimitry Andric       } else {
2660*0b57cec5SDimitry Andric        // Default behavior for non-CR saves.
2661*0b57cec5SDimitry Andric         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
26625ffd83dbSDimitry Andric 
26635ffd83dbSDimitry Andric         // Functions without NoUnwind need to preserve the order of elements in
26645ffd83dbSDimitry Andric         // saved vector registers.
26655ffd83dbSDimitry Andric         if (Subtarget.needsSwapsForVSXMemOps() &&
26665ffd83dbSDimitry Andric             !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
26675ffd83dbSDimitry Andric           TII.loadRegFromStackSlotNoUpd(MBB, I, Reg, CSI[i].getFrameIdx(), RC,
26685ffd83dbSDimitry Andric                                         TRI);
26695ffd83dbSDimitry Andric         else
2670bdd1243dSDimitry Andric           TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI,
2671bdd1243dSDimitry Andric                                    Register());
26725ffd83dbSDimitry Andric 
2673*0b57cec5SDimitry Andric         assert(I != MBB.begin() &&
2674*0b57cec5SDimitry Andric                "loadRegFromStackSlot didn't insert any code!");
2675*0b57cec5SDimitry Andric       }
2676*0b57cec5SDimitry Andric     }
2677*0b57cec5SDimitry Andric 
2678*0b57cec5SDimitry Andric     // Insert in reverse order.
2679*0b57cec5SDimitry Andric     if (AtStart)
2680*0b57cec5SDimitry Andric       I = MBB.begin();
2681*0b57cec5SDimitry Andric     else {
2682*0b57cec5SDimitry Andric       I = BeforeI;
2683*0b57cec5SDimitry Andric       ++I;
2684*0b57cec5SDimitry Andric     }
2685*0b57cec5SDimitry Andric   }
2686*0b57cec5SDimitry Andric 
2687*0b57cec5SDimitry Andric   // If we haven't yet spilled the CRs, do so now.
2688*0b57cec5SDimitry Andric   if (CR2Spilled || CR3Spilled || CR4Spilled) {
26895ffd83dbSDimitry Andric     assert(Subtarget.is32BitELFABI() &&
26905ffd83dbSDimitry Andric            "Only set CR[2|3|4]Spilled on 32-bit SVR4.");
2691*0b57cec5SDimitry Andric     bool is31 = needsFP(*MF);
26925ffd83dbSDimitry Andric     restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI, CSIIndex);
2693*0b57cec5SDimitry Andric   }
2694*0b57cec5SDimitry Andric 
2695*0b57cec5SDimitry Andric   return true;
2696*0b57cec5SDimitry Andric }
2697*0b57cec5SDimitry Andric 
2698349cc55cSDimitry Andric uint64_t PPCFrameLowering::getTOCSaveOffset() const {
26998bcb0991SDimitry Andric   return TOCSaveOffset;
27008bcb0991SDimitry Andric }
27018bcb0991SDimitry Andric 
2702349cc55cSDimitry Andric uint64_t PPCFrameLowering::getFramePointerSaveOffset() const {
27038bcb0991SDimitry Andric   return FramePointerSaveOffset;
27048bcb0991SDimitry Andric }
27058bcb0991SDimitry Andric 
2706349cc55cSDimitry Andric uint64_t PPCFrameLowering::getBasePointerSaveOffset() const {
27078bcb0991SDimitry Andric   return BasePointerSaveOffset;
27088bcb0991SDimitry Andric }
27098bcb0991SDimitry Andric 
2710*0b57cec5SDimitry Andric bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
2711*0b57cec5SDimitry Andric   if (MF.getInfo<PPCFunctionInfo>()->shrinkWrapDisabled())
2712*0b57cec5SDimitry Andric     return false;
2713fe6060f1SDimitry Andric   return !MF.getSubtarget<PPCSubtarget>().is32BitELFABI();
2714*0b57cec5SDimitry Andric }
2715