1 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the PPC implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCFrameLowering.h"
15 #include "PPCInstrBuilder.h"
16 #include "PPCInstrInfo.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Target/TargetOptions.h"
28 
29 using namespace llvm;
30 
31 /// VRRegNo - Map from a numbered VR register to its enum value.
32 ///
33 static const MCPhysReg VRRegNo[] = {
34  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
35  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
36  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
37  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
38 };
39 
computeReturnSaveOffset(const PPCSubtarget & STI)40 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
41   if (STI.isDarwinABI())
42     return STI.isPPC64() ? 16 : 8;
43   // SVR4 ABI:
44   return STI.isPPC64() ? 16 : 4;
45 }
46 
computeTOCSaveOffset(const PPCSubtarget & STI)47 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
48   return STI.isELFv2ABI() ? 24 : 40;
49 }
50 
computeFramePointerSaveOffset(const PPCSubtarget & STI)51 static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
52   // For the Darwin ABI:
53   // We cannot use the TOC save slot (offset +20) in the PowerPC linkage area
54   // for saving the frame pointer (if needed.)  While the published ABI has
55   // not used this slot since at least MacOSX 10.2, there is older code
56   // around that does use it, and that needs to continue to work.
57   if (STI.isDarwinABI())
58     return STI.isPPC64() ? -8U : -4U;
59 
60   // SVR4 ABI: First slot in the general register save area.
61   return STI.isPPC64() ? -8U : -4U;
62 }
63 
computeLinkageSize(const PPCSubtarget & STI)64 static unsigned computeLinkageSize(const PPCSubtarget &STI) {
65   if (STI.isDarwinABI() || STI.isPPC64())
66     return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
67 
68   // SVR4 ABI:
69   return 8;
70 }
71 
computeBasePointerSaveOffset(const PPCSubtarget & STI)72 static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
73   if (STI.isDarwinABI())
74     return STI.isPPC64() ? -16U : -8U;
75 
76   // SVR4 ABI: First slot in the general register save area.
77   return STI.isPPC64()
78              ? -16U
79              : (STI.getTargetMachine().getRelocationModel() == Reloc::PIC_)
80                    ? -12U
81                    : -8U;
82 }
83 
PPCFrameLowering(const PPCSubtarget & STI)84 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
85     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
86                           STI.getPlatformStackAlignment(), 0),
87       Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
88       TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
89       FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
90       LinkageSize(computeLinkageSize(Subtarget)),
91       BasePointerSaveOffset(computeBasePointerSaveOffset(STI)) {}
92 
93 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
getCalleeSavedSpillSlots(unsigned & NumEntries) const94 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
95     unsigned &NumEntries) const {
96   if (Subtarget.isDarwinABI()) {
97     NumEntries = 1;
98     if (Subtarget.isPPC64()) {
99       static const SpillSlot darwin64Offsets = {PPC::X31, -8};
100       return &darwin64Offsets;
101     } else {
102       static const SpillSlot darwinOffsets = {PPC::R31, -4};
103       return &darwinOffsets;
104     }
105   }
106 
107   // Early exit if not using the SVR4 ABI.
108   if (!Subtarget.isSVR4ABI()) {
109     NumEntries = 0;
110     return nullptr;
111   }
112 
113   // Note that the offsets here overlap, but this is fixed up in
114   // processFunctionBeforeFrameFinalized.
115 
116   static const SpillSlot Offsets[] = {
117       // Floating-point register save area offsets.
118       {PPC::F31, -8},
119       {PPC::F30, -16},
120       {PPC::F29, -24},
121       {PPC::F28, -32},
122       {PPC::F27, -40},
123       {PPC::F26, -48},
124       {PPC::F25, -56},
125       {PPC::F24, -64},
126       {PPC::F23, -72},
127       {PPC::F22, -80},
128       {PPC::F21, -88},
129       {PPC::F20, -96},
130       {PPC::F19, -104},
131       {PPC::F18, -112},
132       {PPC::F17, -120},
133       {PPC::F16, -128},
134       {PPC::F15, -136},
135       {PPC::F14, -144},
136 
137       // General register save area offsets.
138       {PPC::R31, -4},
139       {PPC::R30, -8},
140       {PPC::R29, -12},
141       {PPC::R28, -16},
142       {PPC::R27, -20},
143       {PPC::R26, -24},
144       {PPC::R25, -28},
145       {PPC::R24, -32},
146       {PPC::R23, -36},
147       {PPC::R22, -40},
148       {PPC::R21, -44},
149       {PPC::R20, -48},
150       {PPC::R19, -52},
151       {PPC::R18, -56},
152       {PPC::R17, -60},
153       {PPC::R16, -64},
154       {PPC::R15, -68},
155       {PPC::R14, -72},
156 
157       // CR save area offset.  We map each of the nonvolatile CR fields
158       // to the slot for CR2, which is the first of the nonvolatile CR
159       // fields to be assigned, so that we only allocate one save slot.
160       // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
161       {PPC::CR2, -4},
162 
163       // VRSAVE save area offset.
164       {PPC::VRSAVE, -4},
165 
166       // Vector register save area
167       {PPC::V31, -16},
168       {PPC::V30, -32},
169       {PPC::V29, -48},
170       {PPC::V28, -64},
171       {PPC::V27, -80},
172       {PPC::V26, -96},
173       {PPC::V25, -112},
174       {PPC::V24, -128},
175       {PPC::V23, -144},
176       {PPC::V22, -160},
177       {PPC::V21, -176},
178       {PPC::V20, -192}};
179 
180   static const SpillSlot Offsets64[] = {
181       // Floating-point register save area offsets.
182       {PPC::F31, -8},
183       {PPC::F30, -16},
184       {PPC::F29, -24},
185       {PPC::F28, -32},
186       {PPC::F27, -40},
187       {PPC::F26, -48},
188       {PPC::F25, -56},
189       {PPC::F24, -64},
190       {PPC::F23, -72},
191       {PPC::F22, -80},
192       {PPC::F21, -88},
193       {PPC::F20, -96},
194       {PPC::F19, -104},
195       {PPC::F18, -112},
196       {PPC::F17, -120},
197       {PPC::F16, -128},
198       {PPC::F15, -136},
199       {PPC::F14, -144},
200 
201       // General register save area offsets.
202       {PPC::X31, -8},
203       {PPC::X30, -16},
204       {PPC::X29, -24},
205       {PPC::X28, -32},
206       {PPC::X27, -40},
207       {PPC::X26, -48},
208       {PPC::X25, -56},
209       {PPC::X24, -64},
210       {PPC::X23, -72},
211       {PPC::X22, -80},
212       {PPC::X21, -88},
213       {PPC::X20, -96},
214       {PPC::X19, -104},
215       {PPC::X18, -112},
216       {PPC::X17, -120},
217       {PPC::X16, -128},
218       {PPC::X15, -136},
219       {PPC::X14, -144},
220 
221       // VRSAVE save area offset.
222       {PPC::VRSAVE, -4},
223 
224       // Vector register save area
225       {PPC::V31, -16},
226       {PPC::V30, -32},
227       {PPC::V29, -48},
228       {PPC::V28, -64},
229       {PPC::V27, -80},
230       {PPC::V26, -96},
231       {PPC::V25, -112},
232       {PPC::V24, -128},
233       {PPC::V23, -144},
234       {PPC::V22, -160},
235       {PPC::V21, -176},
236       {PPC::V20, -192}};
237 
238   if (Subtarget.isPPC64()) {
239     NumEntries = array_lengthof(Offsets64);
240 
241     return Offsets64;
242   } else {
243     NumEntries = array_lengthof(Offsets);
244 
245     return Offsets;
246   }
247 }
248 
249 /// RemoveVRSaveCode - We have found that this function does not need any code
250 /// to manipulate the VRSAVE register, even though it uses vector registers.
251 /// This can happen when the only registers used are known to be live in or out
252 /// of the function.  Remove all of the VRSAVE related code from the function.
253 /// FIXME: The removal of the code results in a compile failure at -O0 when the
254 /// function contains a function call, as the GPR containing original VRSAVE
255 /// contents is spilled and reloaded around the call.  Without the prolog code,
256 /// the spill instruction refers to an undefined register.  This code needs
257 /// to account for all uses of that GPR.
RemoveVRSaveCode(MachineInstr * MI)258 static void RemoveVRSaveCode(MachineInstr *MI) {
259   MachineBasicBlock *Entry = MI->getParent();
260   MachineFunction *MF = Entry->getParent();
261 
262   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
263   MachineBasicBlock::iterator MBBI = MI;
264   ++MBBI;
265   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
266   MBBI->eraseFromParent();
267 
268   bool RemovedAllMTVRSAVEs = true;
269   // See if we can find and remove the MTVRSAVE instruction from all of the
270   // epilog blocks.
271   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
272     // If last instruction is a return instruction, add an epilogue
273     if (I->isReturnBlock()) {
274       bool FoundIt = false;
275       for (MBBI = I->end(); MBBI != I->begin(); ) {
276         --MBBI;
277         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
278           MBBI->eraseFromParent();  // remove it.
279           FoundIt = true;
280           break;
281         }
282       }
283       RemovedAllMTVRSAVEs &= FoundIt;
284     }
285   }
286 
287   // If we found and removed all MTVRSAVE instructions, remove the read of
288   // VRSAVE as well.
289   if (RemovedAllMTVRSAVEs) {
290     MBBI = MI;
291     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
292     --MBBI;
293     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
294     MBBI->eraseFromParent();
295   }
296 
297   // Finally, nuke the UPDATE_VRSAVE.
298   MI->eraseFromParent();
299 }
300 
301 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
302 // instruction selector.  Based on the vector registers that have been used,
303 // transform this into the appropriate ORI instruction.
HandleVRSaveUpdate(MachineInstr * MI,const TargetInstrInfo & TII)304 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
305   MachineFunction *MF = MI->getParent()->getParent();
306   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
307   DebugLoc dl = MI->getDebugLoc();
308 
309   const MachineRegisterInfo &MRI = MF->getRegInfo();
310   unsigned UsedRegMask = 0;
311   for (unsigned i = 0; i != 32; ++i)
312     if (MRI.isPhysRegModified(VRRegNo[i]))
313       UsedRegMask |= 1 << (31-i);
314 
315   // Live in and live out values already must be in the mask, so don't bother
316   // marking them.
317   for (MachineRegisterInfo::livein_iterator
318        I = MF->getRegInfo().livein_begin(),
319        E = MF->getRegInfo().livein_end(); I != E; ++I) {
320     unsigned RegNo = TRI->getEncodingValue(I->first);
321     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
322       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
323   }
324 
325   // Live out registers appear as use operands on return instructions.
326   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
327        UsedRegMask != 0 && BI != BE; ++BI) {
328     const MachineBasicBlock &MBB = *BI;
329     if (!MBB.isReturnBlock())
330       continue;
331     const MachineInstr &Ret = MBB.back();
332     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
333       const MachineOperand &MO = Ret.getOperand(I);
334       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
335         continue;
336       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
337       UsedRegMask &= ~(1 << (31-RegNo));
338     }
339   }
340 
341   // If no registers are used, turn this into a copy.
342   if (UsedRegMask == 0) {
343     // Remove all VRSAVE code.
344     RemoveVRSaveCode(MI);
345     return;
346   }
347 
348   unsigned SrcReg = MI->getOperand(1).getReg();
349   unsigned DstReg = MI->getOperand(0).getReg();
350 
351   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
352     if (DstReg != SrcReg)
353       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
354         .addReg(SrcReg)
355         .addImm(UsedRegMask);
356     else
357       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
358         .addReg(SrcReg, RegState::Kill)
359         .addImm(UsedRegMask);
360   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
361     if (DstReg != SrcReg)
362       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
363         .addReg(SrcReg)
364         .addImm(UsedRegMask >> 16);
365     else
366       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
367         .addReg(SrcReg, RegState::Kill)
368         .addImm(UsedRegMask >> 16);
369   } else {
370     if (DstReg != SrcReg)
371       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
372         .addReg(SrcReg)
373         .addImm(UsedRegMask >> 16);
374     else
375       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
376         .addReg(SrcReg, RegState::Kill)
377         .addImm(UsedRegMask >> 16);
378 
379     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
380       .addReg(DstReg, RegState::Kill)
381       .addImm(UsedRegMask & 0xFFFF);
382   }
383 
384   // Remove the old UPDATE_VRSAVE instruction.
385   MI->eraseFromParent();
386 }
387 
spillsCR(const MachineFunction & MF)388 static bool spillsCR(const MachineFunction &MF) {
389   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
390   return FuncInfo->isCRSpilled();
391 }
392 
spillsVRSAVE(const MachineFunction & MF)393 static bool spillsVRSAVE(const MachineFunction &MF) {
394   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
395   return FuncInfo->isVRSAVESpilled();
396 }
397 
hasSpills(const MachineFunction & MF)398 static bool hasSpills(const MachineFunction &MF) {
399   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
400   return FuncInfo->hasSpills();
401 }
402 
hasNonRISpills(const MachineFunction & MF)403 static bool hasNonRISpills(const MachineFunction &MF) {
404   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
405   return FuncInfo->hasNonRISpills();
406 }
407 
408 /// MustSaveLR - Return true if this function requires that we save the LR
409 /// register onto the stack in the prolog and restore it in the epilog of the
410 /// function.
MustSaveLR(const MachineFunction & MF,unsigned LR)411 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
412   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
413 
414   // We need a save/restore of LR if there is any def of LR (which is
415   // defined by calls, including the PIC setup sequence), or if there is
416   // some use of the LR stack slot (e.g. for builtin_return_address).
417   // (LR comes in 32 and 64 bit versions.)
418   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
419   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
420 }
421 
422 /// determineFrameLayout - Determine the size of the frame and maximum call
423 /// frame size.
determineFrameLayout(MachineFunction & MF,bool UpdateMF,bool UseEstimate) const424 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
425                                                 bool UpdateMF,
426                                                 bool UseEstimate) const {
427   MachineFrameInfo *MFI = MF.getFrameInfo();
428 
429   // Get the number of bytes to allocate from the FrameInfo
430   unsigned FrameSize =
431     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
432 
433   // Get stack alignments. The frame must be aligned to the greatest of these:
434   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
435   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
436   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
437 
438   const PPCRegisterInfo *RegInfo =
439       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
440 
441   // If we are a leaf function, and use up to 224 bytes of stack space,
442   // don't have a frame pointer, calls, or dynamic alloca then we do not need
443   // to adjust the stack pointer (we fit in the Red Zone).
444   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
445   // stackless code if all local vars are reg-allocated.
446   bool DisableRedZone = MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
447   unsigned LR = RegInfo->getRARegister();
448   if (!DisableRedZone &&
449       (Subtarget.isPPC64() ||                      // 32-bit SVR4, no stack-
450        !Subtarget.isSVR4ABI() ||                   //   allocated locals.
451         FrameSize == 0) &&
452       FrameSize <= 224 &&                          // Fits in red zone.
453       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
454       !MFI->adjustsStack() &&                      // No calls.
455       !MustSaveLR(MF, LR) &&
456       !RegInfo->hasBasePointer(MF)) { // No special alignment.
457     // No need for frame
458     if (UpdateMF)
459       MFI->setStackSize(0);
460     return 0;
461   }
462 
463   // Get the maximum call frame size of all the calls.
464   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
465 
466   // Maximum call frame needs to be at least big enough for linkage area.
467   unsigned minCallFrameSize = getLinkageSize();
468   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
469 
470   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
471   // that allocations will be aligned.
472   if (MFI->hasVarSizedObjects())
473     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
474 
475   // Update maximum call frame size.
476   if (UpdateMF)
477     MFI->setMaxCallFrameSize(maxCallFrameSize);
478 
479   // Include call frame size in total.
480   FrameSize += maxCallFrameSize;
481 
482   // Make sure the frame is aligned.
483   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
484 
485   // Update frame info.
486   if (UpdateMF)
487     MFI->setStackSize(FrameSize);
488 
489   return FrameSize;
490 }
491 
492 // hasFP - Return true if the specified function actually has a dedicated frame
493 // pointer register.
hasFP(const MachineFunction & MF) const494 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
495   const MachineFrameInfo *MFI = MF.getFrameInfo();
496   // FIXME: This is pretty much broken by design: hasFP() might be called really
497   // early, before the stack layout was calculated and thus hasFP() might return
498   // true or false here depending on the time of call.
499   return (MFI->getStackSize()) && needsFP(MF);
500 }
501 
502 // needsFP - Return true if the specified function should have a dedicated frame
503 // pointer register.  This is true if the function has variable sized allocas or
504 // if frame pointer elimination is disabled.
needsFP(const MachineFunction & MF) const505 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
506   const MachineFrameInfo *MFI = MF.getFrameInfo();
507 
508   // Naked functions have no stack frame pushed, so we don't have a frame
509   // pointer.
510   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
511     return false;
512 
513   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
514     MFI->hasVarSizedObjects() ||
515     MFI->hasStackMap() || MFI->hasPatchPoint() ||
516     (MF.getTarget().Options.GuaranteedTailCallOpt &&
517      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
518 }
519 
replaceFPWithRealFP(MachineFunction & MF) const520 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
521   bool is31 = needsFP(MF);
522   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
523   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
524 
525   const PPCRegisterInfo *RegInfo =
526       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
527   bool HasBP = RegInfo->hasBasePointer(MF);
528   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
529   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
530 
531   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
532        BI != BE; ++BI)
533     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
534       --MBBI;
535       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
536         MachineOperand &MO = MBBI->getOperand(I);
537         if (!MO.isReg())
538           continue;
539 
540         switch (MO.getReg()) {
541         case PPC::FP:
542           MO.setReg(FPReg);
543           break;
544         case PPC::FP8:
545           MO.setReg(FP8Reg);
546           break;
547         case PPC::BP:
548           MO.setReg(BPReg);
549           break;
550         case PPC::BP8:
551           MO.setReg(BP8Reg);
552           break;
553 
554         }
555       }
556     }
557 }
558 
findScratchRegister(MachineBasicBlock * MBB,bool UseAtEnd,unsigned * ScratchRegister) const559 bool PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
560                                            bool UseAtEnd,
561                                            unsigned *ScratchRegister) const {
562   RegScavenger RS;
563   unsigned     R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
564 
565   if (ScratchRegister)
566     *ScratchRegister = R0;
567 
568   // If MBB is an entry or exit block, use R0 as the scratch register
569   if ((UseAtEnd && MBB->isReturnBlock()) ||
570       (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
571     return true;
572 
573   RS.enterBasicBlock(MBB);
574 
575   if (UseAtEnd && !MBB->empty()) {
576     // The scratch register will be used at the end of the block, so must consider
577     // all registers used within the block
578 
579     MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
580     // If no terminator, back iterator up to previous instruction.
581     if (MBBI == MBB->end())
582       MBBI = std::prev(MBBI);
583 
584     if (MBBI != MBB->begin())
585       RS.forward(MBBI);
586   }
587 
588   if (!RS.isRegUsed(R0))
589     return true;
590 
591   unsigned Reg = RS.FindUnusedReg(Subtarget.isPPC64() ? &PPC::G8RCRegClass
592                                   : &PPC::GPRCRegClass);
593 
594   // Make sure the register scavenger was able to find an available register
595   // If not, use R0 but return false to indicate no register was available and
596   // R0 must be used (as recommended by the ABI)
597   if (Reg == 0)
598     return false;
599 
600   if (ScratchRegister)
601     *ScratchRegister = Reg;
602 
603   return true;
604 }
605 
canUseAsPrologue(const MachineBasicBlock & MBB) const606 bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
607   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
608 
609   return findScratchRegister(TmpMBB, false, nullptr);
610 }
611 
canUseAsEpilogue(const MachineBasicBlock & MBB) const612 bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
613   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
614 
615   return findScratchRegister(TmpMBB, true, nullptr);
616 }
617 
emitPrologue(MachineFunction & MF,MachineBasicBlock & MBB) const618 void PPCFrameLowering::emitPrologue(MachineFunction &MF,
619                                     MachineBasicBlock &MBB) const {
620   MachineBasicBlock::iterator MBBI = MBB.begin();
621   MachineFrameInfo *MFI = MF.getFrameInfo();
622   const PPCInstrInfo &TII =
623       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
624   const PPCRegisterInfo *RegInfo =
625       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
626 
627   MachineModuleInfo &MMI = MF.getMMI();
628   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
629   DebugLoc dl;
630   bool needsCFI = MMI.hasDebugInfo() ||
631     MF.getFunction()->needsUnwindTableEntry();
632 
633   // Get processor type.
634   bool isPPC64 = Subtarget.isPPC64();
635   // Get the ABI.
636   bool isSVR4ABI = Subtarget.isSVR4ABI();
637   bool isELFv2ABI = Subtarget.isELFv2ABI();
638   assert((Subtarget.isDarwinABI() || isSVR4ABI) &&
639          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
640 
641   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
642   // process it.
643   if (!isSVR4ABI)
644     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
645       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
646         HandleVRSaveUpdate(MBBI, TII);
647         break;
648       }
649     }
650 
651   // Move MBBI back to the beginning of the prologue block.
652   MBBI = MBB.begin();
653 
654   // Work out frame sizes.
655   unsigned FrameSize = determineFrameLayout(MF);
656   int NegFrameSize = -FrameSize;
657   if (!isInt<32>(NegFrameSize))
658     llvm_unreachable("Unhandled stack size!");
659 
660   if (MFI->isFrameAddressTaken())
661     replaceFPWithRealFP(MF);
662 
663   // Check if the link register (LR) must be saved.
664   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
665   bool MustSaveLR = FI->mustSaveLR();
666   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
667   // Do we have a frame pointer and/or base pointer for this function?
668   bool HasFP = hasFP(MF);
669   bool HasBP = RegInfo->hasBasePointer(MF);
670 
671   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
672   unsigned BPReg       = RegInfo->getBaseRegister(MF);
673   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
674   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
675   unsigned ScratchReg  = 0;
676   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
677   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
678   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
679                                                 : PPC::MFLR );
680   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
681                                                  : PPC::STW );
682   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
683                                                      : PPC::STWU );
684   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
685                                                         : PPC::STWUX);
686   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
687                                                           : PPC::LIS );
688   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
689                                                  : PPC::ORI );
690   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
691                                               : PPC::OR );
692   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
693                                                             : PPC::SUBFC);
694   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
695                                                                : PPC::SUBFIC);
696 
697   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
698   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
699   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
700   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
701   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
702          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
703 
704   findScratchRegister(&MBB, false, &ScratchReg);
705   assert(ScratchReg && "No scratch register!");
706 
707   int LROffset = getReturnSaveOffset();
708 
709   int FPOffset = 0;
710   if (HasFP) {
711     if (isSVR4ABI) {
712       MachineFrameInfo *FFI = MF.getFrameInfo();
713       int FPIndex = FI->getFramePointerSaveIndex();
714       assert(FPIndex && "No Frame Pointer Save Slot!");
715       FPOffset = FFI->getObjectOffset(FPIndex);
716     } else {
717       FPOffset = getFramePointerSaveOffset();
718     }
719   }
720 
721   int BPOffset = 0;
722   if (HasBP) {
723     if (isSVR4ABI) {
724       MachineFrameInfo *FFI = MF.getFrameInfo();
725       int BPIndex = FI->getBasePointerSaveIndex();
726       assert(BPIndex && "No Base Pointer Save Slot!");
727       BPOffset = FFI->getObjectOffset(BPIndex);
728     } else {
729       BPOffset = getBasePointerSaveOffset();
730     }
731   }
732 
733   int PBPOffset = 0;
734   if (FI->usesPICBase()) {
735     MachineFrameInfo *FFI = MF.getFrameInfo();
736     int PBPIndex = FI->getPICBasePointerSaveIndex();
737     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
738     PBPOffset = FFI->getObjectOffset(PBPIndex);
739   }
740 
741   // Get stack alignments.
742   unsigned MaxAlign = MFI->getMaxAlignment();
743   if (HasBP && MaxAlign > 1)
744     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
745            "Invalid alignment!");
746 
747   // Frames of 32KB & larger require special handling because they cannot be
748   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
749   bool isLargeFrame = !isInt<16>(NegFrameSize);
750 
751   if (MustSaveLR)
752     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
753 
754   assert((isPPC64 || MustSaveCRs.empty()) &&
755          "Prologue CR saving supported only in 64-bit mode");
756 
757   if (!MustSaveCRs.empty()) { // will only occur for PPC64
758     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
759     // If only one or two CR fields are clobbered, it could be more
760     // efficient to use mfocrf to selectively save just those fields.
761     MachineInstrBuilder MIB =
762       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
763     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
764       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
765   }
766 
767   if (HasFP)
768     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
769     BuildMI(MBB, MBBI, dl, StoreInst)
770       .addReg(FPReg)
771       .addImm(FPOffset)
772       .addReg(SPReg);
773 
774   if (FI->usesPICBase())
775     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
776     BuildMI(MBB, MBBI, dl, StoreInst)
777       .addReg(PPC::R30)
778       .addImm(PBPOffset)
779       .addReg(SPReg);
780 
781   if (HasBP)
782     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
783     BuildMI(MBB, MBBI, dl, StoreInst)
784       .addReg(BPReg)
785       .addImm(BPOffset)
786       .addReg(SPReg);
787 
788   if (MustSaveLR)
789     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
790     BuildMI(MBB, MBBI, dl, StoreInst)
791       .addReg(ScratchReg)
792       .addImm(LROffset)
793       .addReg(SPReg);
794 
795   if (!MustSaveCRs.empty()) // will only occur for PPC64
796     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
797       .addReg(TempReg, getKillRegState(true))
798       .addImm(8)
799       .addReg(SPReg);
800 
801   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
802   if (!FrameSize) return;
803 
804   // Adjust stack pointer: r1 += NegFrameSize.
805   // If there is a preferred stack alignment, align R1 now
806 
807   if (HasBP) {
808     // Save a copy of r1 as the base pointer.
809     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
810       .addReg(SPReg)
811       .addReg(SPReg);
812   }
813 
814   if (HasBP && MaxAlign > 1) {
815     if (isPPC64)
816       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
817         .addReg(SPReg)
818         .addImm(0)
819         .addImm(64 - Log2_32(MaxAlign));
820     else // PPC32...
821       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
822         .addReg(SPReg)
823         .addImm(0)
824         .addImm(32 - Log2_32(MaxAlign))
825         .addImm(31);
826     if (!isLargeFrame) {
827       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
828         .addReg(ScratchReg, RegState::Kill)
829         .addImm(NegFrameSize);
830     } else {
831       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
832         .addImm(NegFrameSize >> 16);
833       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
834         .addReg(TempReg, RegState::Kill)
835         .addImm(NegFrameSize & 0xFFFF);
836       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
837         .addReg(ScratchReg, RegState::Kill)
838         .addReg(TempReg, RegState::Kill);
839     }
840     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
841       .addReg(SPReg, RegState::Kill)
842       .addReg(SPReg)
843       .addReg(ScratchReg);
844 
845   } else if (!isLargeFrame) {
846     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
847       .addReg(SPReg)
848       .addImm(NegFrameSize)
849       .addReg(SPReg);
850 
851   } else {
852     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
853       .addImm(NegFrameSize >> 16);
854     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
855       .addReg(ScratchReg, RegState::Kill)
856       .addImm(NegFrameSize & 0xFFFF);
857     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
858       .addReg(SPReg, RegState::Kill)
859       .addReg(SPReg)
860       .addReg(ScratchReg);
861   }
862 
863   // Add Call Frame Information for the instructions we generated above.
864   if (needsCFI) {
865     unsigned CFIIndex;
866 
867     if (HasBP) {
868       // Define CFA in terms of BP. Do this in preference to using FP/SP,
869       // because if the stack needed aligning then CFA won't be at a fixed
870       // offset from FP/SP.
871       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
872       CFIIndex = MMI.addFrameInst(
873           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
874     } else {
875       // Adjust the definition of CFA to account for the change in SP.
876       assert(NegFrameSize);
877       CFIIndex = MMI.addFrameInst(
878           MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
879     }
880     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
881         .addCFIIndex(CFIIndex);
882 
883     if (HasFP) {
884       // Describe where FP was saved, at a fixed offset from CFA.
885       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
886       CFIIndex = MMI.addFrameInst(
887           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
888       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
889           .addCFIIndex(CFIIndex);
890     }
891 
892     if (FI->usesPICBase()) {
893       // Describe where FP was saved, at a fixed offset from CFA.
894       unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
895       CFIIndex = MMI.addFrameInst(
896           MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
897       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
898           .addCFIIndex(CFIIndex);
899     }
900 
901     if (HasBP) {
902       // Describe where BP was saved, at a fixed offset from CFA.
903       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
904       CFIIndex = MMI.addFrameInst(
905           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
906       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
907           .addCFIIndex(CFIIndex);
908     }
909 
910     if (MustSaveLR) {
911       // Describe where LR was saved, at a fixed offset from CFA.
912       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
913       CFIIndex = MMI.addFrameInst(
914           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
915       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
916           .addCFIIndex(CFIIndex);
917     }
918   }
919 
920   // If there is a frame pointer, copy R1 into R31
921   if (HasFP) {
922     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
923       .addReg(SPReg)
924       .addReg(SPReg);
925 
926     if (!HasBP && needsCFI) {
927       // Change the definition of CFA from SP+offset to FP+offset, because SP
928       // will change at every alloca.
929       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
930       unsigned CFIIndex = MMI.addFrameInst(
931           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
932 
933       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
934           .addCFIIndex(CFIIndex);
935     }
936   }
937 
938   if (needsCFI) {
939     // Describe where callee saved registers were saved, at fixed offsets from
940     // CFA.
941     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
942     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
943       unsigned Reg = CSI[I].getReg();
944       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
945 
946       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
947       // subregisters of CR2. We just need to emit a move of CR2.
948       if (PPC::CRBITRCRegClass.contains(Reg))
949         continue;
950 
951       // For SVR4, don't emit a move for the CR spill slot if we haven't
952       // spilled CRs.
953       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
954           && MustSaveCRs.empty())
955         continue;
956 
957       // For 64-bit SVR4 when we have spilled CRs, the spill location
958       // is SP+8, not a frame-relative slot.
959       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
960         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
961         // the whole CR word.  In the ELFv2 ABI, every CR that was
962         // actually saved gets its own CFI record.
963         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
964         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
965             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
966         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
967             .addCFIIndex(CFIIndex);
968         continue;
969       }
970 
971       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
972       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
973           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
974       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
975           .addCFIIndex(CFIIndex);
976     }
977   }
978 }
979 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const980 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
981                                     MachineBasicBlock &MBB) const {
982   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
983   DebugLoc dl;
984 
985   if (MBBI != MBB.end())
986     dl = MBBI->getDebugLoc();
987 
988   const PPCInstrInfo &TII =
989       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
990   const PPCRegisterInfo *RegInfo =
991       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
992 
993   // Get alignment info so we know how to restore the SP.
994   const MachineFrameInfo *MFI = MF.getFrameInfo();
995 
996   // Get the number of bytes allocated from the FrameInfo.
997   int FrameSize = MFI->getStackSize();
998 
999   // Get processor type.
1000   bool isPPC64 = Subtarget.isPPC64();
1001   // Get the ABI.
1002   bool isSVR4ABI = Subtarget.isSVR4ABI();
1003 
1004   // Check if the link register (LR) has been saved.
1005   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1006   bool MustSaveLR = FI->mustSaveLR();
1007   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
1008   // Do we have a frame pointer and/or base pointer for this function?
1009   bool HasFP = hasFP(MF);
1010   bool HasBP = RegInfo->hasBasePointer(MF);
1011 
1012   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
1013   unsigned BPReg      = RegInfo->getBaseRegister(MF);
1014   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
1015   unsigned ScratchReg = 0;
1016   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
1017   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
1018                                                  : PPC::MTLR );
1019   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
1020                                                  : PPC::LWZ );
1021   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
1022                                                            : PPC::LIS );
1023   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
1024                                                   : PPC::ORI );
1025   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
1026                                                    : PPC::ADDI );
1027   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
1028                                                 : PPC::ADD4 );
1029 
1030   int LROffset = getReturnSaveOffset();
1031 
1032   int FPOffset = 0;
1033 
1034   findScratchRegister(&MBB, true, &ScratchReg);
1035   assert(ScratchReg && "No scratch register!");
1036 
1037   if (HasFP) {
1038     if (isSVR4ABI) {
1039       MachineFrameInfo *FFI = MF.getFrameInfo();
1040       int FPIndex = FI->getFramePointerSaveIndex();
1041       assert(FPIndex && "No Frame Pointer Save Slot!");
1042       FPOffset = FFI->getObjectOffset(FPIndex);
1043     } else {
1044       FPOffset = getFramePointerSaveOffset();
1045     }
1046   }
1047 
1048   int BPOffset = 0;
1049   if (HasBP) {
1050     if (isSVR4ABI) {
1051       MachineFrameInfo *FFI = MF.getFrameInfo();
1052       int BPIndex = FI->getBasePointerSaveIndex();
1053       assert(BPIndex && "No Base Pointer Save Slot!");
1054       BPOffset = FFI->getObjectOffset(BPIndex);
1055     } else {
1056       BPOffset = getBasePointerSaveOffset();
1057     }
1058   }
1059 
1060   int PBPOffset = 0;
1061   if (FI->usesPICBase()) {
1062     MachineFrameInfo *FFI = MF.getFrameInfo();
1063     int PBPIndex = FI->getPICBasePointerSaveIndex();
1064     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1065     PBPOffset = FFI->getObjectOffset(PBPIndex);
1066   }
1067 
1068   bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
1069 
1070   if (IsReturnBlock) {
1071     unsigned RetOpcode = MBBI->getOpcode();
1072     bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
1073                       RetOpcode == PPC::TCRETURNdi ||
1074                       RetOpcode == PPC::TCRETURNai ||
1075                       RetOpcode == PPC::TCRETURNri8 ||
1076                       RetOpcode == PPC::TCRETURNdi8 ||
1077                       RetOpcode == PPC::TCRETURNai8;
1078 
1079     if (UsesTCRet) {
1080       int MaxTCRetDelta = FI->getTailCallSPDelta();
1081       MachineOperand &StackAdjust = MBBI->getOperand(1);
1082       assert(StackAdjust.isImm() && "Expecting immediate value.");
1083       // Adjust stack pointer.
1084       int StackAdj = StackAdjust.getImm();
1085       int Delta = StackAdj - MaxTCRetDelta;
1086       assert((Delta >= 0) && "Delta must be positive");
1087       if (MaxTCRetDelta>0)
1088         FrameSize += (StackAdj +Delta);
1089       else
1090         FrameSize += StackAdj;
1091     }
1092   }
1093 
1094   // Frames of 32KB & larger require special handling because they cannot be
1095   // indexed into with a simple LD/LWZ immediate offset operand.
1096   bool isLargeFrame = !isInt<16>(FrameSize);
1097 
1098   if (FrameSize) {
1099     // In the prologue, the loaded (or persistent) stack pointer value is offset
1100     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
1101 
1102     // If this function contained a fastcc call and GuaranteedTailCallOpt is
1103     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1104     // call which invalidates the stack pointer value in SP(0). So we use the
1105     // value of R31 in this case.
1106     if (FI->hasFastCall()) {
1107       assert(HasFP && "Expecting a valid frame pointer.");
1108       if (!isLargeFrame) {
1109         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1110           .addReg(FPReg).addImm(FrameSize);
1111       } else {
1112         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1113           .addImm(FrameSize >> 16);
1114         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1115           .addReg(ScratchReg, RegState::Kill)
1116           .addImm(FrameSize & 0xFFFF);
1117         BuildMI(MBB, MBBI, dl, AddInst)
1118           .addReg(SPReg)
1119           .addReg(FPReg)
1120           .addReg(ScratchReg);
1121       }
1122     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1123       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1124         .addReg(SPReg)
1125         .addImm(FrameSize);
1126     } else {
1127       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1128         .addImm(0)
1129         .addReg(SPReg);
1130     }
1131   }
1132 
1133   if (MustSaveLR)
1134     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1135       .addImm(LROffset)
1136       .addReg(SPReg);
1137 
1138   assert((isPPC64 || MustSaveCRs.empty()) &&
1139          "Epilogue CR restoring supported only in 64-bit mode");
1140 
1141   if (!MustSaveCRs.empty()) // will only occur for PPC64
1142     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1143       .addImm(8)
1144       .addReg(SPReg);
1145 
1146   if (HasFP)
1147     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1148       .addImm(FPOffset)
1149       .addReg(SPReg);
1150 
1151   if (FI->usesPICBase())
1152     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1153     BuildMI(MBB, MBBI, dl, LoadInst)
1154       .addReg(PPC::R30)
1155       .addImm(PBPOffset)
1156       .addReg(SPReg);
1157 
1158   if (HasBP)
1159     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1160       .addImm(BPOffset)
1161       .addReg(SPReg);
1162 
1163   if (!MustSaveCRs.empty()) // will only occur for PPC64
1164     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1165       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1166         .addReg(TempReg, getKillRegState(i == e-1));
1167 
1168   if (MustSaveLR)
1169     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1170 
1171   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1172   // call optimization
1173   if (IsReturnBlock) {
1174     unsigned RetOpcode = MBBI->getOpcode();
1175     if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1176         (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1177         MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1178       PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1179       unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1180 
1181       if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1182         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1183           .addReg(SPReg).addImm(CallerAllocatedAmt);
1184       } else {
1185         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1186           .addImm(CallerAllocatedAmt >> 16);
1187         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1188           .addReg(ScratchReg, RegState::Kill)
1189           .addImm(CallerAllocatedAmt & 0xFFFF);
1190         BuildMI(MBB, MBBI, dl, AddInst)
1191           .addReg(SPReg)
1192           .addReg(FPReg)
1193           .addReg(ScratchReg);
1194       }
1195     } else if (RetOpcode == PPC::TCRETURNdi) {
1196       MBBI = MBB.getLastNonDebugInstr();
1197       MachineOperand &JumpTarget = MBBI->getOperand(0);
1198       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1199         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1200     } else if (RetOpcode == PPC::TCRETURNri) {
1201       MBBI = MBB.getLastNonDebugInstr();
1202       assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1203       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1204     } else if (RetOpcode == PPC::TCRETURNai) {
1205       MBBI = MBB.getLastNonDebugInstr();
1206       MachineOperand &JumpTarget = MBBI->getOperand(0);
1207       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1208     } else if (RetOpcode == PPC::TCRETURNdi8) {
1209       MBBI = MBB.getLastNonDebugInstr();
1210       MachineOperand &JumpTarget = MBBI->getOperand(0);
1211       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1212         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1213     } else if (RetOpcode == PPC::TCRETURNri8) {
1214       MBBI = MBB.getLastNonDebugInstr();
1215       assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1216       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1217     } else if (RetOpcode == PPC::TCRETURNai8) {
1218       MBBI = MBB.getLastNonDebugInstr();
1219       MachineOperand &JumpTarget = MBBI->getOperand(0);
1220       BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1221     }
1222   }
1223 }
1224 
determineCalleeSaves(MachineFunction & MF,BitVector & SavedRegs,RegScavenger * RS) const1225 void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,
1226                                             BitVector &SavedRegs,
1227                                             RegScavenger *RS) const {
1228   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1229 
1230   const PPCRegisterInfo *RegInfo =
1231       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1232 
1233   //  Save and clear the LR state.
1234   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1235   unsigned LR = RegInfo->getRARegister();
1236   FI->setMustSaveLR(MustSaveLR(MF, LR));
1237   SavedRegs.reset(LR);
1238 
1239   //  Save R31 if necessary
1240   int FPSI = FI->getFramePointerSaveIndex();
1241   bool isPPC64 = Subtarget.isPPC64();
1242   bool isDarwinABI  = Subtarget.isDarwinABI();
1243   MachineFrameInfo *MFI = MF.getFrameInfo();
1244 
1245   // If the frame pointer save index hasn't been defined yet.
1246   if (!FPSI && needsFP(MF)) {
1247     // Find out what the fix offset of the frame pointer save area.
1248     int FPOffset = getFramePointerSaveOffset();
1249     // Allocate the frame index for frame pointer save area.
1250     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1251     // Save the result.
1252     FI->setFramePointerSaveIndex(FPSI);
1253   }
1254 
1255   int BPSI = FI->getBasePointerSaveIndex();
1256   if (!BPSI && RegInfo->hasBasePointer(MF)) {
1257     int BPOffset = getBasePointerSaveOffset();
1258     // Allocate the frame index for the base pointer save area.
1259     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1260     // Save the result.
1261     FI->setBasePointerSaveIndex(BPSI);
1262   }
1263 
1264   // Reserve stack space for the PIC Base register (R30).
1265   // Only used in SVR4 32-bit.
1266   if (FI->usesPICBase()) {
1267     int PBPSI = MFI->CreateFixedObject(4, -8, true);
1268     FI->setPICBasePointerSaveIndex(PBPSI);
1269   }
1270 
1271   // Reserve stack space to move the linkage area to in case of a tail call.
1272   int TCSPDelta = 0;
1273   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1274       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1275     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1276   }
1277 
1278   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1279   // function uses CR 2, 3, or 4.
1280   if (!isPPC64 && !isDarwinABI &&
1281       (SavedRegs.test(PPC::CR2) ||
1282        SavedRegs.test(PPC::CR3) ||
1283        SavedRegs.test(PPC::CR4))) {
1284     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1285     FI->setCRSpillFrameIndex(FrameIdx);
1286   }
1287 }
1288 
processFunctionBeforeFrameFinalized(MachineFunction & MF,RegScavenger * RS) const1289 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1290                                                        RegScavenger *RS) const {
1291   // Early exit if not using the SVR4 ABI.
1292   if (!Subtarget.isSVR4ABI()) {
1293     addScavengingSpillSlot(MF, RS);
1294     return;
1295   }
1296 
1297   // Get callee saved register information.
1298   MachineFrameInfo *FFI = MF.getFrameInfo();
1299   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1300 
1301   // Early exit if no callee saved registers are modified!
1302   if (CSI.empty() && !needsFP(MF)) {
1303     addScavengingSpillSlot(MF, RS);
1304     return;
1305   }
1306 
1307   unsigned MinGPR = PPC::R31;
1308   unsigned MinG8R = PPC::X31;
1309   unsigned MinFPR = PPC::F31;
1310   unsigned MinVR = PPC::V31;
1311 
1312   bool HasGPSaveArea = false;
1313   bool HasG8SaveArea = false;
1314   bool HasFPSaveArea = false;
1315   bool HasVRSAVESaveArea = false;
1316   bool HasVRSaveArea = false;
1317 
1318   SmallVector<CalleeSavedInfo, 18> GPRegs;
1319   SmallVector<CalleeSavedInfo, 18> G8Regs;
1320   SmallVector<CalleeSavedInfo, 18> FPRegs;
1321   SmallVector<CalleeSavedInfo, 18> VRegs;
1322 
1323   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1324     unsigned Reg = CSI[i].getReg();
1325     if (PPC::GPRCRegClass.contains(Reg)) {
1326       HasGPSaveArea = true;
1327 
1328       GPRegs.push_back(CSI[i]);
1329 
1330       if (Reg < MinGPR) {
1331         MinGPR = Reg;
1332       }
1333     } else if (PPC::G8RCRegClass.contains(Reg)) {
1334       HasG8SaveArea = true;
1335 
1336       G8Regs.push_back(CSI[i]);
1337 
1338       if (Reg < MinG8R) {
1339         MinG8R = Reg;
1340       }
1341     } else if (PPC::F8RCRegClass.contains(Reg)) {
1342       HasFPSaveArea = true;
1343 
1344       FPRegs.push_back(CSI[i]);
1345 
1346       if (Reg < MinFPR) {
1347         MinFPR = Reg;
1348       }
1349     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1350                PPC::CRRCRegClass.contains(Reg)) {
1351       ; // do nothing, as we already know whether CRs are spilled
1352     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1353       HasVRSAVESaveArea = true;
1354     } else if (PPC::VRRCRegClass.contains(Reg)) {
1355       HasVRSaveArea = true;
1356 
1357       VRegs.push_back(CSI[i]);
1358 
1359       if (Reg < MinVR) {
1360         MinVR = Reg;
1361       }
1362     } else {
1363       llvm_unreachable("Unknown RegisterClass!");
1364     }
1365   }
1366 
1367   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1368   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1369 
1370   int64_t LowerBound = 0;
1371 
1372   // Take into account stack space reserved for tail calls.
1373   int TCSPDelta = 0;
1374   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1375       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1376     LowerBound = TCSPDelta;
1377   }
1378 
1379   // The Floating-point register save area is right below the back chain word
1380   // of the previous stack frame.
1381   if (HasFPSaveArea) {
1382     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1383       int FI = FPRegs[i].getFrameIdx();
1384 
1385       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1386     }
1387 
1388     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1389   }
1390 
1391   // Check whether the frame pointer register is allocated. If so, make sure it
1392   // is spilled to the correct offset.
1393   if (needsFP(MF)) {
1394     HasGPSaveArea = true;
1395 
1396     int FI = PFI->getFramePointerSaveIndex();
1397     assert(FI && "No Frame Pointer Save Slot!");
1398 
1399     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1400   }
1401 
1402   if (PFI->usesPICBase()) {
1403     HasGPSaveArea = true;
1404 
1405     int FI = PFI->getPICBasePointerSaveIndex();
1406     assert(FI && "No PIC Base Pointer Save Slot!");
1407 
1408     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1409   }
1410 
1411   const PPCRegisterInfo *RegInfo =
1412       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1413   if (RegInfo->hasBasePointer(MF)) {
1414     HasGPSaveArea = true;
1415 
1416     int FI = PFI->getBasePointerSaveIndex();
1417     assert(FI && "No Base Pointer Save Slot!");
1418 
1419     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1420   }
1421 
1422   // General register save area starts right below the Floating-point
1423   // register save area.
1424   if (HasGPSaveArea || HasG8SaveArea) {
1425     // Move general register save area spill slots down, taking into account
1426     // the size of the Floating-point register save area.
1427     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1428       int FI = GPRegs[i].getFrameIdx();
1429 
1430       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1431     }
1432 
1433     // Move general register save area spill slots down, taking into account
1434     // the size of the Floating-point register save area.
1435     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1436       int FI = G8Regs[i].getFrameIdx();
1437 
1438       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1439     }
1440 
1441     unsigned MinReg =
1442       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1443                          TRI->getEncodingValue(MinG8R));
1444 
1445     if (Subtarget.isPPC64()) {
1446       LowerBound -= (31 - MinReg + 1) * 8;
1447     } else {
1448       LowerBound -= (31 - MinReg + 1) * 4;
1449     }
1450   }
1451 
1452   // For 32-bit only, the CR save area is below the general register
1453   // save area.  For 64-bit SVR4, the CR save area is addressed relative
1454   // to the stack pointer and hence does not need an adjustment here.
1455   // Only CR2 (the first nonvolatile spilled) has an associated frame
1456   // index so that we have a single uniform save area.
1457   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1458     // Adjust the frame index of the CR spill slot.
1459     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1460       unsigned Reg = CSI[i].getReg();
1461 
1462       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1463           // Leave Darwin logic as-is.
1464           || (!Subtarget.isSVR4ABI() &&
1465               (PPC::CRBITRCRegClass.contains(Reg) ||
1466                PPC::CRRCRegClass.contains(Reg)))) {
1467         int FI = CSI[i].getFrameIdx();
1468 
1469         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1470       }
1471     }
1472 
1473     LowerBound -= 4; // The CR save area is always 4 bytes long.
1474   }
1475 
1476   if (HasVRSAVESaveArea) {
1477     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1478     //             which have the VRSAVE register class?
1479     // Adjust the frame index of the VRSAVE spill slot.
1480     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1481       unsigned Reg = CSI[i].getReg();
1482 
1483       if (PPC::VRSAVERCRegClass.contains(Reg)) {
1484         int FI = CSI[i].getFrameIdx();
1485 
1486         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1487       }
1488     }
1489 
1490     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1491   }
1492 
1493   if (HasVRSaveArea) {
1494     // Insert alignment padding, we need 16-byte alignment.
1495     LowerBound = (LowerBound - 15) & ~(15);
1496 
1497     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1498       int FI = VRegs[i].getFrameIdx();
1499 
1500       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1501     }
1502   }
1503 
1504   addScavengingSpillSlot(MF, RS);
1505 }
1506 
1507 void
addScavengingSpillSlot(MachineFunction & MF,RegScavenger * RS) const1508 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1509                                          RegScavenger *RS) const {
1510   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1511   // a large stack, which will require scavenging a register to materialize a
1512   // large offset.
1513 
1514   // We need to have a scavenger spill slot for spills if the frame size is
1515   // large. In case there is no free register for large-offset addressing,
1516   // this slot is used for the necessary emergency spill. Also, we need the
1517   // slot for dynamic stack allocations.
1518 
1519   // The scavenger might be invoked if the frame offset does not fit into
1520   // the 16-bit immediate. We don't know the complete frame size here
1521   // because we've not yet computed callee-saved register spills or the
1522   // needed alignment padding.
1523   unsigned StackSize = determineFrameLayout(MF, false, true);
1524   MachineFrameInfo *MFI = MF.getFrameInfo();
1525   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1526       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1527     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1528     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1529     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1530     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1531                                                        RC->getAlignment(),
1532                                                        false));
1533 
1534     // Might we have over-aligned allocas?
1535     bool HasAlVars = MFI->hasVarSizedObjects() &&
1536                      MFI->getMaxAlignment() > getStackAlignment();
1537 
1538     // These kinds of spills might need two registers.
1539     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1540       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1541                                                          RC->getAlignment(),
1542                                                          false));
1543 
1544   }
1545 }
1546 
1547 bool
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const std::vector<CalleeSavedInfo> & CSI,const TargetRegisterInfo * TRI) const1548 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1549                                      MachineBasicBlock::iterator MI,
1550                                      const std::vector<CalleeSavedInfo> &CSI,
1551                                      const TargetRegisterInfo *TRI) const {
1552 
1553   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1554   // Return false otherwise to maintain pre-existing behavior.
1555   if (!Subtarget.isSVR4ABI())
1556     return false;
1557 
1558   MachineFunction *MF = MBB.getParent();
1559   const PPCInstrInfo &TII =
1560       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1561   DebugLoc DL;
1562   bool CRSpilled = false;
1563   MachineInstrBuilder CRMIB;
1564 
1565   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1566     unsigned Reg = CSI[i].getReg();
1567     // Only Darwin actually uses the VRSAVE register, but it can still appear
1568     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1569     // Darwin, ignore it.
1570     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1571       continue;
1572 
1573     // CR2 through CR4 are the nonvolatile CR fields.
1574     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1575 
1576     // Add the callee-saved register as live-in; it's killed at the spill.
1577     MBB.addLiveIn(Reg);
1578 
1579     if (CRSpilled && IsCRField) {
1580       CRMIB.addReg(Reg, RegState::ImplicitKill);
1581       continue;
1582     }
1583 
1584     // Insert the spill to the stack frame.
1585     if (IsCRField) {
1586       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1587       if (Subtarget.isPPC64()) {
1588         // The actual spill will happen at the start of the prologue.
1589         FuncInfo->addMustSaveCR(Reg);
1590       } else {
1591         CRSpilled = true;
1592         FuncInfo->setSpillsCR();
1593 
1594         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
1595         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1596         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1597                   .addReg(Reg, RegState::ImplicitKill);
1598 
1599         MBB.insert(MI, CRMIB);
1600         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1601                                          .addReg(PPC::R12,
1602                                                  getKillRegState(true)),
1603                                          CSI[i].getFrameIdx()));
1604       }
1605     } else {
1606       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1607       TII.storeRegToStackSlot(MBB, MI, Reg, true,
1608                               CSI[i].getFrameIdx(), RC, TRI);
1609     }
1610   }
1611   return true;
1612 }
1613 
1614 static void
restoreCRs(bool isPPC64,bool is31,bool CR2Spilled,bool CR3Spilled,bool CR4Spilled,MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const std::vector<CalleeSavedInfo> & CSI,unsigned CSIIndex)1615 restoreCRs(bool isPPC64, bool is31,
1616            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1617            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1618            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1619 
1620   MachineFunction *MF = MBB.getParent();
1621   const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1622   DebugLoc DL;
1623   unsigned RestoreOp, MoveReg;
1624 
1625   if (isPPC64)
1626     // This is handled during epilogue generation.
1627     return;
1628   else {
1629     // 32-bit:  FP-relative
1630     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1631                                              PPC::R12),
1632                                      CSI[CSIIndex].getFrameIdx()));
1633     RestoreOp = PPC::MTOCRF;
1634     MoveReg = PPC::R12;
1635   }
1636 
1637   if (CR2Spilled)
1638     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1639                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1640 
1641   if (CR3Spilled)
1642     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1643                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1644 
1645   if (CR4Spilled)
1646     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1647                .addReg(MoveReg, getKillRegState(true)));
1648 }
1649 
1650 void PPCFrameLowering::
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const1651 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1652                               MachineBasicBlock::iterator I) const {
1653   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1654   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1655       I->getOpcode() == PPC::ADJCALLSTACKUP) {
1656     // Add (actually subtract) back the amount the callee popped on return.
1657     if (int CalleeAmt =  I->getOperand(1).getImm()) {
1658       bool is64Bit = Subtarget.isPPC64();
1659       CalleeAmt *= -1;
1660       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1661       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1662       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1663       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1664       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1665       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1666       MachineInstr *MI = I;
1667       DebugLoc dl = MI->getDebugLoc();
1668 
1669       if (isInt<16>(CalleeAmt)) {
1670         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1671           .addReg(StackReg, RegState::Kill)
1672           .addImm(CalleeAmt);
1673       } else {
1674         MachineBasicBlock::iterator MBBI = I;
1675         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1676           .addImm(CalleeAmt >> 16);
1677         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1678           .addReg(TmpReg, RegState::Kill)
1679           .addImm(CalleeAmt & 0xFFFF);
1680         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1681           .addReg(StackReg, RegState::Kill)
1682           .addReg(TmpReg);
1683       }
1684     }
1685   }
1686   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1687   MBB.erase(I);
1688 }
1689 
1690 bool
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const std::vector<CalleeSavedInfo> & CSI,const TargetRegisterInfo * TRI) const1691 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1692                                         MachineBasicBlock::iterator MI,
1693                                         const std::vector<CalleeSavedInfo> &CSI,
1694                                         const TargetRegisterInfo *TRI) const {
1695 
1696   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1697   // Return false otherwise to maintain pre-existing behavior.
1698   if (!Subtarget.isSVR4ABI())
1699     return false;
1700 
1701   MachineFunction *MF = MBB.getParent();
1702   const PPCInstrInfo &TII =
1703       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1704   bool CR2Spilled = false;
1705   bool CR3Spilled = false;
1706   bool CR4Spilled = false;
1707   unsigned CSIIndex = 0;
1708 
1709   // Initialize insertion-point logic; we will be restoring in reverse
1710   // order of spill.
1711   MachineBasicBlock::iterator I = MI, BeforeI = I;
1712   bool AtStart = I == MBB.begin();
1713 
1714   if (!AtStart)
1715     --BeforeI;
1716 
1717   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1718     unsigned Reg = CSI[i].getReg();
1719 
1720     // Only Darwin actually uses the VRSAVE register, but it can still appear
1721     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1722     // Darwin, ignore it.
1723     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1724       continue;
1725 
1726     if (Reg == PPC::CR2) {
1727       CR2Spilled = true;
1728       // The spill slot is associated only with CR2, which is the
1729       // first nonvolatile spilled.  Save it here.
1730       CSIIndex = i;
1731       continue;
1732     } else if (Reg == PPC::CR3) {
1733       CR3Spilled = true;
1734       continue;
1735     } else if (Reg == PPC::CR4) {
1736       CR4Spilled = true;
1737       continue;
1738     } else {
1739       // When we first encounter a non-CR register after seeing at
1740       // least one CR register, restore all spilled CRs together.
1741       if ((CR2Spilled || CR3Spilled || CR4Spilled)
1742           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1743         bool is31 = needsFP(*MF);
1744         restoreCRs(Subtarget.isPPC64(), is31,
1745                    CR2Spilled, CR3Spilled, CR4Spilled,
1746                    MBB, I, CSI, CSIIndex);
1747         CR2Spilled = CR3Spilled = CR4Spilled = false;
1748       }
1749 
1750       // Default behavior for non-CR saves.
1751       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1752       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1753                                RC, TRI);
1754       assert(I != MBB.begin() &&
1755              "loadRegFromStackSlot didn't insert any code!");
1756       }
1757 
1758     // Insert in reverse order.
1759     if (AtStart)
1760       I = MBB.begin();
1761     else {
1762       I = BeforeI;
1763       ++I;
1764     }
1765   }
1766 
1767   // If we haven't yet spilled the CRs, do so now.
1768   if (CR2Spilled || CR3Spilled || CR4Spilled) {
1769     bool is31 = needsFP(*MF);
1770     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1771                MBB, I, CSI, CSIIndex);
1772   }
1773 
1774   return true;
1775 }
1776 
enableShrinkWrapping(const MachineFunction & MF) const1777 bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1778   return (MF.getSubtarget<PPCSubtarget>().isSVR4ABI() &&
1779           MF.getSubtarget<PPCSubtarget>().isPPC64());
1780 }
1781