Revert "r225808 - [PowerPC] Add StackMap/PatchPoint support"
[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 || OpC == PPC::BLR8) {
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::BLR8:
1281   case PPC::BCTR:
1282   case PPC::BCTR8:
1283   case PPC::BCTRL:
1284   case PPC::BCTRL8:
1285     return true;
1286   }
1287 }
1288
1289 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1290                                   unsigned &SrcReg, unsigned &SrcReg2,
1291                                   int &Mask, int &Value) const {
1292   unsigned Opc = MI->getOpcode();
1293
1294   switch (Opc) {
1295   default: return false;
1296   case PPC::CMPWI:
1297   case PPC::CMPLWI:
1298   case PPC::CMPDI:
1299   case PPC::CMPLDI:
1300     SrcReg = MI->getOperand(1).getReg();
1301     SrcReg2 = 0;
1302     Value = MI->getOperand(2).getImm();
1303     Mask = 0xFFFF;
1304     return true;
1305   case PPC::CMPW:
1306   case PPC::CMPLW:
1307   case PPC::CMPD:
1308   case PPC::CMPLD:
1309   case PPC::FCMPUS:
1310   case PPC::FCMPUD:
1311     SrcReg = MI->getOperand(1).getReg();
1312     SrcReg2 = MI->getOperand(2).getReg();
1313     return true;
1314   }
1315 }
1316
1317 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1318                                         unsigned SrcReg, unsigned SrcReg2,
1319                                         int Mask, int Value,
1320                                         const MachineRegisterInfo *MRI) const {
1321   if (DisableCmpOpt)
1322     return false;
1323
1324   int OpC = CmpInstr->getOpcode();
1325   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1326
1327   // FP record forms set CR1 based on the execption status bits, not a
1328   // comparison with zero.
1329   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1330     return false;
1331
1332   // The record forms set the condition register based on a signed comparison
1333   // with zero (so says the ISA manual). This is not as straightforward as it
1334   // seems, however, because this is always a 64-bit comparison on PPC64, even
1335   // for instructions that are 32-bit in nature (like slw for example).
1336   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1337   // for equality checks (as those don't depend on the sign). On PPC64,
1338   // we are restricted to equality for unsigned 64-bit comparisons and for
1339   // signed 32-bit comparisons the applicability is more restricted.
1340   bool isPPC64 = Subtarget.isPPC64();
1341   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1342   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1343   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1344
1345   // Get the unique definition of SrcReg.
1346   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1347   if (!MI) return false;
1348   int MIOpC = MI->getOpcode();
1349
1350   bool equalityOnly = false;
1351   bool noSub = false;
1352   if (isPPC64) {
1353     if (is32BitSignedCompare) {
1354       // We can perform this optimization only if MI is sign-extending.
1355       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1356           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1357           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1358           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1359           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1360         noSub = true;
1361       } else
1362         return false;
1363     } else if (is32BitUnsignedCompare) {
1364       // We can perform this optimization, equality only, if MI is
1365       // zero-extending.
1366       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1367           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1368           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1369         noSub = true;
1370         equalityOnly = true;
1371       } else
1372         return false;
1373     } else
1374       equalityOnly = is64BitUnsignedCompare;
1375   } else
1376     equalityOnly = is32BitUnsignedCompare;
1377
1378   if (equalityOnly) {
1379     // We need to check the uses of the condition register in order to reject
1380     // non-equality comparisons.
1381     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1382          IE = MRI->use_instr_end(); I != IE; ++I) {
1383       MachineInstr *UseMI = &*I;
1384       if (UseMI->getOpcode() == PPC::BCC) {
1385         unsigned Pred = UseMI->getOperand(0).getImm();
1386         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1387           return false;
1388       } else if (UseMI->getOpcode() == PPC::ISEL ||
1389                  UseMI->getOpcode() == PPC::ISEL8) {
1390         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1391         if (SubIdx != PPC::sub_eq)
1392           return false;
1393       } else
1394         return false;
1395     }
1396   }
1397
1398   MachineBasicBlock::iterator I = CmpInstr;
1399
1400   // Scan forward to find the first use of the compare.
1401   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1402        I != EL; ++I) {
1403     bool FoundUse = false;
1404     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1405          JE = MRI->use_instr_end(); J != JE; ++J)
1406       if (&*J == &*I) {
1407         FoundUse = true;
1408         break;
1409       }
1410
1411     if (FoundUse)
1412       break;
1413   }
1414
1415   // There are two possible candidates which can be changed to set CR[01].
1416   // One is MI, the other is a SUB instruction.
1417   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1418   MachineInstr *Sub = nullptr;
1419   if (SrcReg2 != 0)
1420     // MI is not a candidate for CMPrr.
1421     MI = nullptr;
1422   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1423   // same BB as the comparison. This is to allow the check below to avoid calls
1424   // (and other explicit clobbers); instead we should really check for these
1425   // more explicitly (in at least a few predecessors).
1426   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1427     // PPC does not have a record-form SUBri.
1428     return false;
1429   }
1430
1431   // Search for Sub.
1432   const TargetRegisterInfo *TRI = &getRegisterInfo();
1433   --I;
1434
1435   // Get ready to iterate backward from CmpInstr.
1436   MachineBasicBlock::iterator E = MI,
1437                               B = CmpInstr->getParent()->begin();
1438
1439   for (; I != E && !noSub; --I) {
1440     const MachineInstr &Instr = *I;
1441     unsigned IOpC = Instr.getOpcode();
1442
1443     if (&*I != CmpInstr && (
1444         Instr.modifiesRegister(PPC::CR0, TRI) ||
1445         Instr.readsRegister(PPC::CR0, TRI)))
1446       // This instruction modifies or uses the record condition register after
1447       // the one we want to change. While we could do this transformation, it
1448       // would likely not be profitable. This transformation removes one
1449       // instruction, and so even forcing RA to generate one move probably
1450       // makes it unprofitable.
1451       return false;
1452
1453     // Check whether CmpInstr can be made redundant by the current instruction.
1454     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1455          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1456         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1457         ((Instr.getOperand(1).getReg() == SrcReg &&
1458           Instr.getOperand(2).getReg() == SrcReg2) ||
1459         (Instr.getOperand(1).getReg() == SrcReg2 &&
1460          Instr.getOperand(2).getReg() == SrcReg))) {
1461       Sub = &*I;
1462       break;
1463     }
1464
1465     if (I == B)
1466       // The 'and' is below the comparison instruction.
1467       return false;
1468   }
1469
1470   // Return false if no candidates exist.
1471   if (!MI && !Sub)
1472     return false;
1473
1474   // The single candidate is called MI.
1475   if (!MI) MI = Sub;
1476
1477   int NewOpC = -1;
1478   MIOpC = MI->getOpcode();
1479   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1480     NewOpC = MIOpC;
1481   else {
1482     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1483     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1484       NewOpC = MIOpC;
1485   }
1486
1487   // FIXME: On the non-embedded POWER architectures, only some of the record
1488   // forms are fast, and we should use only the fast ones.
1489
1490   // The defining instruction has a record form (or is already a record
1491   // form). It is possible, however, that we'll need to reverse the condition
1492   // code of the users.
1493   if (NewOpC == -1)
1494     return false;
1495
1496   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1497   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1498
1499   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1500   // needs to be updated to be based on SUB.  Push the condition code
1501   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1502   // condition code of these operands will be modified.
1503   bool ShouldSwap = false;
1504   if (Sub) {
1505     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1506       Sub->getOperand(2).getReg() == SrcReg;
1507
1508     // The operands to subf are the opposite of sub, so only in the fixed-point
1509     // case, invert the order.
1510     ShouldSwap = !ShouldSwap;
1511   }
1512
1513   if (ShouldSwap)
1514     for (MachineRegisterInfo::use_instr_iterator
1515          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1516          I != IE; ++I) {
1517       MachineInstr *UseMI = &*I;
1518       if (UseMI->getOpcode() == PPC::BCC) {
1519         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1520         assert((!equalityOnly ||
1521                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1522                "Invalid predicate for equality-only optimization");
1523         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1524                                 PPC::getSwappedPredicate(Pred)));
1525       } else if (UseMI->getOpcode() == PPC::ISEL ||
1526                  UseMI->getOpcode() == PPC::ISEL8) {
1527         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1528         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1529                "Invalid CR bit for equality-only optimization");
1530
1531         if (NewSubReg == PPC::sub_lt)
1532           NewSubReg = PPC::sub_gt;
1533         else if (NewSubReg == PPC::sub_gt)
1534           NewSubReg = PPC::sub_lt;
1535
1536         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1537                                                  NewSubReg));
1538       } else // We need to abort on a user we don't understand.
1539         return false;
1540     }
1541
1542   // Create a new virtual register to hold the value of the CR set by the
1543   // record-form instruction. If the instruction was not previously in
1544   // record form, then set the kill flag on the CR.
1545   CmpInstr->eraseFromParent();
1546
1547   MachineBasicBlock::iterator MII = MI;
1548   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1549           get(TargetOpcode::COPY), CRReg)
1550     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1551
1552   if (MIOpC != NewOpC) {
1553     // We need to be careful here: we're replacing one instruction with
1554     // another, and we need to make sure that we get all of the right
1555     // implicit uses and defs. On the other hand, the caller may be holding
1556     // an iterator to this instruction, and so we can't delete it (this is
1557     // specifically the case if this is the instruction directly after the
1558     // compare).
1559
1560     const MCInstrDesc &NewDesc = get(NewOpC);
1561     MI->setDesc(NewDesc);
1562
1563     if (NewDesc.ImplicitDefs)
1564       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1565            *ImpDefs; ++ImpDefs)
1566         if (!MI->definesRegister(*ImpDefs))
1567           MI->addOperand(*MI->getParent()->getParent(),
1568                          MachineOperand::CreateReg(*ImpDefs, true, true));
1569     if (NewDesc.ImplicitUses)
1570       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1571            *ImpUses; ++ImpUses)
1572         if (!MI->readsRegister(*ImpUses))
1573           MI->addOperand(*MI->getParent()->getParent(),
1574                          MachineOperand::CreateReg(*ImpUses, false, true));
1575   }
1576
1577   // Modify the condition code of operands in OperandsToUpdate.
1578   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1579   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1580   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1581     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1582
1583   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1584     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1585
1586   return true;
1587 }
1588
1589 /// GetInstSize - Return the number of bytes of code the specified
1590 /// instruction may be.  This returns the maximum number of bytes.
1591 ///
1592 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1593   unsigned Opcode = MI->getOpcode();
1594
1595   if (Opcode == PPC::INLINEASM) {
1596     const MachineFunction *MF = MI->getParent()->getParent();
1597     const char *AsmStr = MI->getOperand(0).getSymbolName();
1598     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1599   } else {
1600     const MCInstrDesc &Desc = get(Opcode);
1601     return Desc.getSize();
1602   }
1603 }
1604
1605 #undef DEBUG_TYPE
1606 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1607
1608 namespace {
1609   // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1610   // (Altivec and scalar floating-point registers), we need to transform the
1611   // copies into subregister copies with other restrictions.
1612   struct PPCVSXFMAMutate : public MachineFunctionPass {
1613     static char ID;
1614     PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1615       initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1616     }
1617
1618     LiveIntervals *LIS;
1619
1620     const PPCTargetMachine *TM;
1621     const PPCInstrInfo *TII;
1622
1623 protected:
1624     bool processBlock(MachineBasicBlock &MBB) {
1625       bool Changed = false;
1626
1627       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1628       const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
1629       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1630            I != IE; ++I) {
1631         MachineInstr *MI = I;
1632
1633         // The default (A-type) VSX FMA form kills the addend (it is taken from
1634         // the target register, which is then updated to reflect the result of
1635         // the FMA). If the instruction, however, kills one of the registers
1636         // used for the product, then we can use the M-form instruction (which
1637         // will take that value from the to-be-defined register).
1638
1639         int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1640         if (AltOpc == -1)
1641           continue;
1642
1643         // This pass is run after register coalescing, and so we're looking for
1644         // a situation like this:
1645         //   ...
1646         //   %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1647         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1648         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1649         //   ...
1650         //   %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1651         //                         %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1652         //   ...
1653         // Where we can eliminate the copy by changing from the A-type to the
1654         // M-type instruction. Specifically, for this example, this means:
1655         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1656         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1657         // is replaced by:
1658         //   %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1659         //                         %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1660         // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1661
1662         SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1663
1664         VNInfo *AddendValNo =
1665           LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1666         MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1667
1668         // The addend and this instruction must be in the same block.
1669
1670         if (!AddendMI || AddendMI->getParent() != MI->getParent())
1671           continue;
1672
1673         // The addend must be a full copy within the same register class.
1674
1675         if (!AddendMI->isFullCopy())
1676           continue;
1677
1678         unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1679         if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1680           if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1681               MRI.getRegClass(AddendSrcReg))
1682             continue;
1683         } else {
1684           // If AddendSrcReg is a physical register, make sure the destination
1685           // register class contains it.
1686           if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1687                 ->contains(AddendSrcReg))
1688             continue;
1689         }
1690
1691         // In theory, there could be other uses of the addend copy before this
1692         // fma.  We could deal with this, but that would require additional
1693         // logic below and I suspect it will not occur in any relevant
1694         // situations.  Additionally, check whether the copy source is killed
1695         // prior to the fma.  In order to replace the addend here with the
1696         // source of the copy, it must still be live here.  We can't use
1697         // interval testing for a physical register, so as long as we're
1698         // walking the MIs we may as well test liveness here.
1699         bool OtherUsers = false, KillsAddendSrc = false;
1700         for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1701              J != JE; --J) {
1702           if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1703             OtherUsers = true;
1704             break;
1705           }
1706           if (J->modifiesRegister(AddendSrcReg, TRI) ||
1707               J->killsRegister(AddendSrcReg, TRI)) {
1708             KillsAddendSrc = true;
1709             break;
1710           }
1711         }
1712
1713         if (OtherUsers || KillsAddendSrc)
1714           continue;
1715
1716         // Find one of the product operands that is killed by this instruction.
1717
1718         unsigned KilledProdOp = 0, OtherProdOp = 0;
1719         if (LIS->getInterval(MI->getOperand(2).getReg())
1720                      .Query(FMAIdx).isKill()) {
1721           KilledProdOp = 2;
1722           OtherProdOp  = 3;
1723         } else if (LIS->getInterval(MI->getOperand(3).getReg())
1724                      .Query(FMAIdx).isKill()) {
1725           KilledProdOp = 3;
1726           OtherProdOp  = 2;
1727         }
1728
1729         // If there are no killed product operands, then this transformation is
1730         // likely not profitable.
1731         if (!KilledProdOp)
1732           continue;
1733
1734         // For virtual registers, verify that the addend source register
1735         // is live here (as should have been assured above).
1736         assert((!TargetRegisterInfo::isVirtualRegister(AddendSrcReg) ||
1737                 LIS->getInterval(AddendSrcReg).liveAt(FMAIdx)) &&
1738                "Addend source register is not live!");
1739
1740         // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1741
1742         unsigned AddReg = AddendMI->getOperand(1).getReg();
1743         unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1744         unsigned OtherProdReg  = MI->getOperand(OtherProdOp).getReg();
1745
1746         unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1747         unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1748         unsigned OtherProdSubReg  = MI->getOperand(OtherProdOp).getSubReg();
1749
1750         bool AddRegKill = AddendMI->getOperand(1).isKill();
1751         bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1752         bool OtherProdRegKill  = MI->getOperand(OtherProdOp).isKill();
1753
1754         bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1755         bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1756         bool OtherProdRegUndef  = MI->getOperand(OtherProdOp).isUndef();
1757
1758         unsigned OldFMAReg = MI->getOperand(0).getReg();
1759
1760         // The transformation doesn't work well with things like:
1761         //    %vreg5 = A-form-op %vreg5, %vreg11, %vreg5;
1762         // so leave such things alone.
1763         if (OldFMAReg == KilledProdReg)
1764           continue;
1765
1766         assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1767                "Addend copy not tied to old FMA output!");
1768
1769         DEBUG(dbgs() << "VSX FMA Mutation:\n    " << *MI;);
1770
1771         MI->getOperand(0).setReg(KilledProdReg);
1772         MI->getOperand(1).setReg(KilledProdReg);
1773         MI->getOperand(3).setReg(AddReg);
1774         MI->getOperand(2).setReg(OtherProdReg);
1775
1776         MI->getOperand(0).setSubReg(KilledProdSubReg);
1777         MI->getOperand(1).setSubReg(KilledProdSubReg);
1778         MI->getOperand(3).setSubReg(AddSubReg);
1779         MI->getOperand(2).setSubReg(OtherProdSubReg);
1780
1781         MI->getOperand(1).setIsKill(KilledProdRegKill);
1782         MI->getOperand(3).setIsKill(AddRegKill);
1783         MI->getOperand(2).setIsKill(OtherProdRegKill);
1784
1785         MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1786         MI->getOperand(3).setIsUndef(AddRegUndef);
1787         MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1788
1789         MI->setDesc(TII->get(AltOpc));
1790
1791         DEBUG(dbgs() << " -> " << *MI);
1792
1793         // The killed product operand was killed here, so we can reuse it now
1794         // for the result of the fma.
1795
1796         LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1797         VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1798         for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1799              UI != UE;) {
1800           MachineOperand &UseMO = *UI;
1801           MachineInstr *UseMI = UseMO.getParent();
1802           ++UI;
1803
1804           // Don't replace the result register of the copy we're about to erase.
1805           if (UseMI == AddendMI)
1806             continue;
1807
1808           UseMO.setReg(KilledProdReg);
1809           UseMO.setSubReg(KilledProdSubReg);
1810         }
1811
1812         // Extend the live intervals of the killed product operand to hold the
1813         // fma result.
1814
1815         LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1816         for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1817              AI != AE; ++AI) {
1818           // Don't add the segment that corresponds to the original copy.
1819           if (AI->valno == AddendValNo)
1820             continue;
1821
1822           VNInfo *NewFMAValNo =
1823             NewFMAInt.getNextValue(AI->start,
1824                                    LIS->getVNInfoAllocator());
1825
1826           NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1827                                                      NewFMAValNo));
1828         }
1829         DEBUG(dbgs() << "  extended: " << NewFMAInt << '\n');
1830
1831         FMAInt.removeValNo(FMAValNo);
1832         DEBUG(dbgs() << "  trimmed:  " << FMAInt << '\n');
1833
1834         // Remove the (now unused) copy.
1835
1836         DEBUG(dbgs() << "  removing: " << *AddendMI << '\n');
1837         LIS->RemoveMachineInstrFromMaps(AddendMI);
1838         AddendMI->eraseFromParent();
1839
1840         Changed = true;
1841       }
1842
1843       return Changed;
1844     }
1845
1846 public:
1847     bool runOnMachineFunction(MachineFunction &MF) override {
1848       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1849       // If we don't have VSX then go ahead and return without doing
1850       // anything.
1851       if (!TM->getSubtargetImpl()->hasVSX())
1852         return false;
1853
1854       LIS = &getAnalysis<LiveIntervals>();
1855
1856       TII = TM->getSubtargetImpl()->getInstrInfo();
1857
1858       bool Changed = false;
1859
1860       if (DisableVSXFMAMutate)
1861         return Changed;
1862
1863       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1864         MachineBasicBlock &B = *I++;
1865         if (processBlock(B))
1866           Changed = true;
1867       }
1868
1869       return Changed;
1870     }
1871
1872     void getAnalysisUsage(AnalysisUsage &AU) const override {
1873       AU.addRequired<LiveIntervals>();
1874       AU.addPreserved<LiveIntervals>();
1875       AU.addRequired<SlotIndexes>();
1876       AU.addPreserved<SlotIndexes>();
1877       MachineFunctionPass::getAnalysisUsage(AU);
1878     }
1879   };
1880 }
1881
1882 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1883                       "PowerPC VSX FMA Mutation", false, false)
1884 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1885 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1886 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1887                     "PowerPC VSX FMA Mutation", false, false)
1888
1889 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1890
1891 char PPCVSXFMAMutate::ID = 0;
1892 FunctionPass*
1893 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1894
1895 #undef DEBUG_TYPE
1896 #define DEBUG_TYPE "ppc-vsx-copy"
1897
1898 namespace llvm {
1899   void initializePPCVSXCopyPass(PassRegistry&);
1900 }
1901
1902 namespace {
1903   // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1904   // (Altivec and scalar floating-point registers), we need to transform the
1905   // copies into subregister copies with other restrictions.
1906   struct PPCVSXCopy : public MachineFunctionPass {
1907     static char ID;
1908     PPCVSXCopy() : MachineFunctionPass(ID) {
1909       initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1910     }
1911
1912     const PPCTargetMachine *TM;
1913     const PPCInstrInfo *TII;
1914
1915     bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1916                       MachineRegisterInfo &MRI) {
1917       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1918         return RC->hasSubClassEq(MRI.getRegClass(Reg));
1919       } else if (RC->contains(Reg)) {
1920         return true;
1921       }
1922
1923       return false;
1924     }
1925
1926     bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1927       return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1928     }
1929
1930     bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1931       return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1932     }
1933
1934     bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1935       return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1936     }
1937
1938 protected:
1939     bool processBlock(MachineBasicBlock &MBB) {
1940       bool Changed = false;
1941
1942       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1943       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1944            I != IE; ++I) {
1945         MachineInstr *MI = I;
1946         if (!MI->isFullCopy())
1947           continue;
1948
1949         MachineOperand &DstMO = MI->getOperand(0);
1950         MachineOperand &SrcMO = MI->getOperand(1);
1951
1952         if ( IsVSReg(DstMO.getReg(), MRI) &&
1953             !IsVSReg(SrcMO.getReg(), MRI)) {
1954           // This is a copy *to* a VSX register from a non-VSX register.
1955           Changed = true;
1956
1957           const TargetRegisterClass *SrcRC =
1958             IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1959                                            &PPC::VSLRCRegClass;
1960           assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1961                   IsVRReg(SrcMO.getReg(), MRI)) &&
1962                  "Unknown source for a VSX copy");
1963
1964           unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1965           BuildMI(MBB, MI, MI->getDebugLoc(),
1966                   TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1967             .addImm(1) // add 1, not 0, because there is no implicit clearing
1968                        // of the high bits.
1969             .addOperand(SrcMO)
1970             .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1971                                                    PPC::sub_64);
1972
1973           // The source of the original copy is now the new virtual register.
1974           SrcMO.setReg(NewVReg);
1975         } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1976                     IsVSReg(SrcMO.getReg(), MRI)) {
1977           // This is a copy *from* a VSX register to a non-VSX register.
1978           Changed = true;
1979
1980           const TargetRegisterClass *DstRC =
1981             IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1982                                            &PPC::VSLRCRegClass;
1983           assert((IsF8Reg(DstMO.getReg(), MRI) ||
1984                   IsVRReg(DstMO.getReg(), MRI)) &&
1985                  "Unknown destination for a VSX copy");
1986
1987           // Copy the VSX value into a new VSX register of the correct subclass.
1988           unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1989           BuildMI(MBB, MI, MI->getDebugLoc(),
1990                   TII->get(TargetOpcode::COPY), NewVReg)
1991             .addOperand(SrcMO);
1992
1993           // Transform the original copy into a subregister extraction copy.
1994           SrcMO.setReg(NewVReg);
1995           SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1996                                                          PPC::sub_64);
1997         }
1998       }
1999
2000       return Changed;
2001     }
2002
2003 public:
2004     bool runOnMachineFunction(MachineFunction &MF) override {
2005       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2006       // If we don't have VSX on the subtarget, don't do anything.
2007       if (!TM->getSubtargetImpl()->hasVSX())
2008         return false;
2009       TII = TM->getSubtargetImpl()->getInstrInfo();
2010
2011       bool Changed = false;
2012
2013       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2014         MachineBasicBlock &B = *I++;
2015         if (processBlock(B))
2016           Changed = true;
2017       }
2018
2019       return Changed;
2020     }
2021
2022     void getAnalysisUsage(AnalysisUsage &AU) const override {
2023       MachineFunctionPass::getAnalysisUsage(AU);
2024     }
2025   };
2026 }
2027
2028 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2029                 "PowerPC VSX Copy Legalization", false, false)
2030
2031 char PPCVSXCopy::ID = 0;
2032 FunctionPass*
2033 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2034
2035 #undef DEBUG_TYPE
2036 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2037
2038 namespace llvm {
2039   void initializePPCVSXCopyCleanupPass(PassRegistry&);
2040 }
2041
2042 namespace {
2043   // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2044   // registers (mostly because the ABI code still places all values into the
2045   // "traditional" floating-point and vector registers). Remove them here.
2046   struct PPCVSXCopyCleanup : public MachineFunctionPass {
2047     static char ID;
2048     PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2049       initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2050     }
2051
2052     const PPCTargetMachine *TM;
2053     const PPCInstrInfo *TII;
2054
2055 protected:
2056     bool processBlock(MachineBasicBlock &MBB) {
2057       bool Changed = false;
2058
2059       SmallVector<MachineInstr *, 4> ToDelete;
2060       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2061            I != IE; ++I) {
2062         MachineInstr *MI = I;
2063         if (MI->getOpcode() == PPC::XXLOR &&
2064             MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2065             MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2066           ToDelete.push_back(MI);
2067       }
2068
2069       if (!ToDelete.empty())
2070         Changed = true;
2071
2072       for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2073         DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2074         ToDelete[i]->eraseFromParent();
2075       }
2076
2077       return Changed;
2078     }
2079
2080 public:
2081     bool runOnMachineFunction(MachineFunction &MF) override {
2082       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2083       // If we don't have VSX don't bother doing anything here.
2084       if (!TM->getSubtargetImpl()->hasVSX())
2085         return false;
2086       TII = TM->getSubtargetImpl()->getInstrInfo();
2087
2088       bool Changed = false;
2089
2090       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2091         MachineBasicBlock &B = *I++;
2092         if (processBlock(B))
2093           Changed = true;
2094       }
2095
2096       return Changed;
2097     }
2098
2099     void getAnalysisUsage(AnalysisUsage &AU) const override {
2100       MachineFunctionPass::getAnalysisUsage(AU);
2101     }
2102   };
2103 }
2104
2105 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2106                 "PowerPC VSX Copy Cleanup", false, false)
2107
2108 char PPCVSXCopyCleanup::ID = 0;
2109 FunctionPass*
2110 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2111
2112 #undef DEBUG_TYPE
2113 #define DEBUG_TYPE "ppc-early-ret"
2114 STATISTIC(NumBCLR, "Number of early conditional returns");
2115 STATISTIC(NumBLR,  "Number of early returns");
2116
2117 namespace llvm {
2118   void initializePPCEarlyReturnPass(PassRegistry&);
2119 }
2120
2121 namespace {
2122   // PPCEarlyReturn pass - For simple functions without epilogue code, move
2123   // returns up, and create conditional returns, to avoid unnecessary
2124   // branch-to-blr sequences.
2125   struct PPCEarlyReturn : public MachineFunctionPass {
2126     static char ID;
2127     PPCEarlyReturn() : MachineFunctionPass(ID) {
2128       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2129     }
2130
2131     const PPCTargetMachine *TM;
2132     const PPCInstrInfo *TII;
2133
2134 protected:
2135     bool processBlock(MachineBasicBlock &ReturnMBB) {
2136       bool Changed = false;
2137
2138       MachineBasicBlock::iterator I = ReturnMBB.begin();
2139       I = ReturnMBB.SkipPHIsAndLabels(I);
2140
2141       // The block must be essentially empty except for the blr.
2142       if (I == ReturnMBB.end() ||
2143           (I->getOpcode() != PPC::BLR && I->getOpcode() != PPC::BLR8) ||
2144           I != ReturnMBB.getLastNonDebugInstr())
2145         return Changed;
2146
2147       SmallVector<MachineBasicBlock*, 8> PredToRemove;
2148       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2149            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2150         bool OtherReference = false, BlockChanged = false;
2151         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2152           if (J->getOpcode() == PPC::B) {
2153             if (J->getOperand(0).getMBB() == &ReturnMBB) {
2154               // This is an unconditional branch to the return. Replace the
2155               // branch with a blr.
2156               BuildMI(**PI, J, J->getDebugLoc(), TII->get(I->getOpcode()));
2157               MachineBasicBlock::iterator K = J--;
2158               K->eraseFromParent();
2159               BlockChanged = true;
2160               ++NumBLR;
2161               continue;
2162             }
2163           } else if (J->getOpcode() == PPC::BCC) {
2164             if (J->getOperand(2).getMBB() == &ReturnMBB) {
2165               // This is a conditional branch to the return. Replace the branch
2166               // with a bclr.
2167               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2168                 .addImm(J->getOperand(0).getImm())
2169                 .addReg(J->getOperand(1).getReg());
2170               MachineBasicBlock::iterator K = J--;
2171               K->eraseFromParent();
2172               BlockChanged = true;
2173               ++NumBCLR;
2174               continue;
2175             }
2176           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2177             if (J->getOperand(1).getMBB() == &ReturnMBB) {
2178               // This is a conditional branch to the return. Replace the branch
2179               // with a bclr.
2180               BuildMI(**PI, J, J->getDebugLoc(),
2181                       TII->get(J->getOpcode() == PPC::BC ?
2182                                PPC::BCLR : PPC::BCLRn))
2183                 .addReg(J->getOperand(0).getReg());
2184               MachineBasicBlock::iterator K = J--;
2185               K->eraseFromParent();
2186               BlockChanged = true;
2187               ++NumBCLR;
2188               continue;
2189             }
2190           } else if (J->isBranch()) {
2191             if (J->isIndirectBranch()) {
2192               if (ReturnMBB.hasAddressTaken())
2193                 OtherReference = true;
2194             } else
2195               for (unsigned i = 0; i < J->getNumOperands(); ++i)
2196                 if (J->getOperand(i).isMBB() &&
2197                     J->getOperand(i).getMBB() == &ReturnMBB)
2198                   OtherReference = true;
2199           } else if (!J->isTerminator() && !J->isDebugValue())
2200             break;
2201
2202           if (J == (*PI)->begin())
2203             break;
2204
2205           --J;
2206         }
2207
2208         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2209           OtherReference = true;
2210
2211         // Predecessors are stored in a vector and can't be removed here.
2212         if (!OtherReference && BlockChanged) {
2213           PredToRemove.push_back(*PI);
2214         }
2215
2216         if (BlockChanged)
2217           Changed = true;
2218       }
2219
2220       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2221         PredToRemove[i]->removeSuccessor(&ReturnMBB);
2222
2223       if (Changed && !ReturnMBB.hasAddressTaken()) {
2224         // We now might be able to merge this blr-only block into its
2225         // by-layout predecessor.
2226         if (ReturnMBB.pred_size() == 1 &&
2227             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2228           // Move the blr into the preceding block.
2229           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2230           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2231           PrevMBB.removeSuccessor(&ReturnMBB);
2232         }
2233
2234         if (ReturnMBB.pred_empty())
2235           ReturnMBB.eraseFromParent();
2236       }
2237
2238       return Changed;
2239     }
2240
2241 public:
2242     bool runOnMachineFunction(MachineFunction &MF) override {
2243       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2244       TII = TM->getSubtargetImpl()->getInstrInfo();
2245
2246       bool Changed = false;
2247
2248       // If the function does not have at least two blocks, then there is
2249       // nothing to do.
2250       if (MF.size() < 2)
2251         return Changed;
2252
2253       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2254         MachineBasicBlock &B = *I++;
2255         if (processBlock(B))
2256           Changed = true;
2257       }
2258
2259       return Changed;
2260     }
2261
2262     void getAnalysisUsage(AnalysisUsage &AU) const override {
2263       MachineFunctionPass::getAnalysisUsage(AU);
2264     }
2265   };
2266 }
2267
2268 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2269                 "PowerPC Early-Return Creation", false, false)
2270
2271 char PPCEarlyReturn::ID = 0;
2272 FunctionPass*
2273 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }