Add CR-bit tracking to the PowerPC backend for i1 values
[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/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 #define GET_INSTRMAP_INFO
36 #define GET_INSTRINFO_CTOR_DTOR
37 #include "PPCGenInstrInfo.inc"
38
39 using namespace llvm;
40
41 static cl::
42 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
43             cl::desc("Disable analysis for CTR loops"));
44
45 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
46 cl::desc("Disable compare instruction optimization"), cl::Hidden);
47
48 // Pin the vtable to this file.
49 void PPCInstrInfo::anchor() {}
50
51 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
52   : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
53     TM(tm), RI(*TM.getSubtargetImpl()) {}
54
55 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
56 /// this target when scheduling the DAG.
57 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
58   const TargetMachine *TM,
59   const ScheduleDAG *DAG) const {
60   unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
61   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
62       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
63     const InstrItineraryData *II = TM->getInstrItineraryData();
64     return new ScoreboardHazardRecognizer(II, DAG);
65   }
66
67   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
68 }
69
70 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
71 /// to use for this target when scheduling the DAG.
72 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
73   const InstrItineraryData *II,
74   const ScheduleDAG *DAG) const {
75   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
76
77   if (Directive == PPC::DIR_PWR7)
78     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
79
80   // Most subtargets use a PPC970 recognizer.
81   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
82       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
83     assert(TM.getInstrInfo() && "No InstrInfo?");
84
85     return new PPCHazardRecognizer970(TM);
86   }
87
88   return new ScoreboardHazardRecognizer(II, DAG);
89 }
90
91
92 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
93                                     const MachineInstr *DefMI, unsigned DefIdx,
94                                     const MachineInstr *UseMI,
95                                     unsigned UseIdx) const {
96   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
97                                                    UseMI, UseIdx);
98
99   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
100   unsigned Reg = DefMO.getReg();
101
102   const TargetRegisterInfo *TRI = &getRegisterInfo();
103   bool IsRegCR;
104   if (TRI->isVirtualRegister(Reg)) {
105     const MachineRegisterInfo *MRI =
106       &DefMI->getParent()->getParent()->getRegInfo();
107     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
108               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
109   } else {
110     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
111               PPC::CRBITRCRegClass.contains(Reg);
112   }
113
114   if (UseMI->isBranch() && IsRegCR) {
115     if (Latency < 0)
116       Latency = getInstrLatency(ItinData, DefMI);
117
118     // On some cores, there is an additional delay between writing to a condition
119     // register, and using it from a branch.
120     unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
121     switch (Directive) {
122     default: break;
123     case PPC::DIR_7400:
124     case PPC::DIR_750:
125     case PPC::DIR_970:
126     case PPC::DIR_E5500:
127     case PPC::DIR_PWR4:
128     case PPC::DIR_PWR5:
129     case PPC::DIR_PWR5X:
130     case PPC::DIR_PWR6:
131     case PPC::DIR_PWR6X:
132     case PPC::DIR_PWR7:
133       Latency += 2;
134       break;
135     }
136   }
137
138   return Latency;
139 }
140
141 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
142 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
143                                          unsigned &SrcReg, unsigned &DstReg,
144                                          unsigned &SubIdx) const {
145   switch (MI.getOpcode()) {
146   default: return false;
147   case PPC::EXTSW:
148   case PPC::EXTSW_32_64:
149     SrcReg = MI.getOperand(1).getReg();
150     DstReg = MI.getOperand(0).getReg();
151     SubIdx = PPC::sub_32;
152     return true;
153   }
154 }
155
156 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
157                                            int &FrameIndex) const {
158   // Note: This list must be kept consistent with LoadRegFromStackSlot.
159   switch (MI->getOpcode()) {
160   default: break;
161   case PPC::LD:
162   case PPC::LWZ:
163   case PPC::LFS:
164   case PPC::LFD:
165   case PPC::RESTORE_CR:
166   case PPC::RESTORE_CRBIT:
167   case PPC::LVX:
168   case PPC::RESTORE_VRSAVE:
169     // Check for the operands added by addFrameReference (the immediate is the
170     // offset which defaults to 0).
171     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
172         MI->getOperand(2).isFI()) {
173       FrameIndex = MI->getOperand(2).getIndex();
174       return MI->getOperand(0).getReg();
175     }
176     break;
177   }
178   return 0;
179 }
180
181 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
182                                           int &FrameIndex) const {
183   // Note: This list must be kept consistent with StoreRegToStackSlot.
184   switch (MI->getOpcode()) {
185   default: break;
186   case PPC::STD:
187   case PPC::STW:
188   case PPC::STFS:
189   case PPC::STFD:
190   case PPC::SPILL_CR:
191   case PPC::SPILL_CRBIT:
192   case PPC::STVX:
193   case PPC::SPILL_VRSAVE:
194     // Check for the operands added by addFrameReference (the immediate is the
195     // offset which defaults to 0).
196     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
197         MI->getOperand(2).isFI()) {
198       FrameIndex = MI->getOperand(2).getIndex();
199       return MI->getOperand(0).getReg();
200     }
201     break;
202   }
203   return 0;
204 }
205
206 // commuteInstruction - We can commute rlwimi instructions, but only if the
207 // rotate amt is zero.  We also have to munge the immediates a bit.
208 MachineInstr *
209 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
210   MachineFunction &MF = *MI->getParent()->getParent();
211
212   // Normal instructions can be commuted the obvious way.
213   if (MI->getOpcode() != PPC::RLWIMI &&
214       MI->getOpcode() != PPC::RLWIMIo &&
215       MI->getOpcode() != PPC::RLWIMI8 &&
216       MI->getOpcode() != PPC::RLWIMI8o)
217     return TargetInstrInfo::commuteInstruction(MI, NewMI);
218
219   // Cannot commute if it has a non-zero rotate count.
220   if (MI->getOperand(3).getImm() != 0)
221     return 0;
222
223   // If we have a zero rotate count, we have:
224   //   M = mask(MB,ME)
225   //   Op0 = (Op1 & ~M) | (Op2 & M)
226   // Change this to:
227   //   M = mask((ME+1)&31, (MB-1)&31)
228   //   Op0 = (Op2 & ~M) | (Op1 & M)
229
230   // Swap op1/op2
231   unsigned Reg0 = MI->getOperand(0).getReg();
232   unsigned Reg1 = MI->getOperand(1).getReg();
233   unsigned Reg2 = MI->getOperand(2).getReg();
234   unsigned SubReg1 = MI->getOperand(1).getSubReg();
235   unsigned SubReg2 = MI->getOperand(2).getSubReg();
236   bool Reg1IsKill = MI->getOperand(1).isKill();
237   bool Reg2IsKill = MI->getOperand(2).isKill();
238   bool ChangeReg0 = false;
239   // If machine instrs are no longer in two-address forms, update
240   // destination register as well.
241   if (Reg0 == Reg1) {
242     // Must be two address instruction!
243     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
244            "Expecting a two-address instruction!");
245     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
246     Reg2IsKill = false;
247     ChangeReg0 = true;
248   }
249
250   // Masks.
251   unsigned MB = MI->getOperand(4).getImm();
252   unsigned ME = MI->getOperand(5).getImm();
253
254   if (NewMI) {
255     // Create a new instruction.
256     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
257     bool Reg0IsDead = MI->getOperand(0).isDead();
258     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
259       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
260       .addReg(Reg2, getKillRegState(Reg2IsKill))
261       .addReg(Reg1, getKillRegState(Reg1IsKill))
262       .addImm((ME+1) & 31)
263       .addImm((MB-1) & 31);
264   }
265
266   if (ChangeReg0) {
267     MI->getOperand(0).setReg(Reg2);
268     MI->getOperand(0).setSubReg(SubReg2);
269   }
270   MI->getOperand(2).setReg(Reg1);
271   MI->getOperand(1).setReg(Reg2);
272   MI->getOperand(2).setSubReg(SubReg1);
273   MI->getOperand(1).setSubReg(SubReg2);
274   MI->getOperand(2).setIsKill(Reg1IsKill);
275   MI->getOperand(1).setIsKill(Reg2IsKill);
276
277   // Swap the mask around.
278   MI->getOperand(4).setImm((ME+1) & 31);
279   MI->getOperand(5).setImm((MB-1) & 31);
280   return MI;
281 }
282
283 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
284                               MachineBasicBlock::iterator MI) const {
285   // This function is used for scheduling, and the nop wanted here is the type
286   // that terminates dispatch groups on the POWER cores.
287   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
288   unsigned Opcode;
289   switch (Directive) {
290   default:            Opcode = PPC::NOP; break;
291   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
292   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
293   }
294
295   DebugLoc DL;
296   BuildMI(MBB, MI, DL, get(Opcode));
297 }
298
299 // Branch analysis.
300 // Note: If the condition register is set to CTR or CTR8 then this is a
301 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
302 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
303                                  MachineBasicBlock *&FBB,
304                                  SmallVectorImpl<MachineOperand> &Cond,
305                                  bool AllowModify) const {
306   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
307
308   // If the block has no terminators, it just falls into the block after it.
309   MachineBasicBlock::iterator I = MBB.end();
310   if (I == MBB.begin())
311     return false;
312   --I;
313   while (I->isDebugValue()) {
314     if (I == MBB.begin())
315       return false;
316     --I;
317   }
318   if (!isUnpredicatedTerminator(I))
319     return false;
320
321   // Get the last instruction in the block.
322   MachineInstr *LastInst = I;
323
324   // If there is only one terminator instruction, process it.
325   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
326     if (LastInst->getOpcode() == PPC::B) {
327       if (!LastInst->getOperand(0).isMBB())
328         return true;
329       TBB = LastInst->getOperand(0).getMBB();
330       return false;
331     } else if (LastInst->getOpcode() == PPC::BCC) {
332       if (!LastInst->getOperand(2).isMBB())
333         return true;
334       // Block ends with fall-through condbranch.
335       TBB = LastInst->getOperand(2).getMBB();
336       Cond.push_back(LastInst->getOperand(0));
337       Cond.push_back(LastInst->getOperand(1));
338       return false;
339     } else if (LastInst->getOpcode() == PPC::BC) {
340       if (!LastInst->getOperand(1).isMBB())
341         return true;
342       // Block ends with fall-through condbranch.
343       TBB = LastInst->getOperand(1).getMBB();
344       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
345       Cond.push_back(LastInst->getOperand(0));
346       return false;
347     } else if (LastInst->getOpcode() == PPC::BCn) {
348       if (!LastInst->getOperand(1).isMBB())
349         return true;
350       // Block ends with fall-through condbranch.
351       TBB = LastInst->getOperand(1).getMBB();
352       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
353       Cond.push_back(LastInst->getOperand(0));
354       return false;
355     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
356                LastInst->getOpcode() == PPC::BDNZ) {
357       if (!LastInst->getOperand(0).isMBB())
358         return true;
359       if (DisableCTRLoopAnal)
360         return true;
361       TBB = LastInst->getOperand(0).getMBB();
362       Cond.push_back(MachineOperand::CreateImm(1));
363       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
364                                                true));
365       return false;
366     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
367                LastInst->getOpcode() == PPC::BDZ) {
368       if (!LastInst->getOperand(0).isMBB())
369         return true;
370       if (DisableCTRLoopAnal)
371         return true;
372       TBB = LastInst->getOperand(0).getMBB();
373       Cond.push_back(MachineOperand::CreateImm(0));
374       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
375                                                true));
376       return false;
377     }
378
379     // Otherwise, don't know what this is.
380     return true;
381   }
382
383   // Get the instruction before it if it's a terminator.
384   MachineInstr *SecondLastInst = I;
385
386   // If there are three terminators, we don't know what sort of block this is.
387   if (SecondLastInst && I != MBB.begin() &&
388       isUnpredicatedTerminator(--I))
389     return true;
390
391   // If the block ends with PPC::B and PPC:BCC, handle it.
392   if (SecondLastInst->getOpcode() == PPC::BCC &&
393       LastInst->getOpcode() == PPC::B) {
394     if (!SecondLastInst->getOperand(2).isMBB() ||
395         !LastInst->getOperand(0).isMBB())
396       return true;
397     TBB =  SecondLastInst->getOperand(2).getMBB();
398     Cond.push_back(SecondLastInst->getOperand(0));
399     Cond.push_back(SecondLastInst->getOperand(1));
400     FBB = LastInst->getOperand(0).getMBB();
401     return false;
402   } else if (SecondLastInst->getOpcode() == PPC::BC &&
403       LastInst->getOpcode() == PPC::B) {
404     if (!SecondLastInst->getOperand(1).isMBB() ||
405         !LastInst->getOperand(0).isMBB())
406       return true;
407     TBB =  SecondLastInst->getOperand(1).getMBB();
408     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
409     Cond.push_back(SecondLastInst->getOperand(0));
410     FBB = LastInst->getOperand(0).getMBB();
411     return false;
412   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
413       LastInst->getOpcode() == PPC::B) {
414     if (!SecondLastInst->getOperand(1).isMBB() ||
415         !LastInst->getOperand(0).isMBB())
416       return true;
417     TBB =  SecondLastInst->getOperand(1).getMBB();
418     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
419     Cond.push_back(SecondLastInst->getOperand(0));
420     FBB = LastInst->getOperand(0).getMBB();
421     return false;
422   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
423               SecondLastInst->getOpcode() == PPC::BDNZ) &&
424       LastInst->getOpcode() == PPC::B) {
425     if (!SecondLastInst->getOperand(0).isMBB() ||
426         !LastInst->getOperand(0).isMBB())
427       return true;
428     if (DisableCTRLoopAnal)
429       return true;
430     TBB = SecondLastInst->getOperand(0).getMBB();
431     Cond.push_back(MachineOperand::CreateImm(1));
432     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
433                                              true));
434     FBB = LastInst->getOperand(0).getMBB();
435     return false;
436   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
437               SecondLastInst->getOpcode() == PPC::BDZ) &&
438       LastInst->getOpcode() == PPC::B) {
439     if (!SecondLastInst->getOperand(0).isMBB() ||
440         !LastInst->getOperand(0).isMBB())
441       return true;
442     if (DisableCTRLoopAnal)
443       return true;
444     TBB = SecondLastInst->getOperand(0).getMBB();
445     Cond.push_back(MachineOperand::CreateImm(0));
446     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
447                                              true));
448     FBB = LastInst->getOperand(0).getMBB();
449     return false;
450   }
451
452   // If the block ends with two PPC:Bs, handle it.  The second one is not
453   // executed, so remove it.
454   if (SecondLastInst->getOpcode() == PPC::B &&
455       LastInst->getOpcode() == PPC::B) {
456     if (!SecondLastInst->getOperand(0).isMBB())
457       return true;
458     TBB = SecondLastInst->getOperand(0).getMBB();
459     I = LastInst;
460     if (AllowModify)
461       I->eraseFromParent();
462     return false;
463   }
464
465   // Otherwise, can't handle this.
466   return true;
467 }
468
469 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
470   MachineBasicBlock::iterator I = MBB.end();
471   if (I == MBB.begin()) return 0;
472   --I;
473   while (I->isDebugValue()) {
474     if (I == MBB.begin())
475       return 0;
476     --I;
477   }
478   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
479       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
480       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
481       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
482     return 0;
483
484   // Remove the branch.
485   I->eraseFromParent();
486
487   I = MBB.end();
488
489   if (I == MBB.begin()) return 1;
490   --I;
491   if (I->getOpcode() != PPC::BCC &&
492       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
493       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
494       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
495     return 1;
496
497   // Remove the branch.
498   I->eraseFromParent();
499   return 2;
500 }
501
502 unsigned
503 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
504                            MachineBasicBlock *FBB,
505                            const SmallVectorImpl<MachineOperand> &Cond,
506                            DebugLoc DL) const {
507   // Shouldn't be a fall through.
508   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
509   assert((Cond.size() == 2 || Cond.size() == 0) &&
510          "PPC branch conditions have two components!");
511
512   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
513
514   // One-way branch.
515   if (FBB == 0) {
516     if (Cond.empty())   // Unconditional branch
517       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
518     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
519       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
520                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
521                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
522     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
523       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
524     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
525       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
526     else                // Conditional branch
527       BuildMI(&MBB, DL, get(PPC::BCC))
528         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
529     return 1;
530   }
531
532   // Two-way Conditional Branch.
533   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
534     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
535                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
536                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
537   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
538     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
539   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
540     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
541   else
542     BuildMI(&MBB, DL, get(PPC::BCC))
543       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
544   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
545   return 2;
546 }
547
548 // Select analysis.
549 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
550                 const SmallVectorImpl<MachineOperand> &Cond,
551                 unsigned TrueReg, unsigned FalseReg,
552                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
553   if (!TM.getSubtargetImpl()->hasISEL())
554     return false;
555
556   if (Cond.size() != 2)
557     return false;
558
559   // If this is really a bdnz-like condition, then it cannot be turned into a
560   // select.
561   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
562     return false;
563
564   // Check register classes.
565   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
566   const TargetRegisterClass *RC =
567     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
568   if (!RC)
569     return false;
570
571   // isel is for regular integer GPRs only.
572   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
573       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
574       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
575       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
576     return false;
577
578   // FIXME: These numbers are for the A2, how well they work for other cores is
579   // an open question. On the A2, the isel instruction has a 2-cycle latency
580   // but single-cycle throughput. These numbers are used in combination with
581   // the MispredictPenalty setting from the active SchedMachineModel.
582   CondCycles = 1;
583   TrueCycles = 1;
584   FalseCycles = 1;
585
586   return true;
587 }
588
589 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
590                                 MachineBasicBlock::iterator MI, DebugLoc dl,
591                                 unsigned DestReg,
592                                 const SmallVectorImpl<MachineOperand> &Cond,
593                                 unsigned TrueReg, unsigned FalseReg) const {
594   assert(Cond.size() == 2 &&
595          "PPC branch conditions have two components!");
596
597   assert(TM.getSubtargetImpl()->hasISEL() &&
598          "Cannot insert select on target without ISEL support");
599
600   // Get the register classes.
601   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
602   const TargetRegisterClass *RC =
603     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
604   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
605
606   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
607                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
608   assert((Is64Bit ||
609           PPC::GPRCRegClass.hasSubClassEq(RC) ||
610           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
611          "isel is for regular integer GPRs only");
612
613   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
614   unsigned SelectPred = Cond[0].getImm();
615
616   unsigned SubIdx;
617   bool SwapOps;
618   switch (SelectPred) {
619   default: llvm_unreachable("invalid predicate for isel");
620   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
621   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
622   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
623   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
624   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
625   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
626   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
627   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
628   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
629   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
630   }
631
632   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
633            SecondReg = SwapOps ? TrueReg  : FalseReg;
634
635   // The first input register of isel cannot be r0. If it is a member
636   // of a register class that can be r0, then copy it first (the
637   // register allocator should eliminate the copy).
638   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
639       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
640     const TargetRegisterClass *FirstRC =
641       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
642         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
643     unsigned OldFirstReg = FirstReg;
644     FirstReg = MRI.createVirtualRegister(FirstRC);
645     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
646       .addReg(OldFirstReg);
647   }
648
649   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
650     .addReg(FirstReg).addReg(SecondReg)
651     .addReg(Cond[1].getReg(), 0, SubIdx);
652 }
653
654 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
655                                MachineBasicBlock::iterator I, DebugLoc DL,
656                                unsigned DestReg, unsigned SrcReg,
657                                bool KillSrc) const {
658   unsigned Opc;
659   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
660     Opc = PPC::OR;
661   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
662     Opc = PPC::OR8;
663   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
664     Opc = PPC::FMR;
665   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
666     Opc = PPC::MCRF;
667   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
668     Opc = PPC::VOR;
669   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
670     Opc = PPC::CROR;
671   else
672     llvm_unreachable("Impossible reg-to-reg copy");
673
674   const MCInstrDesc &MCID = get(Opc);
675   if (MCID.getNumOperands() == 3)
676     BuildMI(MBB, I, DL, MCID, DestReg)
677       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
678   else
679     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
680 }
681
682 // This function returns true if a CR spill is necessary and false otherwise.
683 bool
684 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
685                                   unsigned SrcReg, bool isKill,
686                                   int FrameIdx,
687                                   const TargetRegisterClass *RC,
688                                   SmallVectorImpl<MachineInstr*> &NewMIs,
689                                   bool &NonRI, bool &SpillsVRS) const{
690   // Note: If additional store instructions are added here,
691   // update isStoreToStackSlot.
692
693   DebugLoc DL;
694   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
695       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
696     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
697                                        .addReg(SrcReg,
698                                                getKillRegState(isKill)),
699                                        FrameIdx));
700   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
701              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
702     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
703                                        .addReg(SrcReg,
704                                                getKillRegState(isKill)),
705                                        FrameIdx));
706   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
707     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
708                                        .addReg(SrcReg,
709                                                getKillRegState(isKill)),
710                                        FrameIdx));
711   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
712     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
713                                        .addReg(SrcReg,
714                                                getKillRegState(isKill)),
715                                        FrameIdx));
716   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
717     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
718                                        .addReg(SrcReg,
719                                                getKillRegState(isKill)),
720                                        FrameIdx));
721     return true;
722   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
723     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
724                                        .addReg(SrcReg,
725                                                getKillRegState(isKill)),
726                                        FrameIdx));
727     return true;
728   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
729     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
730                                        .addReg(SrcReg,
731                                                getKillRegState(isKill)),
732                                        FrameIdx));
733     NonRI = true;
734   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
735     assert(TM.getSubtargetImpl()->isDarwin() &&
736            "VRSAVE only needs spill/restore on Darwin");
737     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
738                                        .addReg(SrcReg,
739                                                getKillRegState(isKill)),
740                                        FrameIdx));
741     SpillsVRS = true;
742   } else {
743     llvm_unreachable("Unknown regclass!");
744   }
745
746   return false;
747 }
748
749 void
750 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
751                                   MachineBasicBlock::iterator MI,
752                                   unsigned SrcReg, bool isKill, int FrameIdx,
753                                   const TargetRegisterClass *RC,
754                                   const TargetRegisterInfo *TRI) const {
755   MachineFunction &MF = *MBB.getParent();
756   SmallVector<MachineInstr*, 4> NewMIs;
757
758   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
759   FuncInfo->setHasSpills();
760
761   bool NonRI = false, SpillsVRS = false;
762   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
763                           NonRI, SpillsVRS))
764     FuncInfo->setSpillsCR();
765
766   if (SpillsVRS)
767     FuncInfo->setSpillsVRSAVE();
768
769   if (NonRI)
770     FuncInfo->setHasNonRISpills();
771
772   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
773     MBB.insert(MI, NewMIs[i]);
774
775   const MachineFrameInfo &MFI = *MF.getFrameInfo();
776   MachineMemOperand *MMO =
777     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
778                             MachineMemOperand::MOStore,
779                             MFI.getObjectSize(FrameIdx),
780                             MFI.getObjectAlignment(FrameIdx));
781   NewMIs.back()->addMemOperand(MF, MMO);
782 }
783
784 bool
785 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
786                                    unsigned DestReg, int FrameIdx,
787                                    const TargetRegisterClass *RC,
788                                    SmallVectorImpl<MachineInstr*> &NewMIs,
789                                    bool &NonRI, bool &SpillsVRS) const{
790   // Note: If additional load instructions are added here,
791   // update isLoadFromStackSlot.
792
793   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
794       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
795     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
796                                                DestReg), FrameIdx));
797   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
798              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
799     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
800                                        FrameIdx));
801   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
802     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
803                                        FrameIdx));
804   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
805     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
806                                        FrameIdx));
807   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
808     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
809                                                get(PPC::RESTORE_CR), DestReg),
810                                        FrameIdx));
811     return true;
812   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
813     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
814                                                get(PPC::RESTORE_CRBIT), DestReg),
815                                        FrameIdx));
816     return true;
817   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
818     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
819                                        FrameIdx));
820     NonRI = true;
821   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
822     assert(TM.getSubtargetImpl()->isDarwin() &&
823            "VRSAVE only needs spill/restore on Darwin");
824     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
825                                                get(PPC::RESTORE_VRSAVE),
826                                                DestReg),
827                                        FrameIdx));
828     SpillsVRS = true;
829   } else {
830     llvm_unreachable("Unknown regclass!");
831   }
832
833   return false;
834 }
835
836 void
837 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
838                                    MachineBasicBlock::iterator MI,
839                                    unsigned DestReg, int FrameIdx,
840                                    const TargetRegisterClass *RC,
841                                    const TargetRegisterInfo *TRI) const {
842   MachineFunction &MF = *MBB.getParent();
843   SmallVector<MachineInstr*, 4> NewMIs;
844   DebugLoc DL;
845   if (MI != MBB.end()) DL = MI->getDebugLoc();
846
847   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
848   FuncInfo->setHasSpills();
849
850   bool NonRI = false, SpillsVRS = false;
851   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
852                            NonRI, SpillsVRS))
853     FuncInfo->setSpillsCR();
854
855   if (SpillsVRS)
856     FuncInfo->setSpillsVRSAVE();
857
858   if (NonRI)
859     FuncInfo->setHasNonRISpills();
860
861   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
862     MBB.insert(MI, NewMIs[i]);
863
864   const MachineFrameInfo &MFI = *MF.getFrameInfo();
865   MachineMemOperand *MMO =
866     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
867                             MachineMemOperand::MOLoad,
868                             MFI.getObjectSize(FrameIdx),
869                             MFI.getObjectAlignment(FrameIdx));
870   NewMIs.back()->addMemOperand(MF, MMO);
871 }
872
873 bool PPCInstrInfo::
874 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
875   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
876   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
877     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
878   else
879     // Leave the CR# the same, but invert the condition.
880     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
881   return false;
882 }
883
884 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
885                              unsigned Reg, MachineRegisterInfo *MRI) const {
886   // For some instructions, it is legal to fold ZERO into the RA register field.
887   // A zero immediate should always be loaded with a single li.
888   unsigned DefOpc = DefMI->getOpcode();
889   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
890     return false;
891   if (!DefMI->getOperand(1).isImm())
892     return false;
893   if (DefMI->getOperand(1).getImm() != 0)
894     return false;
895
896   // Note that we cannot here invert the arguments of an isel in order to fold
897   // a ZERO into what is presented as the second argument. All we have here
898   // is the condition bit, and that might come from a CR-logical bit operation.
899
900   const MCInstrDesc &UseMCID = UseMI->getDesc();
901
902   // Only fold into real machine instructions.
903   if (UseMCID.isPseudo())
904     return false;
905
906   unsigned UseIdx;
907   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
908     if (UseMI->getOperand(UseIdx).isReg() &&
909         UseMI->getOperand(UseIdx).getReg() == Reg)
910       break;
911
912   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
913   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
914
915   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
916
917   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
918   // register (which might also be specified as a pointer class kind).
919   if (UseInfo->isLookupPtrRegClass()) {
920     if (UseInfo->RegClass /* Kind */ != 1)
921       return false;
922   } else {
923     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
924         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
925       return false;
926   }
927
928   // Make sure this is not tied to an output register (or otherwise
929   // constrained). This is true for ST?UX registers, for example, which
930   // are tied to their output registers.
931   if (UseInfo->Constraints != 0)
932     return false;
933
934   unsigned ZeroReg;
935   if (UseInfo->isLookupPtrRegClass()) {
936     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
937     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
938   } else {
939     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
940               PPC::ZERO8 : PPC::ZERO;
941   }
942
943   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
944   UseMI->getOperand(UseIdx).setReg(ZeroReg);
945
946   if (DeleteDef)
947     DefMI->eraseFromParent();
948
949   return true;
950 }
951
952 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
953   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
954        I != IE; ++I)
955     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
956       return true;
957   return false;
958 }
959
960 // We should make sure that, if we're going to predicate both sides of a
961 // condition (a diamond), that both sides don't define the counter register. We
962 // can predicate counter-decrement-based branches, but while that predicates
963 // the branching, it does not predicate the counter decrement. If we tried to
964 // merge the triangle into one predicated block, we'd decrement the counter
965 // twice.
966 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
967                      unsigned NumT, unsigned ExtraT,
968                      MachineBasicBlock &FMBB,
969                      unsigned NumF, unsigned ExtraF,
970                      const BranchProbability &Probability) const {
971   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
972 }
973
974
975 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
976   // The predicated branches are identified by their type, not really by the
977   // explicit presence of a predicate. Furthermore, some of them can be
978   // predicated more than once. Because if conversion won't try to predicate
979   // any instruction which already claims to be predicated (by returning true
980   // here), always return false. In doing so, we let isPredicable() be the
981   // final word on whether not the instruction can be (further) predicated.
982
983   return false;
984 }
985
986 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
987   if (!MI->isTerminator())
988     return false;
989
990   // Conditional branch is a special case.
991   if (MI->isBranch() && !MI->isBarrier())
992     return true;
993
994   return !isPredicated(MI);
995 }
996
997 bool PPCInstrInfo::PredicateInstruction(
998                      MachineInstr *MI,
999                      const SmallVectorImpl<MachineOperand> &Pred) const {
1000   unsigned OpC = MI->getOpcode();
1001   if (OpC == PPC::BLR) {
1002     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1003       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1004       MI->setDesc(get(Pred[0].getImm() ?
1005                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1006                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
1007     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1008       MI->setDesc(get(PPC::BCLR));
1009       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1010         .addReg(Pred[1].getReg());
1011     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1012       MI->setDesc(get(PPC::BCLRn));
1013       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1014         .addReg(Pred[1].getReg());
1015     } else {
1016       MI->setDesc(get(PPC::BCCLR));
1017       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1018         .addImm(Pred[0].getImm())
1019         .addReg(Pred[1].getReg());
1020     }
1021
1022     return true;
1023   } else if (OpC == PPC::B) {
1024     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1025       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1026       MI->setDesc(get(Pred[0].getImm() ?
1027                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1028                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
1029     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1030       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1031       MI->RemoveOperand(0);
1032
1033       MI->setDesc(get(PPC::BC));
1034       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1035         .addReg(Pred[1].getReg())
1036         .addMBB(MBB);
1037     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1038       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1039       MI->RemoveOperand(0);
1040
1041       MI->setDesc(get(PPC::BCn));
1042       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1043         .addReg(Pred[1].getReg())
1044         .addMBB(MBB);
1045     } else {
1046       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1047       MI->RemoveOperand(0);
1048
1049       MI->setDesc(get(PPC::BCC));
1050       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1051         .addImm(Pred[0].getImm())
1052         .addReg(Pred[1].getReg())
1053         .addMBB(MBB);
1054     }
1055
1056     return true;
1057   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1058              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1059     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1060       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1061
1062     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1063     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1064
1065     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1066       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1067                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
1068       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1069         .addReg(Pred[1].getReg());
1070       return true;
1071     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1072       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1073                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
1074       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1075         .addReg(Pred[1].getReg());
1076       return true;
1077     }
1078
1079     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1080                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
1081     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1082       .addImm(Pred[0].getImm())
1083       .addReg(Pred[1].getReg());
1084     return true;
1085   }
1086
1087   return false;
1088 }
1089
1090 bool PPCInstrInfo::SubsumesPredicate(
1091                      const SmallVectorImpl<MachineOperand> &Pred1,
1092                      const SmallVectorImpl<MachineOperand> &Pred2) const {
1093   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1094   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1095
1096   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1097     return false;
1098   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1099     return false;
1100
1101   // P1 can only subsume P2 if they test the same condition register.
1102   if (Pred1[1].getReg() != Pred2[1].getReg())
1103     return false;
1104
1105   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1106   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1107
1108   if (P1 == P2)
1109     return true;
1110
1111   // Does P1 subsume P2, e.g. GE subsumes GT.
1112   if (P1 == PPC::PRED_LE &&
1113       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1114     return true;
1115   if (P1 == PPC::PRED_GE &&
1116       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1117     return true;
1118
1119   return false;
1120 }
1121
1122 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1123                                     std::vector<MachineOperand> &Pred) const {
1124   // Note: At the present time, the contents of Pred from this function is
1125   // unused by IfConversion. This implementation follows ARM by pushing the
1126   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1127   // predicate, instructions defining CTR or CTR8 are also included as
1128   // predicate-defining instructions.
1129
1130   const TargetRegisterClass *RCs[] =
1131     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1132       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1133
1134   bool Found = false;
1135   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1136     const MachineOperand &MO = MI->getOperand(i);
1137     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1138       const TargetRegisterClass *RC = RCs[c];
1139       if (MO.isReg()) {
1140         if (MO.isDef() && RC->contains(MO.getReg())) {
1141           Pred.push_back(MO);
1142           Found = true;
1143         }
1144       } else if (MO.isRegMask()) {
1145         for (TargetRegisterClass::iterator I = RC->begin(),
1146              IE = RC->end(); I != IE; ++I)
1147           if (MO.clobbersPhysReg(*I)) {
1148             Pred.push_back(MO);
1149             Found = true;
1150           }
1151       }
1152     }
1153   }
1154
1155   return Found;
1156 }
1157
1158 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1159   unsigned OpC = MI->getOpcode();
1160   switch (OpC) {
1161   default:
1162     return false;
1163   case PPC::B:
1164   case PPC::BLR:
1165   case PPC::BCTR:
1166   case PPC::BCTR8:
1167   case PPC::BCTRL:
1168   case PPC::BCTRL8:
1169     return true;
1170   }
1171 }
1172
1173 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1174                                   unsigned &SrcReg, unsigned &SrcReg2,
1175                                   int &Mask, int &Value) const {
1176   unsigned Opc = MI->getOpcode();
1177
1178   switch (Opc) {
1179   default: return false;
1180   case PPC::CMPWI:
1181   case PPC::CMPLWI:
1182   case PPC::CMPDI:
1183   case PPC::CMPLDI:
1184     SrcReg = MI->getOperand(1).getReg();
1185     SrcReg2 = 0;
1186     Value = MI->getOperand(2).getImm();
1187     Mask = 0xFFFF;
1188     return true;
1189   case PPC::CMPW:
1190   case PPC::CMPLW:
1191   case PPC::CMPD:
1192   case PPC::CMPLD:
1193   case PPC::FCMPUS:
1194   case PPC::FCMPUD:
1195     SrcReg = MI->getOperand(1).getReg();
1196     SrcReg2 = MI->getOperand(2).getReg();
1197     return true;
1198   }
1199 }
1200
1201 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1202                                         unsigned SrcReg, unsigned SrcReg2,
1203                                         int Mask, int Value,
1204                                         const MachineRegisterInfo *MRI) const {
1205   if (DisableCmpOpt)
1206     return false;
1207
1208   int OpC = CmpInstr->getOpcode();
1209   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1210
1211   // FP record forms set CR1 based on the execption status bits, not a
1212   // comparison with zero.
1213   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1214     return false;
1215
1216   // The record forms set the condition register based on a signed comparison
1217   // with zero (so says the ISA manual). This is not as straightforward as it
1218   // seems, however, because this is always a 64-bit comparison on PPC64, even
1219   // for instructions that are 32-bit in nature (like slw for example).
1220   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1221   // for equality checks (as those don't depend on the sign). On PPC64,
1222   // we are restricted to equality for unsigned 64-bit comparisons and for
1223   // signed 32-bit comparisons the applicability is more restricted.
1224   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1225   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1226   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1227   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1228
1229   // Get the unique definition of SrcReg.
1230   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1231   if (!MI) return false;
1232   int MIOpC = MI->getOpcode();
1233
1234   bool equalityOnly = false;
1235   bool noSub = false;
1236   if (isPPC64) {
1237     if (is32BitSignedCompare) {
1238       // We can perform this optimization only if MI is sign-extending.
1239       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1240           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1241           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1242           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1243           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1244         noSub = true;
1245       } else
1246         return false;
1247     } else if (is32BitUnsignedCompare) {
1248       // We can perform this optimization, equality only, if MI is
1249       // zero-extending.
1250       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1251           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1252           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1253         noSub = true;
1254         equalityOnly = true;
1255       } else
1256         return false;
1257     } else
1258       equalityOnly = is64BitUnsignedCompare;
1259   } else
1260     equalityOnly = is32BitUnsignedCompare;
1261
1262   if (equalityOnly) {
1263     // We need to check the uses of the condition register in order to reject
1264     // non-equality comparisons.
1265     for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1266          IE = MRI->use_end(); I != IE; ++I) {
1267       MachineInstr *UseMI = &*I;
1268       if (UseMI->getOpcode() == PPC::BCC) {
1269         unsigned Pred = UseMI->getOperand(0).getImm();
1270         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1271           return false;
1272       } else if (UseMI->getOpcode() == PPC::ISEL ||
1273                  UseMI->getOpcode() == PPC::ISEL8) {
1274         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1275         if (SubIdx != PPC::sub_eq)
1276           return false;
1277       } else
1278         return false;
1279     }
1280   }
1281
1282   MachineBasicBlock::iterator I = CmpInstr;
1283
1284   // Scan forward to find the first use of the compare.
1285   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1286        I != EL; ++I) {
1287     bool FoundUse = false;
1288     for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1289          JE = MRI->use_end(); J != JE; ++J)
1290       if (&*J == &*I) {
1291         FoundUse = true;
1292         break;
1293       }
1294
1295     if (FoundUse)
1296       break;
1297   }
1298
1299   // There are two possible candidates which can be changed to set CR[01].
1300   // One is MI, the other is a SUB instruction.
1301   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1302   MachineInstr *Sub = NULL;
1303   if (SrcReg2 != 0)
1304     // MI is not a candidate for CMPrr.
1305     MI = NULL;
1306   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1307   // same BB as the comparison. This is to allow the check below to avoid calls
1308   // (and other explicit clobbers); instead we should really check for these
1309   // more explicitly (in at least a few predecessors).
1310   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1311     // PPC does not have a record-form SUBri.
1312     return false;
1313   }
1314
1315   // Search for Sub.
1316   const TargetRegisterInfo *TRI = &getRegisterInfo();
1317   --I;
1318
1319   // Get ready to iterate backward from CmpInstr.
1320   MachineBasicBlock::iterator E = MI,
1321                               B = CmpInstr->getParent()->begin();
1322
1323   for (; I != E && !noSub; --I) {
1324     const MachineInstr &Instr = *I;
1325     unsigned IOpC = Instr.getOpcode();
1326
1327     if (&*I != CmpInstr && (
1328         Instr.modifiesRegister(PPC::CR0, TRI) ||
1329         Instr.readsRegister(PPC::CR0, TRI)))
1330       // This instruction modifies or uses the record condition register after
1331       // the one we want to change. While we could do this transformation, it
1332       // would likely not be profitable. This transformation removes one
1333       // instruction, and so even forcing RA to generate one move probably
1334       // makes it unprofitable.
1335       return false;
1336
1337     // Check whether CmpInstr can be made redundant by the current instruction.
1338     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1339          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1340         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1341         ((Instr.getOperand(1).getReg() == SrcReg &&
1342           Instr.getOperand(2).getReg() == SrcReg2) ||
1343         (Instr.getOperand(1).getReg() == SrcReg2 &&
1344          Instr.getOperand(2).getReg() == SrcReg))) {
1345       Sub = &*I;
1346       break;
1347     }
1348
1349     if (I == B)
1350       // The 'and' is below the comparison instruction.
1351       return false;
1352   }
1353
1354   // Return false if no candidates exist.
1355   if (!MI && !Sub)
1356     return false;
1357
1358   // The single candidate is called MI.
1359   if (!MI) MI = Sub;
1360
1361   int NewOpC = -1;
1362   MIOpC = MI->getOpcode();
1363   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1364     NewOpC = MIOpC;
1365   else {
1366     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1367     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1368       NewOpC = MIOpC;
1369   }
1370
1371   // FIXME: On the non-embedded POWER architectures, only some of the record
1372   // forms are fast, and we should use only the fast ones.
1373
1374   // The defining instruction has a record form (or is already a record
1375   // form). It is possible, however, that we'll need to reverse the condition
1376   // code of the users.
1377   if (NewOpC == -1)
1378     return false;
1379
1380   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1381   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1382
1383   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1384   // needs to be updated to be based on SUB.  Push the condition code
1385   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1386   // condition code of these operands will be modified.
1387   bool ShouldSwap = false;
1388   if (Sub) {
1389     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1390       Sub->getOperand(2).getReg() == SrcReg;
1391
1392     // The operands to subf are the opposite of sub, so only in the fixed-point
1393     // case, invert the order.
1394     ShouldSwap = !ShouldSwap;
1395   }
1396
1397   if (ShouldSwap)
1398     for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1399          IE = MRI->use_end(); I != IE; ++I) {
1400       MachineInstr *UseMI = &*I;
1401       if (UseMI->getOpcode() == PPC::BCC) {
1402         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1403         assert((!equalityOnly ||
1404                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1405                "Invalid predicate for equality-only optimization");
1406         PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1407                                 PPC::getSwappedPredicate(Pred)));
1408       } else if (UseMI->getOpcode() == PPC::ISEL ||
1409                  UseMI->getOpcode() == PPC::ISEL8) {
1410         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1411         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1412                "Invalid CR bit for equality-only optimization");
1413
1414         if (NewSubReg == PPC::sub_lt)
1415           NewSubReg = PPC::sub_gt;
1416         else if (NewSubReg == PPC::sub_gt)
1417           NewSubReg = PPC::sub_lt;
1418
1419         SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1420                                                  NewSubReg));
1421       } else // We need to abort on a user we don't understand.
1422         return false;
1423     }
1424
1425   // Create a new virtual register to hold the value of the CR set by the
1426   // record-form instruction. If the instruction was not previously in
1427   // record form, then set the kill flag on the CR.
1428   CmpInstr->eraseFromParent();
1429
1430   MachineBasicBlock::iterator MII = MI;
1431   BuildMI(*MI->getParent(), llvm::next(MII), MI->getDebugLoc(),
1432           get(TargetOpcode::COPY), CRReg)
1433     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1434
1435   if (MIOpC != NewOpC) {
1436     // We need to be careful here: we're replacing one instruction with
1437     // another, and we need to make sure that we get all of the right
1438     // implicit uses and defs. On the other hand, the caller may be holding
1439     // an iterator to this instruction, and so we can't delete it (this is
1440     // specifically the case if this is the instruction directly after the
1441     // compare).
1442
1443     const MCInstrDesc &NewDesc = get(NewOpC);
1444     MI->setDesc(NewDesc);
1445
1446     if (NewDesc.ImplicitDefs)
1447       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1448            *ImpDefs; ++ImpDefs)
1449         if (!MI->definesRegister(*ImpDefs))
1450           MI->addOperand(*MI->getParent()->getParent(),
1451                          MachineOperand::CreateReg(*ImpDefs, true, true));
1452     if (NewDesc.ImplicitUses)
1453       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1454            *ImpUses; ++ImpUses)
1455         if (!MI->readsRegister(*ImpUses))
1456           MI->addOperand(*MI->getParent()->getParent(),
1457                          MachineOperand::CreateReg(*ImpUses, false, true));
1458   }
1459
1460   // Modify the condition code of operands in OperandsToUpdate.
1461   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1462   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1463   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1464     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1465
1466   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1467     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1468
1469   return true;
1470 }
1471
1472 /// GetInstSize - Return the number of bytes of code the specified
1473 /// instruction may be.  This returns the maximum number of bytes.
1474 ///
1475 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1476   unsigned Opcode = MI->getOpcode();
1477
1478   if (Opcode == PPC::INLINEASM) {
1479     const MachineFunction *MF = MI->getParent()->getParent();
1480     const char *AsmStr = MI->getOperand(0).getSymbolName();
1481     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1482   } else {
1483     const MCInstrDesc &Desc = get(Opcode);
1484     return Desc.getSize();
1485   }
1486 }
1487
1488 #undef DEBUG_TYPE
1489 #define DEBUG_TYPE "ppc-early-ret"
1490 STATISTIC(NumBCLR, "Number of early conditional returns");
1491 STATISTIC(NumBLR,  "Number of early returns");
1492
1493 namespace llvm {
1494   void initializePPCEarlyReturnPass(PassRegistry&);
1495 }
1496
1497 namespace {
1498   // PPCEarlyReturn pass - For simple functions without epilogue code, move
1499   // returns up, and create conditional returns, to avoid unnecessary
1500   // branch-to-blr sequences.
1501   struct PPCEarlyReturn : public MachineFunctionPass {
1502     static char ID;
1503     PPCEarlyReturn() : MachineFunctionPass(ID) {
1504       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1505     }
1506
1507     const PPCTargetMachine *TM;
1508     const PPCInstrInfo *TII;
1509
1510 protected:
1511     bool processBlock(MachineBasicBlock &ReturnMBB) {
1512       bool Changed = false;
1513
1514       MachineBasicBlock::iterator I = ReturnMBB.begin();
1515       I = ReturnMBB.SkipPHIsAndLabels(I);
1516
1517       // The block must be essentially empty except for the blr.
1518       if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1519           I != ReturnMBB.getLastNonDebugInstr())
1520         return Changed;
1521
1522       SmallVector<MachineBasicBlock*, 8> PredToRemove;
1523       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1524            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1525         bool OtherReference = false, BlockChanged = false;
1526         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1527           if (J->getOpcode() == PPC::B) {
1528             if (J->getOperand(0).getMBB() == &ReturnMBB) {
1529               // This is an unconditional branch to the return. Replace the
1530               // branch with a blr.
1531               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1532               MachineBasicBlock::iterator K = J--;
1533               K->eraseFromParent();
1534               BlockChanged = true;
1535               ++NumBLR;
1536               continue;
1537             }
1538           } else if (J->getOpcode() == PPC::BCC) {
1539             if (J->getOperand(2).getMBB() == &ReturnMBB) {
1540               // This is a conditional branch to the return. Replace the branch
1541               // with a bclr.
1542               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
1543                 .addImm(J->getOperand(0).getImm())
1544                 .addReg(J->getOperand(1).getReg());
1545               MachineBasicBlock::iterator K = J--;
1546               K->eraseFromParent();
1547               BlockChanged = true;
1548               ++NumBCLR;
1549               continue;
1550             }
1551           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
1552             if (J->getOperand(1).getMBB() == &ReturnMBB) {
1553               // This is a conditional branch to the return. Replace the branch
1554               // with a bclr.
1555               BuildMI(**PI, J, J->getDebugLoc(),
1556                       TII->get(J->getOpcode() == PPC::BC ?
1557                                PPC::BCLR : PPC::BCLRn))
1558                 .addReg(J->getOperand(0).getReg());
1559               MachineBasicBlock::iterator K = J--;
1560               K->eraseFromParent();
1561               BlockChanged = true;
1562               ++NumBCLR;
1563               continue;
1564             }
1565           } else if (J->isBranch()) {
1566             if (J->isIndirectBranch()) {
1567               if (ReturnMBB.hasAddressTaken())
1568                 OtherReference = true;
1569             } else
1570               for (unsigned i = 0; i < J->getNumOperands(); ++i)
1571                 if (J->getOperand(i).isMBB() &&
1572                     J->getOperand(i).getMBB() == &ReturnMBB)
1573                   OtherReference = true;
1574           } else if (!J->isTerminator() && !J->isDebugValue())
1575             break;
1576
1577           if (J == (*PI)->begin())
1578             break;
1579
1580           --J;
1581         }
1582
1583         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1584           OtherReference = true;
1585
1586         // Predecessors are stored in a vector and can't be removed here.
1587         if (!OtherReference && BlockChanged) {
1588           PredToRemove.push_back(*PI);
1589         }
1590
1591         if (BlockChanged)
1592           Changed = true;
1593       }
1594
1595       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1596         PredToRemove[i]->removeSuccessor(&ReturnMBB);
1597
1598       if (Changed && !ReturnMBB.hasAddressTaken()) {
1599         // We now might be able to merge this blr-only block into its
1600         // by-layout predecessor.
1601         if (ReturnMBB.pred_size() == 1 &&
1602             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1603           // Move the blr into the preceding block.
1604           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1605           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1606           PrevMBB.removeSuccessor(&ReturnMBB);
1607         }
1608
1609         if (ReturnMBB.pred_empty())
1610           ReturnMBB.eraseFromParent();
1611       }
1612
1613       return Changed;
1614     }
1615
1616 public:
1617     virtual bool runOnMachineFunction(MachineFunction &MF) {
1618       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1619       TII = TM->getInstrInfo();
1620
1621       bool Changed = false;
1622
1623       // If the function does not have at least two blocks, then there is
1624       // nothing to do.
1625       if (MF.size() < 2)
1626         return Changed;
1627
1628       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1629         MachineBasicBlock &B = *I++;
1630         if (processBlock(B))
1631           Changed = true;
1632       }
1633
1634       return Changed;
1635     }
1636
1637     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1638       MachineFunctionPass::getAnalysisUsage(AU);
1639     }
1640   };
1641 }
1642
1643 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1644                 "PowerPC Early-Return Creation", false, false)
1645
1646 char PPCEarlyReturn::ID = 0;
1647 FunctionPass*
1648 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }