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