The base pointer save offset can be computed at initialization time,
[oota-llvm.git] / lib / Target / PowerPC / PPCFrameLowering.cpp
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 uint16_t 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
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
47 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
48   return STI.isELFv2ABI() ? 24 : 40;
49 }
50
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
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
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
84 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
85     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
86                           (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 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.
94 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.
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->empty() && I->back().isReturn()) {
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.
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   unsigned UsedRegMask = 0;
310   for (unsigned i = 0; i != 32; ++i)
311     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
312       UsedRegMask |= 1 << (31-i);
313
314   // Live in and live out values already must be in the mask, so don't bother
315   // marking them.
316   for (MachineRegisterInfo::livein_iterator
317        I = MF->getRegInfo().livein_begin(),
318        E = MF->getRegInfo().livein_end(); I != E; ++I) {
319     unsigned RegNo = TRI->getEncodingValue(I->first);
320     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
321       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
322   }
323
324   // Live out registers appear as use operands on return instructions.
325   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
326        UsedRegMask != 0 && BI != BE; ++BI) {
327     const MachineBasicBlock &MBB = *BI;
328     if (MBB.empty() || !MBB.back().isReturn())
329       continue;
330     const MachineInstr &Ret = MBB.back();
331     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
332       const MachineOperand &MO = Ret.getOperand(I);
333       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
334         continue;
335       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
336       UsedRegMask &= ~(1 << (31-RegNo));
337     }
338   }
339
340   // If no registers are used, turn this into a copy.
341   if (UsedRegMask == 0) {
342     // Remove all VRSAVE code.
343     RemoveVRSaveCode(MI);
344     return;
345   }
346
347   unsigned SrcReg = MI->getOperand(1).getReg();
348   unsigned DstReg = MI->getOperand(0).getReg();
349
350   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
351     if (DstReg != SrcReg)
352       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
353         .addReg(SrcReg)
354         .addImm(UsedRegMask);
355     else
356       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
357         .addReg(SrcReg, RegState::Kill)
358         .addImm(UsedRegMask);
359   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
360     if (DstReg != SrcReg)
361       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
362         .addReg(SrcReg)
363         .addImm(UsedRegMask >> 16);
364     else
365       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
366         .addReg(SrcReg, RegState::Kill)
367         .addImm(UsedRegMask >> 16);
368   } else {
369     if (DstReg != SrcReg)
370       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
371         .addReg(SrcReg)
372         .addImm(UsedRegMask >> 16);
373     else
374       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
375         .addReg(SrcReg, RegState::Kill)
376         .addImm(UsedRegMask >> 16);
377
378     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
379       .addReg(DstReg, RegState::Kill)
380       .addImm(UsedRegMask & 0xFFFF);
381   }
382
383   // Remove the old UPDATE_VRSAVE instruction.
384   MI->eraseFromParent();
385 }
386
387 static bool spillsCR(const MachineFunction &MF) {
388   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
389   return FuncInfo->isCRSpilled();
390 }
391
392 static bool spillsVRSAVE(const MachineFunction &MF) {
393   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
394   return FuncInfo->isVRSAVESpilled();
395 }
396
397 static bool hasSpills(const MachineFunction &MF) {
398   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
399   return FuncInfo->hasSpills();
400 }
401
402 static bool hasNonRISpills(const MachineFunction &MF) {
403   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
404   return FuncInfo->hasNonRISpills();
405 }
406
407 /// MustSaveLR - Return true if this function requires that we save the LR
408 /// register onto the stack in the prolog and restore it in the epilog of the
409 /// function.
410 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
411   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
412
413   // We need a save/restore of LR if there is any def of LR (which is
414   // defined by calls, including the PIC setup sequence), or if there is
415   // some use of the LR stack slot (e.g. for builtin_return_address).
416   // (LR comes in 32 and 64 bit versions.)
417   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
418   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
419 }
420
421 /// determineFrameLayout - Determine the size of the frame and maximum call
422 /// frame size.
423 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
424                                                 bool UpdateMF,
425                                                 bool UseEstimate) const {
426   MachineFrameInfo *MFI = MF.getFrameInfo();
427
428   // Get the number of bytes to allocate from the FrameInfo
429   unsigned FrameSize =
430     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
431
432   // Get stack alignments. The frame must be aligned to the greatest of these:
433   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
434   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
435   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
436
437   const PPCRegisterInfo *RegInfo =
438       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
439
440   // If we are a leaf function, and use up to 224 bytes of stack space,
441   // don't have a frame pointer, calls, or dynamic alloca then we do not need
442   // to adjust the stack pointer (we fit in the Red Zone).
443   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
444   // stackless code if all local vars are reg-allocated.
445   bool DisableRedZone = MF.getFunction()->getAttributes().
446     hasAttribute(AttributeSet::FunctionIndex, 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.
494 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.
505 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()->getAttributes().hasAttribute(
511           AttributeSet::FunctionIndex, Attribute::Naked))
512     return false;
513
514   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
515     MFI->hasVarSizedObjects() ||
516     MFI->hasStackMap() || MFI->hasPatchPoint() ||
517     (MF.getTarget().Options.GuaranteedTailCallOpt &&
518      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
519 }
520
521 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
522   bool is31 = needsFP(MF);
523   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
524   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
525
526   const PPCRegisterInfo *RegInfo =
527       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
528   bool HasBP = RegInfo->hasBasePointer(MF);
529   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
530   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
531
532   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
533        BI != BE; ++BI)
534     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
535       --MBBI;
536       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
537         MachineOperand &MO = MBBI->getOperand(I);
538         if (!MO.isReg())
539           continue;
540
541         switch (MO.getReg()) {
542         case PPC::FP:
543           MO.setReg(FPReg);
544           break;
545         case PPC::FP8:
546           MO.setReg(FP8Reg);
547           break;
548         case PPC::BP:
549           MO.setReg(BPReg);
550           break;
551         case PPC::BP8:
552           MO.setReg(BP8Reg);
553           break;
554
555         }
556       }
557     }
558 }
559
560 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
561   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
562   MachineBasicBlock::iterator MBBI = MBB.begin();
563   MachineFrameInfo *MFI = MF.getFrameInfo();
564   const PPCInstrInfo &TII =
565       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
566   const PPCRegisterInfo *RegInfo =
567       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
568
569   MachineModuleInfo &MMI = MF.getMMI();
570   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
571   DebugLoc dl;
572   bool needsCFI = MMI.hasDebugInfo() ||
573     MF.getFunction()->needsUnwindTableEntry();
574
575   // Get processor type.
576   bool isPPC64 = Subtarget.isPPC64();
577   // Get the ABI.
578   bool isDarwinABI = Subtarget.isDarwinABI();
579   bool isSVR4ABI = Subtarget.isSVR4ABI();
580   bool isELFv2ABI = Subtarget.isELFv2ABI();
581   assert((isDarwinABI || isSVR4ABI) &&
582          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
583
584   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
585   // process it.
586   if (!isSVR4ABI)
587     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
588       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
589         HandleVRSaveUpdate(MBBI, TII);
590         break;
591       }
592     }
593
594   // Move MBBI back to the beginning of the function.
595   MBBI = MBB.begin();
596
597   // Work out frame sizes.
598   unsigned FrameSize = determineFrameLayout(MF);
599   int NegFrameSize = -FrameSize;
600   if (!isInt<32>(NegFrameSize))
601     llvm_unreachable("Unhandled stack size!");
602
603   if (MFI->isFrameAddressTaken())
604     replaceFPWithRealFP(MF);
605
606   // Check if the link register (LR) must be saved.
607   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
608   bool MustSaveLR = FI->mustSaveLR();
609   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
610   // Do we have a frame pointer and/or base pointer for this function?
611   bool HasFP = hasFP(MF);
612   bool HasBP = RegInfo->hasBasePointer(MF);
613
614   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
615   unsigned BPReg       = RegInfo->getBaseRegister(MF);
616   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
617   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
618   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
619   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
620   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
621   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
622                                                 : PPC::MFLR );
623   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
624                                                  : PPC::STW );
625   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
626                                                      : PPC::STWU );
627   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
628                                                         : PPC::STWUX);
629   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
630                                                           : PPC::LIS );
631   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
632                                                  : PPC::ORI );
633   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
634                                               : PPC::OR );
635   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
636                                                             : PPC::SUBFC);
637   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
638                                                                : PPC::SUBFIC);
639
640   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
641   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
642   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
643   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
644   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
645          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
646
647   int LROffset = getReturnSaveOffset();
648
649   int FPOffset = 0;
650   if (HasFP) {
651     if (isSVR4ABI) {
652       MachineFrameInfo *FFI = MF.getFrameInfo();
653       int FPIndex = FI->getFramePointerSaveIndex();
654       assert(FPIndex && "No Frame Pointer Save Slot!");
655       FPOffset = FFI->getObjectOffset(FPIndex);
656     } else {
657       FPOffset = getFramePointerSaveOffset();
658     }
659   }
660
661   int BPOffset = 0;
662   if (HasBP) {
663     if (isSVR4ABI) {
664       MachineFrameInfo *FFI = MF.getFrameInfo();
665       int BPIndex = FI->getBasePointerSaveIndex();
666       assert(BPIndex && "No Base Pointer Save Slot!");
667       BPOffset = FFI->getObjectOffset(BPIndex);
668     } else {
669       BPOffset = getBasePointerSaveOffset();
670     }
671   }
672
673   int PBPOffset = 0;
674   if (FI->usesPICBase()) {
675     MachineFrameInfo *FFI = MF.getFrameInfo();
676     int PBPIndex = FI->getPICBasePointerSaveIndex();
677     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
678     PBPOffset = FFI->getObjectOffset(PBPIndex);
679   }
680
681   // Get stack alignments.
682   unsigned MaxAlign = MFI->getMaxAlignment();
683   if (HasBP && MaxAlign > 1)
684     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
685            "Invalid alignment!");
686
687   // Frames of 32KB & larger require special handling because they cannot be
688   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
689   bool isLargeFrame = !isInt<16>(NegFrameSize);
690
691   if (MustSaveLR)
692     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
693
694   assert((isPPC64 || MustSaveCRs.empty()) &&
695          "Prologue CR saving supported only in 64-bit mode");
696
697   if (!MustSaveCRs.empty()) { // will only occur for PPC64
698     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
699     // If only one or two CR fields are clobbered, it could be more
700     // efficient to use mfocrf to selectively save just those fields.
701     MachineInstrBuilder MIB =
702       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
703     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
704       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
705   }
706
707   if (HasFP)
708     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
709     BuildMI(MBB, MBBI, dl, StoreInst)
710       .addReg(FPReg)
711       .addImm(FPOffset)
712       .addReg(SPReg);
713
714   if (FI->usesPICBase())
715     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
716     BuildMI(MBB, MBBI, dl, StoreInst)
717       .addReg(PPC::R30)
718       .addImm(PBPOffset)
719       .addReg(SPReg);
720
721   if (HasBP)
722     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
723     BuildMI(MBB, MBBI, dl, StoreInst)
724       .addReg(BPReg)
725       .addImm(BPOffset)
726       .addReg(SPReg);
727
728   if (MustSaveLR)
729     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
730     BuildMI(MBB, MBBI, dl, StoreInst)
731       .addReg(ScratchReg)
732       .addImm(LROffset)
733       .addReg(SPReg);
734
735   if (!MustSaveCRs.empty()) // will only occur for PPC64
736     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
737       .addReg(TempReg, getKillRegState(true))
738       .addImm(8)
739       .addReg(SPReg);
740
741   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
742   if (!FrameSize) return;
743
744   // Adjust stack pointer: r1 += NegFrameSize.
745   // If there is a preferred stack alignment, align R1 now
746
747   if (HasBP) {
748     // Save a copy of r1 as the base pointer.
749     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
750       .addReg(SPReg)
751       .addReg(SPReg);
752   }
753
754   if (HasBP && MaxAlign > 1) {
755     if (isPPC64)
756       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
757         .addReg(SPReg)
758         .addImm(0)
759         .addImm(64 - Log2_32(MaxAlign));
760     else // PPC32...
761       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
762         .addReg(SPReg)
763         .addImm(0)
764         .addImm(32 - Log2_32(MaxAlign))
765         .addImm(31);
766     if (!isLargeFrame) {
767       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
768         .addReg(ScratchReg, RegState::Kill)
769         .addImm(NegFrameSize);
770     } else {
771       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
772         .addImm(NegFrameSize >> 16);
773       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
774         .addReg(TempReg, RegState::Kill)
775         .addImm(NegFrameSize & 0xFFFF);
776       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
777         .addReg(ScratchReg, RegState::Kill)
778         .addReg(TempReg, RegState::Kill);
779     }
780     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
781       .addReg(SPReg, RegState::Kill)
782       .addReg(SPReg)
783       .addReg(ScratchReg);
784
785   } else if (!isLargeFrame) {
786     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
787       .addReg(SPReg)
788       .addImm(NegFrameSize)
789       .addReg(SPReg);
790
791   } else {
792     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
793       .addImm(NegFrameSize >> 16);
794     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
795       .addReg(ScratchReg, RegState::Kill)
796       .addImm(NegFrameSize & 0xFFFF);
797     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
798       .addReg(SPReg, RegState::Kill)
799       .addReg(SPReg)
800       .addReg(ScratchReg);
801   }
802
803   // Add Call Frame Information for the instructions we generated above.
804   if (needsCFI) {
805     unsigned CFIIndex;
806
807     if (HasBP) {
808       // Define CFA in terms of BP. Do this in preference to using FP/SP,
809       // because if the stack needed aligning then CFA won't be at a fixed
810       // offset from FP/SP.
811       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
812       CFIIndex = MMI.addFrameInst(
813           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
814     } else {
815       // Adjust the definition of CFA to account for the change in SP.
816       assert(NegFrameSize);
817       CFIIndex = MMI.addFrameInst(
818           MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
819     }
820     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
821         .addCFIIndex(CFIIndex);
822
823     if (HasFP) {
824       // Describe where FP was saved, at a fixed offset from CFA.
825       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
826       CFIIndex = MMI.addFrameInst(
827           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
828       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
829           .addCFIIndex(CFIIndex);
830     }
831
832     if (FI->usesPICBase()) {
833       // Describe where FP was saved, at a fixed offset from CFA.
834       unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
835       CFIIndex = MMI.addFrameInst(
836           MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
837       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
838           .addCFIIndex(CFIIndex);
839     }
840
841     if (HasBP) {
842       // Describe where BP was saved, at a fixed offset from CFA.
843       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
844       CFIIndex = MMI.addFrameInst(
845           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
846       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
847           .addCFIIndex(CFIIndex);
848     }
849
850     if (MustSaveLR) {
851       // Describe where LR was saved, at a fixed offset from CFA.
852       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
853       CFIIndex = MMI.addFrameInst(
854           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
855       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
856           .addCFIIndex(CFIIndex);
857     }
858   }
859
860   // If there is a frame pointer, copy R1 into R31
861   if (HasFP) {
862     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
863       .addReg(SPReg)
864       .addReg(SPReg);
865
866     if (!HasBP && needsCFI) {
867       // Change the definition of CFA from SP+offset to FP+offset, because SP
868       // will change at every alloca.
869       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
870       unsigned CFIIndex = MMI.addFrameInst(
871           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
872
873       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
874           .addCFIIndex(CFIIndex);
875     }
876   }
877
878   if (needsCFI) {
879     // Describe where callee saved registers were saved, at fixed offsets from
880     // CFA.
881     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
882     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
883       unsigned Reg = CSI[I].getReg();
884       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
885
886       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
887       // subregisters of CR2. We just need to emit a move of CR2.
888       if (PPC::CRBITRCRegClass.contains(Reg))
889         continue;
890
891       // For SVR4, don't emit a move for the CR spill slot if we haven't
892       // spilled CRs.
893       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
894           && MustSaveCRs.empty())
895         continue;
896
897       // For 64-bit SVR4 when we have spilled CRs, the spill location
898       // is SP+8, not a frame-relative slot.
899       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
900         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
901         // the whole CR word.  In the ELFv2 ABI, every CR that was
902         // actually saved gets its own CFI record.
903         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
904         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
905             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
906         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
907             .addCFIIndex(CFIIndex);
908         continue;
909       }
910
911       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
912       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
913           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
914       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
915           .addCFIIndex(CFIIndex);
916     }
917   }
918 }
919
920 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
921                                 MachineBasicBlock &MBB) const {
922   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
923   assert(MBBI != MBB.end() && "Returning block has no terminator");
924   const PPCInstrInfo &TII =
925       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
926   const PPCRegisterInfo *RegInfo =
927       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
928
929   unsigned RetOpcode = MBBI->getOpcode();
930   DebugLoc dl;
931
932   assert((RetOpcode == PPC::BLR ||
933           RetOpcode == PPC::BLR8 ||
934           RetOpcode == PPC::TCRETURNri ||
935           RetOpcode == PPC::TCRETURNdi ||
936           RetOpcode == PPC::TCRETURNai ||
937           RetOpcode == PPC::TCRETURNri8 ||
938           RetOpcode == PPC::TCRETURNdi8 ||
939           RetOpcode == PPC::TCRETURNai8) &&
940          "Can only insert epilog into returning blocks");
941
942   // Get alignment info so we know how to restore the SP.
943   const MachineFrameInfo *MFI = MF.getFrameInfo();
944
945   // Get the number of bytes allocated from the FrameInfo.
946   int FrameSize = MFI->getStackSize();
947
948   // Get processor type.
949   bool isPPC64 = Subtarget.isPPC64();
950   // Get the ABI.
951   bool isSVR4ABI = Subtarget.isSVR4ABI();
952
953   // Check if the link register (LR) has been saved.
954   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
955   bool MustSaveLR = FI->mustSaveLR();
956   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
957   // Do we have a frame pointer and/or base pointer for this function?
958   bool HasFP = hasFP(MF);
959   bool HasBP = RegInfo->hasBasePointer(MF);
960
961   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
962   unsigned BPReg      = RegInfo->getBaseRegister(MF);
963   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
964   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
965   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
966   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
967                                                  : PPC::MTLR );
968   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
969                                                  : PPC::LWZ );
970   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
971                                                            : PPC::LIS );
972   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
973                                                   : PPC::ORI );
974   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
975                                                    : PPC::ADDI );
976   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
977                                                 : PPC::ADD4 );
978
979   int LROffset = getReturnSaveOffset();
980
981   int FPOffset = 0;
982   if (HasFP) {
983     if (isSVR4ABI) {
984       MachineFrameInfo *FFI = MF.getFrameInfo();
985       int FPIndex = FI->getFramePointerSaveIndex();
986       assert(FPIndex && "No Frame Pointer Save Slot!");
987       FPOffset = FFI->getObjectOffset(FPIndex);
988     } else {
989       FPOffset = getFramePointerSaveOffset();
990     }
991   }
992
993   int BPOffset = 0;
994   if (HasBP) {
995     if (isSVR4ABI) {
996       MachineFrameInfo *FFI = MF.getFrameInfo();
997       int BPIndex = FI->getBasePointerSaveIndex();
998       assert(BPIndex && "No Base Pointer Save Slot!");
999       BPOffset = FFI->getObjectOffset(BPIndex);
1000     } else {
1001       BPOffset = getBasePointerSaveOffset();
1002     }
1003   }
1004
1005   int PBPOffset = 0;
1006   if (FI->usesPICBase()) {
1007     MachineFrameInfo *FFI = MF.getFrameInfo();
1008     int PBPIndex = FI->getPICBasePointerSaveIndex();
1009     assert(PBPIndex && "No PIC Base Pointer Save Slot!");
1010     PBPOffset = FFI->getObjectOffset(PBPIndex);
1011   }
1012
1013   bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
1014     RetOpcode == PPC::TCRETURNdi ||
1015     RetOpcode == PPC::TCRETURNai ||
1016     RetOpcode == PPC::TCRETURNri8 ||
1017     RetOpcode == PPC::TCRETURNdi8 ||
1018     RetOpcode == PPC::TCRETURNai8;
1019
1020   if (UsesTCRet) {
1021     int MaxTCRetDelta = FI->getTailCallSPDelta();
1022     MachineOperand &StackAdjust = MBBI->getOperand(1);
1023     assert(StackAdjust.isImm() && "Expecting immediate value.");
1024     // Adjust stack pointer.
1025     int StackAdj = StackAdjust.getImm();
1026     int Delta = StackAdj - MaxTCRetDelta;
1027     assert((Delta >= 0) && "Delta must be positive");
1028     if (MaxTCRetDelta>0)
1029       FrameSize += (StackAdj +Delta);
1030     else
1031       FrameSize += StackAdj;
1032   }
1033
1034   // Frames of 32KB & larger require special handling because they cannot be
1035   // indexed into with a simple LD/LWZ immediate offset operand.
1036   bool isLargeFrame = !isInt<16>(FrameSize);
1037
1038   if (FrameSize) {
1039     // In the prologue, the loaded (or persistent) stack pointer value is offset
1040     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
1041
1042     // If this function contained a fastcc call and GuaranteedTailCallOpt is
1043     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1044     // call which invalidates the stack pointer value in SP(0). So we use the
1045     // value of R31 in this case.
1046     if (FI->hasFastCall()) {
1047       assert(HasFP && "Expecting a valid frame pointer.");
1048       if (!isLargeFrame) {
1049         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1050           .addReg(FPReg).addImm(FrameSize);
1051       } else {
1052         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1053           .addImm(FrameSize >> 16);
1054         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1055           .addReg(ScratchReg, RegState::Kill)
1056           .addImm(FrameSize & 0xFFFF);
1057         BuildMI(MBB, MBBI, dl, AddInst)
1058           .addReg(SPReg)
1059           .addReg(FPReg)
1060           .addReg(ScratchReg);
1061       }
1062     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1063       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1064         .addReg(SPReg)
1065         .addImm(FrameSize);
1066     } else {
1067       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1068         .addImm(0)
1069         .addReg(SPReg);
1070     }
1071
1072   }
1073
1074   if (MustSaveLR)
1075     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1076       .addImm(LROffset)
1077       .addReg(SPReg);
1078
1079   assert((isPPC64 || MustSaveCRs.empty()) &&
1080          "Epilogue CR restoring supported only in 64-bit mode");
1081
1082   if (!MustSaveCRs.empty()) // will only occur for PPC64
1083     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1084       .addImm(8)
1085       .addReg(SPReg);
1086
1087   if (HasFP)
1088     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1089       .addImm(FPOffset)
1090       .addReg(SPReg);
1091
1092   if (FI->usesPICBase())
1093     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1094     BuildMI(MBB, MBBI, dl, LoadInst)
1095       .addReg(PPC::R30)
1096       .addImm(PBPOffset)
1097       .addReg(SPReg);
1098
1099   if (HasBP)
1100     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1101       .addImm(BPOffset)
1102       .addReg(SPReg);
1103
1104   if (!MustSaveCRs.empty()) // will only occur for PPC64
1105     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1106       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1107         .addReg(TempReg, getKillRegState(i == e-1));
1108
1109   if (MustSaveLR)
1110     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1111
1112   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1113   // call optimization
1114   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1115       (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1116       MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1117      PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1118      unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1119
1120      if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1121        BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1122          .addReg(SPReg).addImm(CallerAllocatedAmt);
1123      } else {
1124        BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1125           .addImm(CallerAllocatedAmt >> 16);
1126        BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1127           .addReg(ScratchReg, RegState::Kill)
1128           .addImm(CallerAllocatedAmt & 0xFFFF);
1129        BuildMI(MBB, MBBI, dl, AddInst)
1130           .addReg(SPReg)
1131           .addReg(FPReg)
1132           .addReg(ScratchReg);
1133      }
1134   } else if (RetOpcode == PPC::TCRETURNdi) {
1135     MBBI = MBB.getLastNonDebugInstr();
1136     MachineOperand &JumpTarget = MBBI->getOperand(0);
1137     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1138       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1139   } else if (RetOpcode == PPC::TCRETURNri) {
1140     MBBI = MBB.getLastNonDebugInstr();
1141     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1142     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1143   } else if (RetOpcode == PPC::TCRETURNai) {
1144     MBBI = MBB.getLastNonDebugInstr();
1145     MachineOperand &JumpTarget = MBBI->getOperand(0);
1146     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1147   } else if (RetOpcode == PPC::TCRETURNdi8) {
1148     MBBI = MBB.getLastNonDebugInstr();
1149     MachineOperand &JumpTarget = MBBI->getOperand(0);
1150     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1151       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1152   } else if (RetOpcode == PPC::TCRETURNri8) {
1153     MBBI = MBB.getLastNonDebugInstr();
1154     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1155     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1156   } else if (RetOpcode == PPC::TCRETURNai8) {
1157     MBBI = MBB.getLastNonDebugInstr();
1158     MachineOperand &JumpTarget = MBBI->getOperand(0);
1159     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1160   }
1161 }
1162
1163 void
1164 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1165                                                    RegScavenger *) const {
1166   const PPCRegisterInfo *RegInfo =
1167       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1168
1169   //  Save and clear the LR state.
1170   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1171   unsigned LR = RegInfo->getRARegister();
1172   FI->setMustSaveLR(MustSaveLR(MF, LR));
1173   MachineRegisterInfo &MRI = MF.getRegInfo();
1174   MRI.setPhysRegUnused(LR);
1175
1176   //  Save R31 if necessary
1177   int FPSI = FI->getFramePointerSaveIndex();
1178   bool isPPC64 = Subtarget.isPPC64();
1179   bool isDarwinABI  = Subtarget.isDarwinABI();
1180   MachineFrameInfo *MFI = MF.getFrameInfo();
1181
1182   // If the frame pointer save index hasn't been defined yet.
1183   if (!FPSI && needsFP(MF)) {
1184     // Find out what the fix offset of the frame pointer save area.
1185     int FPOffset = getFramePointerSaveOffset();
1186     // Allocate the frame index for frame pointer save area.
1187     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1188     // Save the result.
1189     FI->setFramePointerSaveIndex(FPSI);
1190   }
1191
1192   int BPSI = FI->getBasePointerSaveIndex();
1193   if (!BPSI && RegInfo->hasBasePointer(MF)) {
1194     int BPOffset = getBasePointerSaveOffset();
1195     // Allocate the frame index for the base pointer save area.
1196     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1197     // Save the result.
1198     FI->setBasePointerSaveIndex(BPSI);
1199   }
1200
1201   // Reserve stack space for the PIC Base register (R30).
1202   // Only used in SVR4 32-bit.
1203   if (FI->usesPICBase()) {
1204     int PBPSI = FI->getPICBasePointerSaveIndex();
1205     PBPSI = MFI->CreateFixedObject(4, -8, true);
1206     FI->setPICBasePointerSaveIndex(PBPSI);
1207   }
1208
1209   // Reserve stack space to move the linkage area to in case of a tail call.
1210   int TCSPDelta = 0;
1211   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1212       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1213     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1214   }
1215
1216   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1217   // function uses CR 2, 3, or 4.
1218   if (!isPPC64 && !isDarwinABI &&
1219       (MRI.isPhysRegUsed(PPC::CR2) ||
1220        MRI.isPhysRegUsed(PPC::CR3) ||
1221        MRI.isPhysRegUsed(PPC::CR4))) {
1222     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1223     FI->setCRSpillFrameIndex(FrameIdx);
1224   }
1225 }
1226
1227 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1228                                                        RegScavenger *RS) const {
1229   // Early exit if not using the SVR4 ABI.
1230   if (!Subtarget.isSVR4ABI()) {
1231     addScavengingSpillSlot(MF, RS);
1232     return;
1233   }
1234
1235   // Get callee saved register information.
1236   MachineFrameInfo *FFI = MF.getFrameInfo();
1237   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1238
1239   // Early exit if no callee saved registers are modified!
1240   if (CSI.empty() && !needsFP(MF)) {
1241     addScavengingSpillSlot(MF, RS);
1242     return;
1243   }
1244
1245   unsigned MinGPR = PPC::R31;
1246   unsigned MinG8R = PPC::X31;
1247   unsigned MinFPR = PPC::F31;
1248   unsigned MinVR = PPC::V31;
1249
1250   bool HasGPSaveArea = false;
1251   bool HasG8SaveArea = false;
1252   bool HasFPSaveArea = false;
1253   bool HasVRSAVESaveArea = false;
1254   bool HasVRSaveArea = false;
1255
1256   SmallVector<CalleeSavedInfo, 18> GPRegs;
1257   SmallVector<CalleeSavedInfo, 18> G8Regs;
1258   SmallVector<CalleeSavedInfo, 18> FPRegs;
1259   SmallVector<CalleeSavedInfo, 18> VRegs;
1260
1261   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1262     unsigned Reg = CSI[i].getReg();
1263     if (PPC::GPRCRegClass.contains(Reg)) {
1264       HasGPSaveArea = true;
1265
1266       GPRegs.push_back(CSI[i]);
1267
1268       if (Reg < MinGPR) {
1269         MinGPR = Reg;
1270       }
1271     } else if (PPC::G8RCRegClass.contains(Reg)) {
1272       HasG8SaveArea = true;
1273
1274       G8Regs.push_back(CSI[i]);
1275
1276       if (Reg < MinG8R) {
1277         MinG8R = Reg;
1278       }
1279     } else if (PPC::F8RCRegClass.contains(Reg)) {
1280       HasFPSaveArea = true;
1281
1282       FPRegs.push_back(CSI[i]);
1283
1284       if (Reg < MinFPR) {
1285         MinFPR = Reg;
1286       }
1287     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1288                PPC::CRRCRegClass.contains(Reg)) {
1289       ; // do nothing, as we already know whether CRs are spilled
1290     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1291       HasVRSAVESaveArea = true;
1292     } else if (PPC::VRRCRegClass.contains(Reg)) {
1293       HasVRSaveArea = true;
1294
1295       VRegs.push_back(CSI[i]);
1296
1297       if (Reg < MinVR) {
1298         MinVR = Reg;
1299       }
1300     } else {
1301       llvm_unreachable("Unknown RegisterClass!");
1302     }
1303   }
1304
1305   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1306   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1307
1308   int64_t LowerBound = 0;
1309
1310   // Take into account stack space reserved for tail calls.
1311   int TCSPDelta = 0;
1312   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1313       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1314     LowerBound = TCSPDelta;
1315   }
1316
1317   // The Floating-point register save area is right below the back chain word
1318   // of the previous stack frame.
1319   if (HasFPSaveArea) {
1320     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1321       int FI = FPRegs[i].getFrameIdx();
1322
1323       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1324     }
1325
1326     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1327   }
1328
1329   // Check whether the frame pointer register is allocated. If so, make sure it
1330   // is spilled to the correct offset.
1331   if (needsFP(MF)) {
1332     HasGPSaveArea = true;
1333
1334     int FI = PFI->getFramePointerSaveIndex();
1335     assert(FI && "No Frame Pointer Save Slot!");
1336
1337     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1338   }
1339
1340   if (PFI->usesPICBase()) {
1341     HasGPSaveArea = true;
1342
1343     int FI = PFI->getPICBasePointerSaveIndex();
1344     assert(FI && "No PIC Base Pointer Save Slot!");
1345
1346     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1347   }
1348
1349   const PPCRegisterInfo *RegInfo =
1350       static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1351   if (RegInfo->hasBasePointer(MF)) {
1352     HasGPSaveArea = true;
1353
1354     int FI = PFI->getBasePointerSaveIndex();
1355     assert(FI && "No Base Pointer Save Slot!");
1356
1357     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1358   }
1359
1360   // General register save area starts right below the Floating-point
1361   // register save area.
1362   if (HasGPSaveArea || HasG8SaveArea) {
1363     // Move general register save area spill slots down, taking into account
1364     // the size of the Floating-point register save area.
1365     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1366       int FI = GPRegs[i].getFrameIdx();
1367
1368       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1369     }
1370
1371     // Move general register save area spill slots down, taking into account
1372     // the size of the Floating-point register save area.
1373     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1374       int FI = G8Regs[i].getFrameIdx();
1375
1376       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1377     }
1378
1379     unsigned MinReg =
1380       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1381                          TRI->getEncodingValue(MinG8R));
1382
1383     if (Subtarget.isPPC64()) {
1384       LowerBound -= (31 - MinReg + 1) * 8;
1385     } else {
1386       LowerBound -= (31 - MinReg + 1) * 4;
1387     }
1388   }
1389
1390   // For 32-bit only, the CR save area is below the general register
1391   // save area.  For 64-bit SVR4, the CR save area is addressed relative
1392   // to the stack pointer and hence does not need an adjustment here.
1393   // Only CR2 (the first nonvolatile spilled) has an associated frame
1394   // index so that we have a single uniform save area.
1395   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1396     // Adjust the frame index of the CR spill slot.
1397     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1398       unsigned Reg = CSI[i].getReg();
1399
1400       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1401           // Leave Darwin logic as-is.
1402           || (!Subtarget.isSVR4ABI() &&
1403               (PPC::CRBITRCRegClass.contains(Reg) ||
1404                PPC::CRRCRegClass.contains(Reg)))) {
1405         int FI = CSI[i].getFrameIdx();
1406
1407         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1408       }
1409     }
1410
1411     LowerBound -= 4; // The CR save area is always 4 bytes long.
1412   }
1413
1414   if (HasVRSAVESaveArea) {
1415     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1416     //             which have the VRSAVE register class?
1417     // Adjust the frame index of the VRSAVE spill slot.
1418     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1419       unsigned Reg = CSI[i].getReg();
1420
1421       if (PPC::VRSAVERCRegClass.contains(Reg)) {
1422         int FI = CSI[i].getFrameIdx();
1423
1424         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1425       }
1426     }
1427
1428     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1429   }
1430
1431   if (HasVRSaveArea) {
1432     // Insert alignment padding, we need 16-byte alignment.
1433     LowerBound = (LowerBound - 15) & ~(15);
1434
1435     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1436       int FI = VRegs[i].getFrameIdx();
1437
1438       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1439     }
1440   }
1441
1442   addScavengingSpillSlot(MF, RS);
1443 }
1444
1445 void
1446 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1447                                          RegScavenger *RS) const {
1448   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1449   // a large stack, which will require scavenging a register to materialize a
1450   // large offset.
1451
1452   // We need to have a scavenger spill slot for spills if the frame size is
1453   // large. In case there is no free register for large-offset addressing,
1454   // this slot is used for the necessary emergency spill. Also, we need the
1455   // slot for dynamic stack allocations.
1456
1457   // The scavenger might be invoked if the frame offset does not fit into
1458   // the 16-bit immediate. We don't know the complete frame size here
1459   // because we've not yet computed callee-saved register spills or the
1460   // needed alignment padding.
1461   unsigned StackSize = determineFrameLayout(MF, false, true);
1462   MachineFrameInfo *MFI = MF.getFrameInfo();
1463   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1464       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1465     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1466     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1467     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1468     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1469                                                        RC->getAlignment(),
1470                                                        false));
1471
1472     // Might we have over-aligned allocas?
1473     bool HasAlVars = MFI->hasVarSizedObjects() &&
1474                      MFI->getMaxAlignment() > getStackAlignment();
1475
1476     // These kinds of spills might need two registers.
1477     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1478       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1479                                                          RC->getAlignment(),
1480                                                          false));
1481
1482   }
1483 }
1484
1485 bool
1486 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1487                                      MachineBasicBlock::iterator MI,
1488                                      const std::vector<CalleeSavedInfo> &CSI,
1489                                      const TargetRegisterInfo *TRI) const {
1490
1491   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1492   // Return false otherwise to maintain pre-existing behavior.
1493   if (!Subtarget.isSVR4ABI())
1494     return false;
1495
1496   MachineFunction *MF = MBB.getParent();
1497   const PPCInstrInfo &TII =
1498       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1499   DebugLoc DL;
1500   bool CRSpilled = false;
1501   MachineInstrBuilder CRMIB;
1502
1503   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1504     unsigned Reg = CSI[i].getReg();
1505     // Only Darwin actually uses the VRSAVE register, but it can still appear
1506     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1507     // Darwin, ignore it.
1508     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1509       continue;
1510
1511     // CR2 through CR4 are the nonvolatile CR fields.
1512     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1513
1514     // Add the callee-saved register as live-in; it's killed at the spill.
1515     MBB.addLiveIn(Reg);
1516
1517     if (CRSpilled && IsCRField) {
1518       CRMIB.addReg(Reg, RegState::ImplicitKill);
1519       continue;
1520     }
1521
1522     // Insert the spill to the stack frame.
1523     if (IsCRField) {
1524       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1525       if (Subtarget.isPPC64()) {
1526         // The actual spill will happen at the start of the prologue.
1527         FuncInfo->addMustSaveCR(Reg);
1528       } else {
1529         CRSpilled = true;
1530         FuncInfo->setSpillsCR();
1531
1532         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
1533         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1534         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1535                   .addReg(Reg, RegState::ImplicitKill);
1536
1537         MBB.insert(MI, CRMIB);
1538         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1539                                          .addReg(PPC::R12,
1540                                                  getKillRegState(true)),
1541                                          CSI[i].getFrameIdx()));
1542       }
1543     } else {
1544       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1545       TII.storeRegToStackSlot(MBB, MI, Reg, true,
1546                               CSI[i].getFrameIdx(), RC, TRI);
1547     }
1548   }
1549   return true;
1550 }
1551
1552 static void
1553 restoreCRs(bool isPPC64, bool is31,
1554            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1555            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1556            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1557
1558   MachineFunction *MF = MBB.getParent();
1559   const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1560   DebugLoc DL;
1561   unsigned RestoreOp, MoveReg;
1562
1563   if (isPPC64)
1564     // This is handled during epilogue generation.
1565     return;
1566   else {
1567     // 32-bit:  FP-relative
1568     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1569                                              PPC::R12),
1570                                      CSI[CSIIndex].getFrameIdx()));
1571     RestoreOp = PPC::MTOCRF;
1572     MoveReg = PPC::R12;
1573   }
1574
1575   if (CR2Spilled)
1576     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1577                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1578
1579   if (CR3Spilled)
1580     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1581                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1582
1583   if (CR4Spilled)
1584     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1585                .addReg(MoveReg, getKillRegState(true)));
1586 }
1587
1588 void PPCFrameLowering::
1589 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1590                               MachineBasicBlock::iterator I) const {
1591   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1592   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1593       I->getOpcode() == PPC::ADJCALLSTACKUP) {
1594     // Add (actually subtract) back the amount the callee popped on return.
1595     if (int CalleeAmt =  I->getOperand(1).getImm()) {
1596       bool is64Bit = Subtarget.isPPC64();
1597       CalleeAmt *= -1;
1598       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1599       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1600       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1601       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1602       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1603       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1604       MachineInstr *MI = I;
1605       DebugLoc dl = MI->getDebugLoc();
1606
1607       if (isInt<16>(CalleeAmt)) {
1608         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1609           .addReg(StackReg, RegState::Kill)
1610           .addImm(CalleeAmt);
1611       } else {
1612         MachineBasicBlock::iterator MBBI = I;
1613         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1614           .addImm(CalleeAmt >> 16);
1615         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1616           .addReg(TmpReg, RegState::Kill)
1617           .addImm(CalleeAmt & 0xFFFF);
1618         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1619           .addReg(StackReg, RegState::Kill)
1620           .addReg(TmpReg);
1621       }
1622     }
1623   }
1624   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1625   MBB.erase(I);
1626 }
1627
1628 bool
1629 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1630                                         MachineBasicBlock::iterator MI,
1631                                         const std::vector<CalleeSavedInfo> &CSI,
1632                                         const TargetRegisterInfo *TRI) const {
1633
1634   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1635   // Return false otherwise to maintain pre-existing behavior.
1636   if (!Subtarget.isSVR4ABI())
1637     return false;
1638
1639   MachineFunction *MF = MBB.getParent();
1640   const PPCInstrInfo &TII =
1641       *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1642   bool CR2Spilled = false;
1643   bool CR3Spilled = false;
1644   bool CR4Spilled = false;
1645   unsigned CSIIndex = 0;
1646
1647   // Initialize insertion-point logic; we will be restoring in reverse
1648   // order of spill.
1649   MachineBasicBlock::iterator I = MI, BeforeI = I;
1650   bool AtStart = I == MBB.begin();
1651
1652   if (!AtStart)
1653     --BeforeI;
1654
1655   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1656     unsigned Reg = CSI[i].getReg();
1657
1658     // Only Darwin actually uses the VRSAVE register, but it can still appear
1659     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1660     // Darwin, ignore it.
1661     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1662       continue;
1663
1664     if (Reg == PPC::CR2) {
1665       CR2Spilled = true;
1666       // The spill slot is associated only with CR2, which is the
1667       // first nonvolatile spilled.  Save it here.
1668       CSIIndex = i;
1669       continue;
1670     } else if (Reg == PPC::CR3) {
1671       CR3Spilled = true;
1672       continue;
1673     } else if (Reg == PPC::CR4) {
1674       CR4Spilled = true;
1675       continue;
1676     } else {
1677       // When we first encounter a non-CR register after seeing at
1678       // least one CR register, restore all spilled CRs together.
1679       if ((CR2Spilled || CR3Spilled || CR4Spilled)
1680           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1681         bool is31 = needsFP(*MF);
1682         restoreCRs(Subtarget.isPPC64(), is31,
1683                    CR2Spilled, CR3Spilled, CR4Spilled,
1684                    MBB, I, CSI, CSIIndex);
1685         CR2Spilled = CR3Spilled = CR4Spilled = false;
1686       }
1687
1688       // Default behavior for non-CR saves.
1689       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1690       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1691                                RC, TRI);
1692       assert(I != MBB.begin() &&
1693              "loadRegFromStackSlot didn't insert any code!");
1694       }
1695
1696     // Insert in reverse order.
1697     if (AtStart)
1698       I = MBB.begin();
1699     else {
1700       I = BeforeI;
1701       ++I;
1702     }
1703   }
1704
1705   // If we haven't yet spilled the CRs, do so now.
1706   if (CR2Spilled || CR3Spilled || CR4Spilled) {
1707     bool is31 = needsFP(*MF);
1708     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1709                MBB, I, CSI, CSIIndex);
1710   }
1711
1712   return true;
1713 }