[PowerPC] Don't remove self VSX copies in PPCInstrInfo::copyPhysReg
[oota-llvm.git] / lib / Target / PowerPC / PPCInstrInfo.cpp
1 //===-- PPCInstrInfo.cpp - PowerPC Instruction 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 PowerPC implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/SlotIndexes.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
37
38 #define GET_INSTRMAP_INFO
39 #define GET_INSTRINFO_CTOR_DTOR
40 #include "PPCGenInstrInfo.inc"
41
42 using namespace llvm;
43
44 static cl::
45 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
46             cl::desc("Disable analysis for CTR loops"));
47
48 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
49 cl::desc("Disable compare instruction optimization"), cl::Hidden);
50
51 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
52 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
53
54 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
55 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
56 cl::Hidden);
57
58 // Pin the vtable to this file.
59 void PPCInstrInfo::anchor() {}
60
61 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
62   : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
63     TM(tm), RI(*TM.getSubtargetImpl()) {}
64
65 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
66 /// this target when scheduling the DAG.
67 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
68   const TargetMachine *TM,
69   const ScheduleDAG *DAG) const {
70   unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
71   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
72       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
73     const InstrItineraryData *II = TM->getInstrItineraryData();
74     return new ScoreboardHazardRecognizer(II, DAG);
75   }
76
77   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
78 }
79
80 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
81 /// to use for this target when scheduling the DAG.
82 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
83   const InstrItineraryData *II,
84   const ScheduleDAG *DAG) const {
85   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
86
87   if (Directive == PPC::DIR_PWR7)
88     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
89
90   // Most subtargets use a PPC970 recognizer.
91   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
92       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
93     assert(TM.getInstrInfo() && "No InstrInfo?");
94
95     return new PPCHazardRecognizer970(TM);
96   }
97
98   return new ScoreboardHazardRecognizer(II, DAG);
99 }
100
101
102 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
103                                     const MachineInstr *DefMI, unsigned DefIdx,
104                                     const MachineInstr *UseMI,
105                                     unsigned UseIdx) const {
106   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
107                                                    UseMI, UseIdx);
108
109   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
110   unsigned Reg = DefMO.getReg();
111
112   const TargetRegisterInfo *TRI = &getRegisterInfo();
113   bool IsRegCR;
114   if (TRI->isVirtualRegister(Reg)) {
115     const MachineRegisterInfo *MRI =
116       &DefMI->getParent()->getParent()->getRegInfo();
117     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
118               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
119   } else {
120     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
121               PPC::CRBITRCRegClass.contains(Reg);
122   }
123
124   if (UseMI->isBranch() && IsRegCR) {
125     if (Latency < 0)
126       Latency = getInstrLatency(ItinData, DefMI);
127
128     // On some cores, there is an additional delay between writing to a condition
129     // register, and using it from a branch.
130     unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
131     switch (Directive) {
132     default: break;
133     case PPC::DIR_7400:
134     case PPC::DIR_750:
135     case PPC::DIR_970:
136     case PPC::DIR_E5500:
137     case PPC::DIR_PWR4:
138     case PPC::DIR_PWR5:
139     case PPC::DIR_PWR5X:
140     case PPC::DIR_PWR6:
141     case PPC::DIR_PWR6X:
142     case PPC::DIR_PWR7:
143       Latency += 2;
144       break;
145     }
146   }
147
148   return Latency;
149 }
150
151 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
152 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
153                                          unsigned &SrcReg, unsigned &DstReg,
154                                          unsigned &SubIdx) const {
155   switch (MI.getOpcode()) {
156   default: return false;
157   case PPC::EXTSW:
158   case PPC::EXTSW_32_64:
159     SrcReg = MI.getOperand(1).getReg();
160     DstReg = MI.getOperand(0).getReg();
161     SubIdx = PPC::sub_32;
162     return true;
163   }
164 }
165
166 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
167                                            int &FrameIndex) const {
168   // Note: This list must be kept consistent with LoadRegFromStackSlot.
169   switch (MI->getOpcode()) {
170   default: break;
171   case PPC::LD:
172   case PPC::LWZ:
173   case PPC::LFS:
174   case PPC::LFD:
175   case PPC::RESTORE_CR:
176   case PPC::RESTORE_CRBIT:
177   case PPC::LVX:
178   case PPC::LXVD2X:
179   case PPC::RESTORE_VRSAVE:
180     // Check for the operands added by addFrameReference (the immediate is the
181     // offset which defaults to 0).
182     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
183         MI->getOperand(2).isFI()) {
184       FrameIndex = MI->getOperand(2).getIndex();
185       return MI->getOperand(0).getReg();
186     }
187     break;
188   }
189   return 0;
190 }
191
192 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
193                                           int &FrameIndex) const {
194   // Note: This list must be kept consistent with StoreRegToStackSlot.
195   switch (MI->getOpcode()) {
196   default: break;
197   case PPC::STD:
198   case PPC::STW:
199   case PPC::STFS:
200   case PPC::STFD:
201   case PPC::SPILL_CR:
202   case PPC::SPILL_CRBIT:
203   case PPC::STVX:
204   case PPC::STXVD2X:
205   case PPC::SPILL_VRSAVE:
206     // Check for the operands added by addFrameReference (the immediate is the
207     // offset which defaults to 0).
208     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
209         MI->getOperand(2).isFI()) {
210       FrameIndex = MI->getOperand(2).getIndex();
211       return MI->getOperand(0).getReg();
212     }
213     break;
214   }
215   return 0;
216 }
217
218 // commuteInstruction - We can commute rlwimi instructions, but only if the
219 // rotate amt is zero.  We also have to munge the immediates a bit.
220 MachineInstr *
221 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
222   MachineFunction &MF = *MI->getParent()->getParent();
223
224   // Normal instructions can be commuted the obvious way.
225   if (MI->getOpcode() != PPC::RLWIMI &&
226       MI->getOpcode() != PPC::RLWIMIo &&
227       MI->getOpcode() != PPC::RLWIMI8 &&
228       MI->getOpcode() != PPC::RLWIMI8o)
229     return TargetInstrInfo::commuteInstruction(MI, NewMI);
230
231   // Cannot commute if it has a non-zero rotate count.
232   if (MI->getOperand(3).getImm() != 0)
233     return 0;
234
235   // If we have a zero rotate count, we have:
236   //   M = mask(MB,ME)
237   //   Op0 = (Op1 & ~M) | (Op2 & M)
238   // Change this to:
239   //   M = mask((ME+1)&31, (MB-1)&31)
240   //   Op0 = (Op2 & ~M) | (Op1 & M)
241
242   // Swap op1/op2
243   unsigned Reg0 = MI->getOperand(0).getReg();
244   unsigned Reg1 = MI->getOperand(1).getReg();
245   unsigned Reg2 = MI->getOperand(2).getReg();
246   unsigned SubReg1 = MI->getOperand(1).getSubReg();
247   unsigned SubReg2 = MI->getOperand(2).getSubReg();
248   bool Reg1IsKill = MI->getOperand(1).isKill();
249   bool Reg2IsKill = MI->getOperand(2).isKill();
250   bool ChangeReg0 = false;
251   // If machine instrs are no longer in two-address forms, update
252   // destination register as well.
253   if (Reg0 == Reg1) {
254     // Must be two address instruction!
255     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
256            "Expecting a two-address instruction!");
257     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
258     Reg2IsKill = false;
259     ChangeReg0 = true;
260   }
261
262   // Masks.
263   unsigned MB = MI->getOperand(4).getImm();
264   unsigned ME = MI->getOperand(5).getImm();
265
266   if (NewMI) {
267     // Create a new instruction.
268     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
269     bool Reg0IsDead = MI->getOperand(0).isDead();
270     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
271       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
272       .addReg(Reg2, getKillRegState(Reg2IsKill))
273       .addReg(Reg1, getKillRegState(Reg1IsKill))
274       .addImm((ME+1) & 31)
275       .addImm((MB-1) & 31);
276   }
277
278   if (ChangeReg0) {
279     MI->getOperand(0).setReg(Reg2);
280     MI->getOperand(0).setSubReg(SubReg2);
281   }
282   MI->getOperand(2).setReg(Reg1);
283   MI->getOperand(1).setReg(Reg2);
284   MI->getOperand(2).setSubReg(SubReg1);
285   MI->getOperand(1).setSubReg(SubReg2);
286   MI->getOperand(2).setIsKill(Reg1IsKill);
287   MI->getOperand(1).setIsKill(Reg2IsKill);
288
289   // Swap the mask around.
290   MI->getOperand(4).setImm((ME+1) & 31);
291   MI->getOperand(5).setImm((MB-1) & 31);
292   return MI;
293 }
294
295 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
296                                          unsigned &SrcOpIdx2) const {
297   // For VSX A-Type FMA instructions, it is the first two operands that can be
298   // commuted, however, because the non-encoded tied input operand is listed
299   // first, the operands to swap are actually the second and third.
300
301   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
302   if (AltOpc == -1)
303     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
304
305   SrcOpIdx1 = 2;
306   SrcOpIdx2 = 3;
307   return true;
308 }
309
310 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
311                               MachineBasicBlock::iterator MI) const {
312   // This function is used for scheduling, and the nop wanted here is the type
313   // that terminates dispatch groups on the POWER cores.
314   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
315   unsigned Opcode;
316   switch (Directive) {
317   default:            Opcode = PPC::NOP; break;
318   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
319   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
320   }
321
322   DebugLoc DL;
323   BuildMI(MBB, MI, DL, get(Opcode));
324 }
325
326 // Branch analysis.
327 // Note: If the condition register is set to CTR or CTR8 then this is a
328 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
329 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
330                                  MachineBasicBlock *&FBB,
331                                  SmallVectorImpl<MachineOperand> &Cond,
332                                  bool AllowModify) const {
333   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
334
335   // If the block has no terminators, it just falls into the block after it.
336   MachineBasicBlock::iterator I = MBB.end();
337   if (I == MBB.begin())
338     return false;
339   --I;
340   while (I->isDebugValue()) {
341     if (I == MBB.begin())
342       return false;
343     --I;
344   }
345   if (!isUnpredicatedTerminator(I))
346     return false;
347
348   // Get the last instruction in the block.
349   MachineInstr *LastInst = I;
350
351   // If there is only one terminator instruction, process it.
352   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
353     if (LastInst->getOpcode() == PPC::B) {
354       if (!LastInst->getOperand(0).isMBB())
355         return true;
356       TBB = LastInst->getOperand(0).getMBB();
357       return false;
358     } else if (LastInst->getOpcode() == PPC::BCC) {
359       if (!LastInst->getOperand(2).isMBB())
360         return true;
361       // Block ends with fall-through condbranch.
362       TBB = LastInst->getOperand(2).getMBB();
363       Cond.push_back(LastInst->getOperand(0));
364       Cond.push_back(LastInst->getOperand(1));
365       return false;
366     } else if (LastInst->getOpcode() == PPC::BC) {
367       if (!LastInst->getOperand(1).isMBB())
368         return true;
369       // Block ends with fall-through condbranch.
370       TBB = LastInst->getOperand(1).getMBB();
371       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
372       Cond.push_back(LastInst->getOperand(0));
373       return false;
374     } else if (LastInst->getOpcode() == PPC::BCn) {
375       if (!LastInst->getOperand(1).isMBB())
376         return true;
377       // Block ends with fall-through condbranch.
378       TBB = LastInst->getOperand(1).getMBB();
379       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
380       Cond.push_back(LastInst->getOperand(0));
381       return false;
382     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
383                LastInst->getOpcode() == PPC::BDNZ) {
384       if (!LastInst->getOperand(0).isMBB())
385         return true;
386       if (DisableCTRLoopAnal)
387         return true;
388       TBB = LastInst->getOperand(0).getMBB();
389       Cond.push_back(MachineOperand::CreateImm(1));
390       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
391                                                true));
392       return false;
393     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
394                LastInst->getOpcode() == PPC::BDZ) {
395       if (!LastInst->getOperand(0).isMBB())
396         return true;
397       if (DisableCTRLoopAnal)
398         return true;
399       TBB = LastInst->getOperand(0).getMBB();
400       Cond.push_back(MachineOperand::CreateImm(0));
401       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
402                                                true));
403       return false;
404     }
405
406     // Otherwise, don't know what this is.
407     return true;
408   }
409
410   // Get the instruction before it if it's a terminator.
411   MachineInstr *SecondLastInst = I;
412
413   // If there are three terminators, we don't know what sort of block this is.
414   if (SecondLastInst && I != MBB.begin() &&
415       isUnpredicatedTerminator(--I))
416     return true;
417
418   // If the block ends with PPC::B and PPC:BCC, handle it.
419   if (SecondLastInst->getOpcode() == PPC::BCC &&
420       LastInst->getOpcode() == PPC::B) {
421     if (!SecondLastInst->getOperand(2).isMBB() ||
422         !LastInst->getOperand(0).isMBB())
423       return true;
424     TBB =  SecondLastInst->getOperand(2).getMBB();
425     Cond.push_back(SecondLastInst->getOperand(0));
426     Cond.push_back(SecondLastInst->getOperand(1));
427     FBB = LastInst->getOperand(0).getMBB();
428     return false;
429   } else if (SecondLastInst->getOpcode() == PPC::BC &&
430       LastInst->getOpcode() == PPC::B) {
431     if (!SecondLastInst->getOperand(1).isMBB() ||
432         !LastInst->getOperand(0).isMBB())
433       return true;
434     TBB =  SecondLastInst->getOperand(1).getMBB();
435     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
436     Cond.push_back(SecondLastInst->getOperand(0));
437     FBB = LastInst->getOperand(0).getMBB();
438     return false;
439   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
440       LastInst->getOpcode() == PPC::B) {
441     if (!SecondLastInst->getOperand(1).isMBB() ||
442         !LastInst->getOperand(0).isMBB())
443       return true;
444     TBB =  SecondLastInst->getOperand(1).getMBB();
445     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
446     Cond.push_back(SecondLastInst->getOperand(0));
447     FBB = LastInst->getOperand(0).getMBB();
448     return false;
449   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
450               SecondLastInst->getOpcode() == PPC::BDNZ) &&
451       LastInst->getOpcode() == PPC::B) {
452     if (!SecondLastInst->getOperand(0).isMBB() ||
453         !LastInst->getOperand(0).isMBB())
454       return true;
455     if (DisableCTRLoopAnal)
456       return true;
457     TBB = SecondLastInst->getOperand(0).getMBB();
458     Cond.push_back(MachineOperand::CreateImm(1));
459     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
460                                              true));
461     FBB = LastInst->getOperand(0).getMBB();
462     return false;
463   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
464               SecondLastInst->getOpcode() == PPC::BDZ) &&
465       LastInst->getOpcode() == PPC::B) {
466     if (!SecondLastInst->getOperand(0).isMBB() ||
467         !LastInst->getOperand(0).isMBB())
468       return true;
469     if (DisableCTRLoopAnal)
470       return true;
471     TBB = SecondLastInst->getOperand(0).getMBB();
472     Cond.push_back(MachineOperand::CreateImm(0));
473     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
474                                              true));
475     FBB = LastInst->getOperand(0).getMBB();
476     return false;
477   }
478
479   // If the block ends with two PPC:Bs, handle it.  The second one is not
480   // executed, so remove it.
481   if (SecondLastInst->getOpcode() == PPC::B &&
482       LastInst->getOpcode() == PPC::B) {
483     if (!SecondLastInst->getOperand(0).isMBB())
484       return true;
485     TBB = SecondLastInst->getOperand(0).getMBB();
486     I = LastInst;
487     if (AllowModify)
488       I->eraseFromParent();
489     return false;
490   }
491
492   // Otherwise, can't handle this.
493   return true;
494 }
495
496 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
497   MachineBasicBlock::iterator I = MBB.end();
498   if (I == MBB.begin()) return 0;
499   --I;
500   while (I->isDebugValue()) {
501     if (I == MBB.begin())
502       return 0;
503     --I;
504   }
505   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
506       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
507       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
508       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
509     return 0;
510
511   // Remove the branch.
512   I->eraseFromParent();
513
514   I = MBB.end();
515
516   if (I == MBB.begin()) return 1;
517   --I;
518   if (I->getOpcode() != PPC::BCC &&
519       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
520       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
521       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
522     return 1;
523
524   // Remove the branch.
525   I->eraseFromParent();
526   return 2;
527 }
528
529 unsigned
530 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
531                            MachineBasicBlock *FBB,
532                            const SmallVectorImpl<MachineOperand> &Cond,
533                            DebugLoc DL) const {
534   // Shouldn't be a fall through.
535   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
536   assert((Cond.size() == 2 || Cond.size() == 0) &&
537          "PPC branch conditions have two components!");
538
539   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
540
541   // One-way branch.
542   if (FBB == 0) {
543     if (Cond.empty())   // Unconditional branch
544       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
545     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
546       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
547                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
548                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
549     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
550       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
551     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
552       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
553     else                // Conditional branch
554       BuildMI(&MBB, DL, get(PPC::BCC))
555         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
556     return 1;
557   }
558
559   // Two-way Conditional Branch.
560   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
561     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
562                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
563                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
564   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
565     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
566   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
567     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
568   else
569     BuildMI(&MBB, DL, get(PPC::BCC))
570       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
571   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
572   return 2;
573 }
574
575 // Select analysis.
576 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
577                 const SmallVectorImpl<MachineOperand> &Cond,
578                 unsigned TrueReg, unsigned FalseReg,
579                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
580   if (!TM.getSubtargetImpl()->hasISEL())
581     return false;
582
583   if (Cond.size() != 2)
584     return false;
585
586   // If this is really a bdnz-like condition, then it cannot be turned into a
587   // select.
588   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
589     return false;
590
591   // Check register classes.
592   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
593   const TargetRegisterClass *RC =
594     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
595   if (!RC)
596     return false;
597
598   // isel is for regular integer GPRs only.
599   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
600       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
601       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
602       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
603     return false;
604
605   // FIXME: These numbers are for the A2, how well they work for other cores is
606   // an open question. On the A2, the isel instruction has a 2-cycle latency
607   // but single-cycle throughput. These numbers are used in combination with
608   // the MispredictPenalty setting from the active SchedMachineModel.
609   CondCycles = 1;
610   TrueCycles = 1;
611   FalseCycles = 1;
612
613   return true;
614 }
615
616 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
617                                 MachineBasicBlock::iterator MI, DebugLoc dl,
618                                 unsigned DestReg,
619                                 const SmallVectorImpl<MachineOperand> &Cond,
620                                 unsigned TrueReg, unsigned FalseReg) const {
621   assert(Cond.size() == 2 &&
622          "PPC branch conditions have two components!");
623
624   assert(TM.getSubtargetImpl()->hasISEL() &&
625          "Cannot insert select on target without ISEL support");
626
627   // Get the register classes.
628   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
629   const TargetRegisterClass *RC =
630     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
631   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
632
633   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
634                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
635   assert((Is64Bit ||
636           PPC::GPRCRegClass.hasSubClassEq(RC) ||
637           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
638          "isel is for regular integer GPRs only");
639
640   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
641   unsigned SelectPred = Cond[0].getImm();
642
643   unsigned SubIdx;
644   bool SwapOps;
645   switch (SelectPred) {
646   default: llvm_unreachable("invalid predicate for isel");
647   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
648   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
649   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
650   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
651   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
652   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
653   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
654   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
655   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
656   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
657   }
658
659   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
660            SecondReg = SwapOps ? TrueReg  : FalseReg;
661
662   // The first input register of isel cannot be r0. If it is a member
663   // of a register class that can be r0, then copy it first (the
664   // register allocator should eliminate the copy).
665   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
666       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
667     const TargetRegisterClass *FirstRC =
668       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
669         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
670     unsigned OldFirstReg = FirstReg;
671     FirstReg = MRI.createVirtualRegister(FirstRC);
672     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
673       .addReg(OldFirstReg);
674   }
675
676   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
677     .addReg(FirstReg).addReg(SecondReg)
678     .addReg(Cond[1].getReg(), 0, SubIdx);
679 }
680
681 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
682                                MachineBasicBlock::iterator I, DebugLoc DL,
683                                unsigned DestReg, unsigned SrcReg,
684                                bool KillSrc) const {
685   // We can end up with self copies and similar things as a result of VSX copy
686   // legalization. Promote them here.
687   const TargetRegisterInfo *TRI = &getRegisterInfo();
688   if (PPC::F8RCRegClass.contains(DestReg) &&
689       PPC::VSLRCRegClass.contains(SrcReg)) {
690     unsigned SuperReg =
691       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
692
693     if (VSXSelfCopyCrash && SrcReg == SuperReg)
694       llvm_unreachable("nop VSX copy");
695
696     DestReg = SuperReg;
697   } else if (PPC::VRRCRegClass.contains(DestReg) &&
698              PPC::VSHRCRegClass.contains(SrcReg)) {
699     unsigned SuperReg =
700       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
701
702     if (VSXSelfCopyCrash && SrcReg == SuperReg)
703       llvm_unreachable("nop VSX copy");
704
705     DestReg = SuperReg;
706   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
707              PPC::VSLRCRegClass.contains(DestReg)) {
708     unsigned SuperReg =
709       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
710
711     if (VSXSelfCopyCrash && DestReg == SuperReg)
712       llvm_unreachable("nop VSX copy");
713
714     SrcReg = SuperReg;
715   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
716              PPC::VSHRCRegClass.contains(DestReg)) {
717     unsigned SuperReg =
718       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
719
720     if (VSXSelfCopyCrash && DestReg == SuperReg)
721       llvm_unreachable("nop VSX copy");
722
723     SrcReg = SuperReg;
724   }
725
726   unsigned Opc;
727   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
728     Opc = PPC::OR;
729   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
730     Opc = PPC::OR8;
731   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
732     Opc = PPC::FMR;
733   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
734     Opc = PPC::MCRF;
735   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
736     Opc = PPC::VOR;
737   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
738     // There are two different ways this can be done:
739     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
740     //      issue in VSU pipeline 0.
741     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
742     //      can go to either pipeline.
743     // We'll always use xxlor here, because in practically all cases where
744     // copies are generated, they are close enough to some use that the
745     // lower-latency form is preferable.
746     Opc = PPC::XXLOR;
747   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
748     Opc = PPC::CROR;
749   else
750     llvm_unreachable("Impossible reg-to-reg copy");
751
752   const MCInstrDesc &MCID = get(Opc);
753   if (MCID.getNumOperands() == 3)
754     BuildMI(MBB, I, DL, MCID, DestReg)
755       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
756   else
757     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
758 }
759
760 // This function returns true if a CR spill is necessary and false otherwise.
761 bool
762 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
763                                   unsigned SrcReg, bool isKill,
764                                   int FrameIdx,
765                                   const TargetRegisterClass *RC,
766                                   SmallVectorImpl<MachineInstr*> &NewMIs,
767                                   bool &NonRI, bool &SpillsVRS) const{
768   // Note: If additional store instructions are added here,
769   // update isStoreToStackSlot.
770
771   DebugLoc DL;
772   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
773       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
774     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
775                                        .addReg(SrcReg,
776                                                getKillRegState(isKill)),
777                                        FrameIdx));
778   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
779              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
780     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
781                                        .addReg(SrcReg,
782                                                getKillRegState(isKill)),
783                                        FrameIdx));
784   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
785     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
786                                        .addReg(SrcReg,
787                                                getKillRegState(isKill)),
788                                        FrameIdx));
789   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
790     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
791                                        .addReg(SrcReg,
792                                                getKillRegState(isKill)),
793                                        FrameIdx));
794   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
795     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
796                                        .addReg(SrcReg,
797                                                getKillRegState(isKill)),
798                                        FrameIdx));
799     return true;
800   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
801     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
802                                        .addReg(SrcReg,
803                                                getKillRegState(isKill)),
804                                        FrameIdx));
805     return true;
806   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
807     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
808                                        .addReg(SrcReg,
809                                                getKillRegState(isKill)),
810                                        FrameIdx));
811     NonRI = true;
812   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
813     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
814                                        .addReg(SrcReg,
815                                                getKillRegState(isKill)),
816                                        FrameIdx));
817     NonRI = true;
818   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
819     assert(TM.getSubtargetImpl()->isDarwin() &&
820            "VRSAVE only needs spill/restore on Darwin");
821     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
822                                        .addReg(SrcReg,
823                                                getKillRegState(isKill)),
824                                        FrameIdx));
825     SpillsVRS = true;
826   } else {
827     llvm_unreachable("Unknown regclass!");
828   }
829
830   return false;
831 }
832
833 void
834 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
835                                   MachineBasicBlock::iterator MI,
836                                   unsigned SrcReg, bool isKill, int FrameIdx,
837                                   const TargetRegisterClass *RC,
838                                   const TargetRegisterInfo *TRI) const {
839   MachineFunction &MF = *MBB.getParent();
840   SmallVector<MachineInstr*, 4> NewMIs;
841
842   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
843   FuncInfo->setHasSpills();
844
845   bool NonRI = false, SpillsVRS = false;
846   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
847                           NonRI, SpillsVRS))
848     FuncInfo->setSpillsCR();
849
850   if (SpillsVRS)
851     FuncInfo->setSpillsVRSAVE();
852
853   if (NonRI)
854     FuncInfo->setHasNonRISpills();
855
856   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
857     MBB.insert(MI, NewMIs[i]);
858
859   const MachineFrameInfo &MFI = *MF.getFrameInfo();
860   MachineMemOperand *MMO =
861     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
862                             MachineMemOperand::MOStore,
863                             MFI.getObjectSize(FrameIdx),
864                             MFI.getObjectAlignment(FrameIdx));
865   NewMIs.back()->addMemOperand(MF, MMO);
866 }
867
868 bool
869 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
870                                    unsigned DestReg, int FrameIdx,
871                                    const TargetRegisterClass *RC,
872                                    SmallVectorImpl<MachineInstr*> &NewMIs,
873                                    bool &NonRI, bool &SpillsVRS) const{
874   // Note: If additional load instructions are added here,
875   // update isLoadFromStackSlot.
876
877   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
878       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
879     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
880                                                DestReg), FrameIdx));
881   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
882              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
883     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
884                                        FrameIdx));
885   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
886     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
887                                        FrameIdx));
888   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
889     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
890                                        FrameIdx));
891   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
892     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
893                                                get(PPC::RESTORE_CR), DestReg),
894                                        FrameIdx));
895     return true;
896   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
897     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
898                                                get(PPC::RESTORE_CRBIT), DestReg),
899                                        FrameIdx));
900     return true;
901   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
902     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
903                                        FrameIdx));
904     NonRI = true;
905   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
906     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
907                                        FrameIdx));
908     NonRI = true;
909   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
910     assert(TM.getSubtargetImpl()->isDarwin() &&
911            "VRSAVE only needs spill/restore on Darwin");
912     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
913                                                get(PPC::RESTORE_VRSAVE),
914                                                DestReg),
915                                        FrameIdx));
916     SpillsVRS = true;
917   } else {
918     llvm_unreachable("Unknown regclass!");
919   }
920
921   return false;
922 }
923
924 void
925 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
926                                    MachineBasicBlock::iterator MI,
927                                    unsigned DestReg, int FrameIdx,
928                                    const TargetRegisterClass *RC,
929                                    const TargetRegisterInfo *TRI) const {
930   MachineFunction &MF = *MBB.getParent();
931   SmallVector<MachineInstr*, 4> NewMIs;
932   DebugLoc DL;
933   if (MI != MBB.end()) DL = MI->getDebugLoc();
934
935   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
936   FuncInfo->setHasSpills();
937
938   bool NonRI = false, SpillsVRS = false;
939   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
940                            NonRI, SpillsVRS))
941     FuncInfo->setSpillsCR();
942
943   if (SpillsVRS)
944     FuncInfo->setSpillsVRSAVE();
945
946   if (NonRI)
947     FuncInfo->setHasNonRISpills();
948
949   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
950     MBB.insert(MI, NewMIs[i]);
951
952   const MachineFrameInfo &MFI = *MF.getFrameInfo();
953   MachineMemOperand *MMO =
954     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
955                             MachineMemOperand::MOLoad,
956                             MFI.getObjectSize(FrameIdx),
957                             MFI.getObjectAlignment(FrameIdx));
958   NewMIs.back()->addMemOperand(MF, MMO);
959 }
960
961 bool PPCInstrInfo::
962 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
963   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
964   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
965     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
966   else
967     // Leave the CR# the same, but invert the condition.
968     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
969   return false;
970 }
971
972 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
973                              unsigned Reg, MachineRegisterInfo *MRI) const {
974   // For some instructions, it is legal to fold ZERO into the RA register field.
975   // A zero immediate should always be loaded with a single li.
976   unsigned DefOpc = DefMI->getOpcode();
977   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
978     return false;
979   if (!DefMI->getOperand(1).isImm())
980     return false;
981   if (DefMI->getOperand(1).getImm() != 0)
982     return false;
983
984   // Note that we cannot here invert the arguments of an isel in order to fold
985   // a ZERO into what is presented as the second argument. All we have here
986   // is the condition bit, and that might come from a CR-logical bit operation.
987
988   const MCInstrDesc &UseMCID = UseMI->getDesc();
989
990   // Only fold into real machine instructions.
991   if (UseMCID.isPseudo())
992     return false;
993
994   unsigned UseIdx;
995   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
996     if (UseMI->getOperand(UseIdx).isReg() &&
997         UseMI->getOperand(UseIdx).getReg() == Reg)
998       break;
999
1000   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1001   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1002
1003   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1004
1005   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1006   // register (which might also be specified as a pointer class kind).
1007   if (UseInfo->isLookupPtrRegClass()) {
1008     if (UseInfo->RegClass /* Kind */ != 1)
1009       return false;
1010   } else {
1011     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1012         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1013       return false;
1014   }
1015
1016   // Make sure this is not tied to an output register (or otherwise
1017   // constrained). This is true for ST?UX registers, for example, which
1018   // are tied to their output registers.
1019   if (UseInfo->Constraints != 0)
1020     return false;
1021
1022   unsigned ZeroReg;
1023   if (UseInfo->isLookupPtrRegClass()) {
1024     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1025     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1026   } else {
1027     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1028               PPC::ZERO8 : PPC::ZERO;
1029   }
1030
1031   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1032   UseMI->getOperand(UseIdx).setReg(ZeroReg);
1033
1034   if (DeleteDef)
1035     DefMI->eraseFromParent();
1036
1037   return true;
1038 }
1039
1040 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1041   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1042        I != IE; ++I)
1043     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1044       return true;
1045   return false;
1046 }
1047
1048 // We should make sure that, if we're going to predicate both sides of a
1049 // condition (a diamond), that both sides don't define the counter register. We
1050 // can predicate counter-decrement-based branches, but while that predicates
1051 // the branching, it does not predicate the counter decrement. If we tried to
1052 // merge the triangle into one predicated block, we'd decrement the counter
1053 // twice.
1054 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1055                      unsigned NumT, unsigned ExtraT,
1056                      MachineBasicBlock &FMBB,
1057                      unsigned NumF, unsigned ExtraF,
1058                      const BranchProbability &Probability) const {
1059   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1060 }
1061
1062
1063 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1064   // The predicated branches are identified by their type, not really by the
1065   // explicit presence of a predicate. Furthermore, some of them can be
1066   // predicated more than once. Because if conversion won't try to predicate
1067   // any instruction which already claims to be predicated (by returning true
1068   // here), always return false. In doing so, we let isPredicable() be the
1069   // final word on whether not the instruction can be (further) predicated.
1070
1071   return false;
1072 }
1073
1074 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1075   if (!MI->isTerminator())
1076     return false;
1077
1078   // Conditional branch is a special case.
1079   if (MI->isBranch() && !MI->isBarrier())
1080     return true;
1081
1082   return !isPredicated(MI);
1083 }
1084
1085 bool PPCInstrInfo::PredicateInstruction(
1086                      MachineInstr *MI,
1087                      const SmallVectorImpl<MachineOperand> &Pred) const {
1088   unsigned OpC = MI->getOpcode();
1089   if (OpC == PPC::BLR) {
1090     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1091       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1092       MI->setDesc(get(Pred[0].getImm() ?
1093                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1094                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
1095     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1096       MI->setDesc(get(PPC::BCLR));
1097       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1098         .addReg(Pred[1].getReg());
1099     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1100       MI->setDesc(get(PPC::BCLRn));
1101       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1102         .addReg(Pred[1].getReg());
1103     } else {
1104       MI->setDesc(get(PPC::BCCLR));
1105       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1106         .addImm(Pred[0].getImm())
1107         .addReg(Pred[1].getReg());
1108     }
1109
1110     return true;
1111   } else if (OpC == PPC::B) {
1112     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1113       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1114       MI->setDesc(get(Pred[0].getImm() ?
1115                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1116                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
1117     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1118       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1119       MI->RemoveOperand(0);
1120
1121       MI->setDesc(get(PPC::BC));
1122       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1123         .addReg(Pred[1].getReg())
1124         .addMBB(MBB);
1125     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1126       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1127       MI->RemoveOperand(0);
1128
1129       MI->setDesc(get(PPC::BCn));
1130       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1131         .addReg(Pred[1].getReg())
1132         .addMBB(MBB);
1133     } else {
1134       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1135       MI->RemoveOperand(0);
1136
1137       MI->setDesc(get(PPC::BCC));
1138       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1139         .addImm(Pred[0].getImm())
1140         .addReg(Pred[1].getReg())
1141         .addMBB(MBB);
1142     }
1143
1144     return true;
1145   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1146              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1147     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1148       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1149
1150     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1151     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1152
1153     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1154       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1155                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
1156       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1157         .addReg(Pred[1].getReg());
1158       return true;
1159     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1160       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1161                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
1162       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1163         .addReg(Pred[1].getReg());
1164       return true;
1165     }
1166
1167     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1168                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
1169     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1170       .addImm(Pred[0].getImm())
1171       .addReg(Pred[1].getReg());
1172     return true;
1173   }
1174
1175   return false;
1176 }
1177
1178 bool PPCInstrInfo::SubsumesPredicate(
1179                      const SmallVectorImpl<MachineOperand> &Pred1,
1180                      const SmallVectorImpl<MachineOperand> &Pred2) const {
1181   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1182   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1183
1184   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1185     return false;
1186   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1187     return false;
1188
1189   // P1 can only subsume P2 if they test the same condition register.
1190   if (Pred1[1].getReg() != Pred2[1].getReg())
1191     return false;
1192
1193   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1194   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1195
1196   if (P1 == P2)
1197     return true;
1198
1199   // Does P1 subsume P2, e.g. GE subsumes GT.
1200   if (P1 == PPC::PRED_LE &&
1201       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1202     return true;
1203   if (P1 == PPC::PRED_GE &&
1204       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1205     return true;
1206
1207   return false;
1208 }
1209
1210 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1211                                     std::vector<MachineOperand> &Pred) const {
1212   // Note: At the present time, the contents of Pred from this function is
1213   // unused by IfConversion. This implementation follows ARM by pushing the
1214   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1215   // predicate, instructions defining CTR or CTR8 are also included as
1216   // predicate-defining instructions.
1217
1218   const TargetRegisterClass *RCs[] =
1219     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1220       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1221
1222   bool Found = false;
1223   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1224     const MachineOperand &MO = MI->getOperand(i);
1225     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1226       const TargetRegisterClass *RC = RCs[c];
1227       if (MO.isReg()) {
1228         if (MO.isDef() && RC->contains(MO.getReg())) {
1229           Pred.push_back(MO);
1230           Found = true;
1231         }
1232       } else if (MO.isRegMask()) {
1233         for (TargetRegisterClass::iterator I = RC->begin(),
1234              IE = RC->end(); I != IE; ++I)
1235           if (MO.clobbersPhysReg(*I)) {
1236             Pred.push_back(MO);
1237             Found = true;
1238           }
1239       }
1240     }
1241   }
1242
1243   return Found;
1244 }
1245
1246 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1247   unsigned OpC = MI->getOpcode();
1248   switch (OpC) {
1249   default:
1250     return false;
1251   case PPC::B:
1252   case PPC::BLR:
1253   case PPC::BCTR:
1254   case PPC::BCTR8:
1255   case PPC::BCTRL:
1256   case PPC::BCTRL8:
1257     return true;
1258   }
1259 }
1260
1261 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1262                                   unsigned &SrcReg, unsigned &SrcReg2,
1263                                   int &Mask, int &Value) const {
1264   unsigned Opc = MI->getOpcode();
1265
1266   switch (Opc) {
1267   default: return false;
1268   case PPC::CMPWI:
1269   case PPC::CMPLWI:
1270   case PPC::CMPDI:
1271   case PPC::CMPLDI:
1272     SrcReg = MI->getOperand(1).getReg();
1273     SrcReg2 = 0;
1274     Value = MI->getOperand(2).getImm();
1275     Mask = 0xFFFF;
1276     return true;
1277   case PPC::CMPW:
1278   case PPC::CMPLW:
1279   case PPC::CMPD:
1280   case PPC::CMPLD:
1281   case PPC::FCMPUS:
1282   case PPC::FCMPUD:
1283     SrcReg = MI->getOperand(1).getReg();
1284     SrcReg2 = MI->getOperand(2).getReg();
1285     return true;
1286   }
1287 }
1288
1289 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1290                                         unsigned SrcReg, unsigned SrcReg2,
1291                                         int Mask, int Value,
1292                                         const MachineRegisterInfo *MRI) const {
1293   if (DisableCmpOpt)
1294     return false;
1295
1296   int OpC = CmpInstr->getOpcode();
1297   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1298
1299   // FP record forms set CR1 based on the execption status bits, not a
1300   // comparison with zero.
1301   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1302     return false;
1303
1304   // The record forms set the condition register based on a signed comparison
1305   // with zero (so says the ISA manual). This is not as straightforward as it
1306   // seems, however, because this is always a 64-bit comparison on PPC64, even
1307   // for instructions that are 32-bit in nature (like slw for example).
1308   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1309   // for equality checks (as those don't depend on the sign). On PPC64,
1310   // we are restricted to equality for unsigned 64-bit comparisons and for
1311   // signed 32-bit comparisons the applicability is more restricted.
1312   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1313   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1314   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1315   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1316
1317   // Get the unique definition of SrcReg.
1318   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1319   if (!MI) return false;
1320   int MIOpC = MI->getOpcode();
1321
1322   bool equalityOnly = false;
1323   bool noSub = false;
1324   if (isPPC64) {
1325     if (is32BitSignedCompare) {
1326       // We can perform this optimization only if MI is sign-extending.
1327       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1328           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1329           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1330           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1331           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1332         noSub = true;
1333       } else
1334         return false;
1335     } else if (is32BitUnsignedCompare) {
1336       // We can perform this optimization, equality only, if MI is
1337       // zero-extending.
1338       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1339           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1340           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1341         noSub = true;
1342         equalityOnly = true;
1343       } else
1344         return false;
1345     } else
1346       equalityOnly = is64BitUnsignedCompare;
1347   } else
1348     equalityOnly = is32BitUnsignedCompare;
1349
1350   if (equalityOnly) {
1351     // We need to check the uses of the condition register in order to reject
1352     // non-equality comparisons.
1353     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1354          IE = MRI->use_instr_end(); I != IE; ++I) {
1355       MachineInstr *UseMI = &*I;
1356       if (UseMI->getOpcode() == PPC::BCC) {
1357         unsigned Pred = UseMI->getOperand(0).getImm();
1358         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1359           return false;
1360       } else if (UseMI->getOpcode() == PPC::ISEL ||
1361                  UseMI->getOpcode() == PPC::ISEL8) {
1362         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1363         if (SubIdx != PPC::sub_eq)
1364           return false;
1365       } else
1366         return false;
1367     }
1368   }
1369
1370   MachineBasicBlock::iterator I = CmpInstr;
1371
1372   // Scan forward to find the first use of the compare.
1373   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1374        I != EL; ++I) {
1375     bool FoundUse = false;
1376     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1377          JE = MRI->use_instr_end(); J != JE; ++J)
1378       if (&*J == &*I) {
1379         FoundUse = true;
1380         break;
1381       }
1382
1383     if (FoundUse)
1384       break;
1385   }
1386
1387   // There are two possible candidates which can be changed to set CR[01].
1388   // One is MI, the other is a SUB instruction.
1389   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1390   MachineInstr *Sub = NULL;
1391   if (SrcReg2 != 0)
1392     // MI is not a candidate for CMPrr.
1393     MI = NULL;
1394   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1395   // same BB as the comparison. This is to allow the check below to avoid calls
1396   // (and other explicit clobbers); instead we should really check for these
1397   // more explicitly (in at least a few predecessors).
1398   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1399     // PPC does not have a record-form SUBri.
1400     return false;
1401   }
1402
1403   // Search for Sub.
1404   const TargetRegisterInfo *TRI = &getRegisterInfo();
1405   --I;
1406
1407   // Get ready to iterate backward from CmpInstr.
1408   MachineBasicBlock::iterator E = MI,
1409                               B = CmpInstr->getParent()->begin();
1410
1411   for (; I != E && !noSub; --I) {
1412     const MachineInstr &Instr = *I;
1413     unsigned IOpC = Instr.getOpcode();
1414
1415     if (&*I != CmpInstr && (
1416         Instr.modifiesRegister(PPC::CR0, TRI) ||
1417         Instr.readsRegister(PPC::CR0, TRI)))
1418       // This instruction modifies or uses the record condition register after
1419       // the one we want to change. While we could do this transformation, it
1420       // would likely not be profitable. This transformation removes one
1421       // instruction, and so even forcing RA to generate one move probably
1422       // makes it unprofitable.
1423       return false;
1424
1425     // Check whether CmpInstr can be made redundant by the current instruction.
1426     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1427          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1428         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1429         ((Instr.getOperand(1).getReg() == SrcReg &&
1430           Instr.getOperand(2).getReg() == SrcReg2) ||
1431         (Instr.getOperand(1).getReg() == SrcReg2 &&
1432          Instr.getOperand(2).getReg() == SrcReg))) {
1433       Sub = &*I;
1434       break;
1435     }
1436
1437     if (I == B)
1438       // The 'and' is below the comparison instruction.
1439       return false;
1440   }
1441
1442   // Return false if no candidates exist.
1443   if (!MI && !Sub)
1444     return false;
1445
1446   // The single candidate is called MI.
1447   if (!MI) MI = Sub;
1448
1449   int NewOpC = -1;
1450   MIOpC = MI->getOpcode();
1451   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1452     NewOpC = MIOpC;
1453   else {
1454     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1455     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1456       NewOpC = MIOpC;
1457   }
1458
1459   // FIXME: On the non-embedded POWER architectures, only some of the record
1460   // forms are fast, and we should use only the fast ones.
1461
1462   // The defining instruction has a record form (or is already a record
1463   // form). It is possible, however, that we'll need to reverse the condition
1464   // code of the users.
1465   if (NewOpC == -1)
1466     return false;
1467
1468   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1469   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1470
1471   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1472   // needs to be updated to be based on SUB.  Push the condition code
1473   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1474   // condition code of these operands will be modified.
1475   bool ShouldSwap = false;
1476   if (Sub) {
1477     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1478       Sub->getOperand(2).getReg() == SrcReg;
1479
1480     // The operands to subf are the opposite of sub, so only in the fixed-point
1481     // case, invert the order.
1482     ShouldSwap = !ShouldSwap;
1483   }
1484
1485   if (ShouldSwap)
1486     for (MachineRegisterInfo::use_instr_iterator
1487          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1488          I != IE; ++I) {
1489       MachineInstr *UseMI = &*I;
1490       if (UseMI->getOpcode() == PPC::BCC) {
1491         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1492         assert((!equalityOnly ||
1493                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1494                "Invalid predicate for equality-only optimization");
1495         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1496                                 PPC::getSwappedPredicate(Pred)));
1497       } else if (UseMI->getOpcode() == PPC::ISEL ||
1498                  UseMI->getOpcode() == PPC::ISEL8) {
1499         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1500         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1501                "Invalid CR bit for equality-only optimization");
1502
1503         if (NewSubReg == PPC::sub_lt)
1504           NewSubReg = PPC::sub_gt;
1505         else if (NewSubReg == PPC::sub_gt)
1506           NewSubReg = PPC::sub_lt;
1507
1508         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1509                                                  NewSubReg));
1510       } else // We need to abort on a user we don't understand.
1511         return false;
1512     }
1513
1514   // Create a new virtual register to hold the value of the CR set by the
1515   // record-form instruction. If the instruction was not previously in
1516   // record form, then set the kill flag on the CR.
1517   CmpInstr->eraseFromParent();
1518
1519   MachineBasicBlock::iterator MII = MI;
1520   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1521           get(TargetOpcode::COPY), CRReg)
1522     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1523
1524   if (MIOpC != NewOpC) {
1525     // We need to be careful here: we're replacing one instruction with
1526     // another, and we need to make sure that we get all of the right
1527     // implicit uses and defs. On the other hand, the caller may be holding
1528     // an iterator to this instruction, and so we can't delete it (this is
1529     // specifically the case if this is the instruction directly after the
1530     // compare).
1531
1532     const MCInstrDesc &NewDesc = get(NewOpC);
1533     MI->setDesc(NewDesc);
1534
1535     if (NewDesc.ImplicitDefs)
1536       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1537            *ImpDefs; ++ImpDefs)
1538         if (!MI->definesRegister(*ImpDefs))
1539           MI->addOperand(*MI->getParent()->getParent(),
1540                          MachineOperand::CreateReg(*ImpDefs, true, true));
1541     if (NewDesc.ImplicitUses)
1542       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1543            *ImpUses; ++ImpUses)
1544         if (!MI->readsRegister(*ImpUses))
1545           MI->addOperand(*MI->getParent()->getParent(),
1546                          MachineOperand::CreateReg(*ImpUses, false, true));
1547   }
1548
1549   // Modify the condition code of operands in OperandsToUpdate.
1550   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1551   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1552   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1553     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1554
1555   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1556     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1557
1558   return true;
1559 }
1560
1561 /// GetInstSize - Return the number of bytes of code the specified
1562 /// instruction may be.  This returns the maximum number of bytes.
1563 ///
1564 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1565   unsigned Opcode = MI->getOpcode();
1566
1567   if (Opcode == PPC::INLINEASM) {
1568     const MachineFunction *MF = MI->getParent()->getParent();
1569     const char *AsmStr = MI->getOperand(0).getSymbolName();
1570     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1571   } else {
1572     const MCInstrDesc &Desc = get(Opcode);
1573     return Desc.getSize();
1574   }
1575 }
1576
1577 #undef DEBUG_TYPE
1578 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1579
1580 namespace {
1581   // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1582   // (Altivec and scalar floating-point registers), we need to transform the
1583   // copies into subregister copies with other restrictions.
1584   struct PPCVSXFMAMutate : public MachineFunctionPass {
1585     static char ID;
1586     PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1587       initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1588     }
1589
1590     LiveIntervals *LIS;
1591
1592     const PPCTargetMachine *TM;
1593     const PPCInstrInfo *TII;
1594
1595 protected:
1596     bool processBlock(MachineBasicBlock &MBB) {
1597       bool Changed = false;
1598
1599       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1600       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1601            I != IE; ++I) {
1602         MachineInstr *MI = I;
1603
1604         // The default (A-type) VSX FMA form kills the addend (it is taken from
1605         // the target register, which is then updated to reflect the result of
1606         // the FMA). If the instruction, however, kills one of the registers
1607         // used for the product, then we can use the M-form instruction (which
1608         // will take that value from the to-be-defined register).
1609
1610         int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1611         if (AltOpc == -1)
1612           continue;
1613
1614         // This pass is run after register coalescing, and so we're looking for
1615         // a situation like this:
1616         //   ...
1617         //   %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1618         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1619         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1620         //   ...
1621         //   %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1622         //                         %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1623         //   ...
1624         // Where we can eliminate the copy by changing from the A-type to the
1625         // M-type instruction. Specifically, for this example, this means:
1626         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1627         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1628         // is replaced by:
1629         //   %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1630         //                         %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1631         // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1632
1633         SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1634
1635         VNInfo *AddendValNo =
1636           LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1637         MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1638
1639         // The addend and this instruction must be in the same block.
1640
1641         if (AddendMI->getParent() != MI->getParent())
1642           continue;
1643
1644         // The addend must be a full copy within the same register class.
1645
1646         if (!AddendMI->isFullCopy())
1647           continue;
1648
1649         if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1650             MRI.getRegClass(AddendMI->getOperand(1).getReg()))
1651           continue;
1652
1653         // In theory, there could be other uses of the addend copy before this
1654         // fma.  We could deal with this, but that would require additional
1655         // logic below and I suspect it will not occur in any relevant
1656         // situations.
1657         bool OtherUsers = false;
1658         for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1659              J != JE; --J)
1660           if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1661             OtherUsers = true;
1662             break;
1663           }
1664
1665         if (OtherUsers)
1666           continue;
1667
1668         // Find one of the product operands that is killed by this instruction.
1669
1670         unsigned KilledProdOp = 0, OtherProdOp = 0;
1671         if (LIS->getInterval(MI->getOperand(2).getReg())
1672                      .Query(FMAIdx).isKill()) {
1673           KilledProdOp = 2;
1674           OtherProdOp  = 3;
1675         } else if (LIS->getInterval(MI->getOperand(3).getReg())
1676                      .Query(FMAIdx).isKill()) {
1677           KilledProdOp = 3;
1678           OtherProdOp  = 2;
1679         }
1680
1681         // If there are no killed product operands, then this transformation is
1682         // likely not profitable.
1683         if (!KilledProdOp)
1684           continue;
1685
1686         // In order to replace the addend here with the source of the copy,
1687         // it must still be live here.
1688         if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1689           continue;
1690
1691         // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1692
1693         unsigned AddReg = AddendMI->getOperand(1).getReg();
1694         unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1695         unsigned OtherProdReg  = MI->getOperand(OtherProdOp).getReg();
1696
1697         unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1698         unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1699         unsigned OtherProdSubReg  = MI->getOperand(OtherProdOp).getSubReg();
1700
1701         bool AddRegKill = AddendMI->getOperand(1).isKill();
1702         bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1703         bool OtherProdRegKill  = MI->getOperand(OtherProdOp).isKill();
1704
1705         bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1706         bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1707         bool OtherProdRegUndef  = MI->getOperand(OtherProdOp).isUndef();
1708
1709         unsigned OldFMAReg = MI->getOperand(0).getReg();
1710
1711         assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1712                "Addend copy not tied to old FMA output!");
1713
1714         DEBUG(dbgs() << "VSX FMA Mutation:\n    " << *MI;);
1715
1716         MI->getOperand(0).setReg(KilledProdReg);
1717         MI->getOperand(1).setReg(KilledProdReg);
1718         MI->getOperand(3).setReg(AddReg);
1719         MI->getOperand(2).setReg(OtherProdReg);
1720
1721         MI->getOperand(0).setSubReg(KilledProdSubReg);
1722         MI->getOperand(1).setSubReg(KilledProdSubReg);
1723         MI->getOperand(3).setSubReg(AddSubReg);
1724         MI->getOperand(2).setSubReg(OtherProdSubReg);
1725
1726         MI->getOperand(1).setIsKill(KilledProdRegKill);
1727         MI->getOperand(3).setIsKill(AddRegKill);
1728         MI->getOperand(2).setIsKill(OtherProdRegKill);
1729
1730         MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1731         MI->getOperand(3).setIsUndef(AddRegUndef);
1732         MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1733
1734         MI->setDesc(TII->get(AltOpc));
1735
1736         DEBUG(dbgs() << " -> " << *MI);
1737
1738         // The killed product operand was killed here, so we can reuse it now
1739         // for the result of the fma.
1740
1741         LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1742         VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1743         for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1744              UI != UE;) {
1745           MachineOperand &UseMO = *UI;
1746           MachineInstr *UseMI = UseMO.getParent();
1747           ++UI;
1748
1749           // Don't replace the result register of the copy we're about to erase.
1750           if (UseMI == AddendMI)
1751             continue;
1752
1753           UseMO.setReg(KilledProdReg);
1754           UseMO.setSubReg(KilledProdSubReg);
1755         }
1756
1757         // Extend the live intervals of the killed product operand to hold the
1758         // fma result.
1759
1760         LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1761         for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1762              AI != AE; ++AI) {
1763           // Don't add the segment that corresponds to the original copy.
1764           if (AI->valno == AddendValNo)
1765             continue;
1766
1767           VNInfo *NewFMAValNo =
1768             NewFMAInt.getNextValue(AI->start,
1769                                    LIS->getVNInfoAllocator());
1770
1771           NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1772                                                      NewFMAValNo));
1773         }
1774         DEBUG(dbgs() << "  extended: " << NewFMAInt << '\n');
1775
1776         FMAInt.removeValNo(FMAValNo);
1777         DEBUG(dbgs() << "  trimmed:  " << FMAInt << '\n');
1778
1779         // Remove the (now unused) copy.
1780
1781         DEBUG(dbgs() << "  removing: " << *AddendMI << '\n');
1782         LIS->RemoveMachineInstrFromMaps(AddendMI);
1783         AddendMI->eraseFromParent();
1784
1785         Changed = true;
1786       }
1787
1788       return Changed;
1789     }
1790
1791 public:
1792     virtual bool runOnMachineFunction(MachineFunction &MF) {
1793       LIS = &getAnalysis<LiveIntervals>();
1794
1795       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1796       TII = TM->getInstrInfo();
1797
1798       bool Changed = false;
1799
1800       if (DisableVSXFMAMutate)
1801         return Changed;
1802
1803       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1804         MachineBasicBlock &B = *I++;
1805         if (processBlock(B))
1806           Changed = true;
1807       }
1808
1809       return Changed;
1810     }
1811
1812     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1813       AU.addRequired<LiveIntervals>();
1814       AU.addPreserved<LiveIntervals>();
1815       AU.addRequired<SlotIndexes>();
1816       AU.addPreserved<SlotIndexes>();
1817       MachineFunctionPass::getAnalysisUsage(AU);
1818     }
1819   };
1820 }
1821
1822 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1823                       "PowerPC VSX FMA Mutation", false, false)
1824 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1825 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1826 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1827                     "PowerPC VSX FMA Mutation", false, false)
1828
1829 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1830
1831 char PPCVSXFMAMutate::ID = 0;
1832 FunctionPass*
1833 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1834
1835 #undef DEBUG_TYPE
1836 #define DEBUG_TYPE "ppc-vsx-copy"
1837
1838 namespace llvm {
1839   void initializePPCVSXCopyPass(PassRegistry&);
1840 }
1841
1842 namespace {
1843   // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1844   // (Altivec and scalar floating-point registers), we need to transform the
1845   // copies into subregister copies with other restrictions.
1846   struct PPCVSXCopy : public MachineFunctionPass {
1847     static char ID;
1848     PPCVSXCopy() : MachineFunctionPass(ID) {
1849       initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1850     }
1851
1852     const PPCTargetMachine *TM;
1853     const PPCInstrInfo *TII;
1854
1855     bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1856                       MachineRegisterInfo &MRI) {
1857       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1858         return RC->hasSubClassEq(MRI.getRegClass(Reg));
1859       } else if (RC->contains(Reg)) {
1860         return true;
1861       }
1862
1863       return false;
1864     }
1865
1866     bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1867       return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1868     }
1869
1870     bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1871       return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1872     }
1873
1874     bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1875       return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1876     }
1877
1878 protected:
1879     bool processBlock(MachineBasicBlock &MBB) {
1880       bool Changed = false;
1881
1882       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1883       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1884            I != IE; ++I) {
1885         MachineInstr *MI = I;
1886         if (!MI->isFullCopy())
1887           continue;
1888
1889         MachineOperand &DstMO = MI->getOperand(0);
1890         MachineOperand &SrcMO = MI->getOperand(1);
1891
1892         if ( IsVSReg(DstMO.getReg(), MRI) &&
1893             !IsVSReg(SrcMO.getReg(), MRI)) {
1894           // This is a copy *to* a VSX register from a non-VSX register.
1895           Changed = true;
1896
1897           const TargetRegisterClass *SrcRC =
1898             IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1899                                            &PPC::VSLRCRegClass;
1900           assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1901                   IsVRReg(SrcMO.getReg(), MRI)) &&
1902                  "Unknown source for a VSX copy");
1903
1904           unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1905           BuildMI(MBB, MI, MI->getDebugLoc(),
1906                   TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1907             .addImm(1) // add 1, not 0, because there is no implicit clearing
1908                        // of the high bits.
1909             .addOperand(SrcMO)
1910             .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1911                                                    PPC::sub_64);
1912
1913           // The source of the original copy is now the new virtual register.
1914           SrcMO.setReg(NewVReg);
1915         } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1916                     IsVSReg(SrcMO.getReg(), MRI)) {
1917           // This is a copy *from* a VSX register to a non-VSX register.
1918           Changed = true;
1919
1920           const TargetRegisterClass *DstRC =
1921             IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1922                                            &PPC::VSLRCRegClass;
1923           assert((IsF8Reg(DstMO.getReg(), MRI) ||
1924                   IsVRReg(DstMO.getReg(), MRI)) &&
1925                  "Unknown destination for a VSX copy");
1926
1927           // Copy the VSX value into a new VSX register of the correct subclass.
1928           unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1929           BuildMI(MBB, MI, MI->getDebugLoc(),
1930                   TII->get(TargetOpcode::COPY), NewVReg)
1931             .addOperand(SrcMO);
1932
1933           // Transform the original copy into a subregister extraction copy.
1934           SrcMO.setReg(NewVReg);
1935           SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1936                                                          PPC::sub_64);
1937         }
1938       }
1939
1940       return Changed;
1941     }
1942
1943 public:
1944     virtual bool runOnMachineFunction(MachineFunction &MF) {
1945       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1946       TII = TM->getInstrInfo();
1947
1948       bool Changed = false;
1949
1950       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1951         MachineBasicBlock &B = *I++;
1952         if (processBlock(B))
1953           Changed = true;
1954       }
1955
1956       return Changed;
1957     }
1958
1959     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1960       MachineFunctionPass::getAnalysisUsage(AU);
1961     }
1962   };
1963 }
1964
1965 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
1966                 "PowerPC VSX Copy Legalization", false, false)
1967
1968 char PPCVSXCopy::ID = 0;
1969 FunctionPass*
1970 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
1971
1972 #undef DEBUG_TYPE
1973 #define DEBUG_TYPE "ppc-early-ret"
1974 STATISTIC(NumBCLR, "Number of early conditional returns");
1975 STATISTIC(NumBLR,  "Number of early returns");
1976
1977 namespace llvm {
1978   void initializePPCEarlyReturnPass(PassRegistry&);
1979 }
1980
1981 namespace {
1982   // PPCEarlyReturn pass - For simple functions without epilogue code, move
1983   // returns up, and create conditional returns, to avoid unnecessary
1984   // branch-to-blr sequences.
1985   struct PPCEarlyReturn : public MachineFunctionPass {
1986     static char ID;
1987     PPCEarlyReturn() : MachineFunctionPass(ID) {
1988       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1989     }
1990
1991     const PPCTargetMachine *TM;
1992     const PPCInstrInfo *TII;
1993
1994 protected:
1995     bool processBlock(MachineBasicBlock &ReturnMBB) {
1996       bool Changed = false;
1997
1998       MachineBasicBlock::iterator I = ReturnMBB.begin();
1999       I = ReturnMBB.SkipPHIsAndLabels(I);
2000
2001       // The block must be essentially empty except for the blr.
2002       if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2003           I != ReturnMBB.getLastNonDebugInstr())
2004         return Changed;
2005
2006       SmallVector<MachineBasicBlock*, 8> PredToRemove;
2007       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2008            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2009         bool OtherReference = false, BlockChanged = false;
2010         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2011           if (J->getOpcode() == PPC::B) {
2012             if (J->getOperand(0).getMBB() == &ReturnMBB) {
2013               // This is an unconditional branch to the return. Replace the
2014               // branch with a blr.
2015               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2016               MachineBasicBlock::iterator K = J--;
2017               K->eraseFromParent();
2018               BlockChanged = true;
2019               ++NumBLR;
2020               continue;
2021             }
2022           } else if (J->getOpcode() == PPC::BCC) {
2023             if (J->getOperand(2).getMBB() == &ReturnMBB) {
2024               // This is a conditional branch to the return. Replace the branch
2025               // with a bclr.
2026               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2027                 .addImm(J->getOperand(0).getImm())
2028                 .addReg(J->getOperand(1).getReg());
2029               MachineBasicBlock::iterator K = J--;
2030               K->eraseFromParent();
2031               BlockChanged = true;
2032               ++NumBCLR;
2033               continue;
2034             }
2035           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2036             if (J->getOperand(1).getMBB() == &ReturnMBB) {
2037               // This is a conditional branch to the return. Replace the branch
2038               // with a bclr.
2039               BuildMI(**PI, J, J->getDebugLoc(),
2040                       TII->get(J->getOpcode() == PPC::BC ?
2041                                PPC::BCLR : PPC::BCLRn))
2042                 .addReg(J->getOperand(0).getReg());
2043               MachineBasicBlock::iterator K = J--;
2044               K->eraseFromParent();
2045               BlockChanged = true;
2046               ++NumBCLR;
2047               continue;
2048             }
2049           } else if (J->isBranch()) {
2050             if (J->isIndirectBranch()) {
2051               if (ReturnMBB.hasAddressTaken())
2052                 OtherReference = true;
2053             } else
2054               for (unsigned i = 0; i < J->getNumOperands(); ++i)
2055                 if (J->getOperand(i).isMBB() &&
2056                     J->getOperand(i).getMBB() == &ReturnMBB)
2057                   OtherReference = true;
2058           } else if (!J->isTerminator() && !J->isDebugValue())
2059             break;
2060
2061           if (J == (*PI)->begin())
2062             break;
2063
2064           --J;
2065         }
2066
2067         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2068           OtherReference = true;
2069
2070         // Predecessors are stored in a vector and can't be removed here.
2071         if (!OtherReference && BlockChanged) {
2072           PredToRemove.push_back(*PI);
2073         }
2074
2075         if (BlockChanged)
2076           Changed = true;
2077       }
2078
2079       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2080         PredToRemove[i]->removeSuccessor(&ReturnMBB);
2081
2082       if (Changed && !ReturnMBB.hasAddressTaken()) {
2083         // We now might be able to merge this blr-only block into its
2084         // by-layout predecessor.
2085         if (ReturnMBB.pred_size() == 1 &&
2086             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2087           // Move the blr into the preceding block.
2088           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2089           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2090           PrevMBB.removeSuccessor(&ReturnMBB);
2091         }
2092
2093         if (ReturnMBB.pred_empty())
2094           ReturnMBB.eraseFromParent();
2095       }
2096
2097       return Changed;
2098     }
2099
2100 public:
2101     virtual bool runOnMachineFunction(MachineFunction &MF) {
2102       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2103       TII = TM->getInstrInfo();
2104
2105       bool Changed = false;
2106
2107       // If the function does not have at least two blocks, then there is
2108       // nothing to do.
2109       if (MF.size() < 2)
2110         return Changed;
2111
2112       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2113         MachineBasicBlock &B = *I++;
2114         if (processBlock(B))
2115           Changed = true;
2116       }
2117
2118       return Changed;
2119     }
2120
2121     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2122       MachineFunctionPass::getAnalysisUsage(AU);
2123     }
2124   };
2125 }
2126
2127 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2128                 "PowerPC Early-Return Creation", false, false)
2129
2130 char PPCEarlyReturn::ID = 0;
2131 FunctionPass*
2132 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }