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