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