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