[PowerPC] Enable interleaved-access vectorization
[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/CodeGen/StackMaps.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "ppc-instr-info"
44
45 #define GET_INSTRMAP_INFO
46 #define GET_INSTRINFO_CTOR_DTOR
47 #include "PPCGenInstrInfo.inc"
48
49 static cl::
50 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
51             cl::desc("Disable analysis for CTR loops"));
52
53 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
54 cl::desc("Disable compare instruction optimization"), cl::Hidden);
55
56 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
57 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
58 cl::Hidden);
59
60 static cl::opt<bool>
61 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
62   cl::desc("Use the old (incorrect) instruction latency calculation"));
63
64 // Pin the vtable to this file.
65 void PPCInstrInfo::anchor() {}
66
67 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
68     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
69       Subtarget(STI), RI(STI.getTargetMachine()) {}
70
71 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
72 /// this target when scheduling the DAG.
73 ScheduleHazardRecognizer *
74 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
75                                            const ScheduleDAG *DAG) const {
76   unsigned Directive =
77       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
78   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
79       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
80     const InstrItineraryData *II =
81         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
82     return new ScoreboardHazardRecognizer(II, DAG);
83   }
84
85   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
86 }
87
88 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
89 /// to use for this target when scheduling the DAG.
90 ScheduleHazardRecognizer *
91 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
92                                                  const ScheduleDAG *DAG) const {
93   unsigned Directive =
94       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
95
96   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
97     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
98
99   // Most subtargets use a PPC970 recognizer.
100   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
101       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
102     assert(DAG->TII && "No InstrInfo?");
103
104     return new PPCHazardRecognizer970(*DAG);
105   }
106
107   return new ScoreboardHazardRecognizer(II, DAG);
108 }
109
110 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
111                                        const MachineInstr *MI,
112                                        unsigned *PredCost) const {
113   if (!ItinData || UseOldLatencyCalc)
114     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
115
116   // The default implementation of getInstrLatency calls getStageLatency, but
117   // getStageLatency does not do the right thing for us. While we have
118   // itinerary, most cores are fully pipelined, and so the itineraries only
119   // express the first part of the pipeline, not every stage. Instead, we need
120   // to use the listed output operand cycle number (using operand 0 here, which
121   // is an output).
122
123   unsigned Latency = 1;
124   unsigned DefClass = MI->getDesc().getSchedClass();
125   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
126     const MachineOperand &MO = MI->getOperand(i);
127     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
128       continue;
129
130     int Cycle = ItinData->getOperandCycle(DefClass, i);
131     if (Cycle < 0)
132       continue;
133
134     Latency = std::max(Latency, (unsigned) Cycle);
135   }
136
137   return Latency;
138 }
139
140 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
141                                     const MachineInstr *DefMI, unsigned DefIdx,
142                                     const MachineInstr *UseMI,
143                                     unsigned UseIdx) const {
144   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
145                                                    UseMI, UseIdx);
146
147   if (!DefMI->getParent())
148     return Latency;
149
150   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
151   unsigned Reg = DefMO.getReg();
152
153   bool IsRegCR;
154   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
155     const MachineRegisterInfo *MRI =
156       &DefMI->getParent()->getParent()->getRegInfo();
157     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
158               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
159   } else {
160     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
161               PPC::CRBITRCRegClass.contains(Reg);
162   }
163
164   if (UseMI->isBranch() && IsRegCR) {
165     if (Latency < 0)
166       Latency = getInstrLatency(ItinData, DefMI);
167
168     // On some cores, there is an additional delay between writing to a condition
169     // register, and using it from a branch.
170     unsigned Directive = Subtarget.getDarwinDirective();
171     switch (Directive) {
172     default: break;
173     case PPC::DIR_7400:
174     case PPC::DIR_750:
175     case PPC::DIR_970:
176     case PPC::DIR_E5500:
177     case PPC::DIR_PWR4:
178     case PPC::DIR_PWR5:
179     case PPC::DIR_PWR5X:
180     case PPC::DIR_PWR6:
181     case PPC::DIR_PWR6X:
182     case PPC::DIR_PWR7:
183     case PPC::DIR_PWR8:
184       Latency += 2;
185       break;
186     }
187   }
188
189   return Latency;
190 }
191
192 static bool hasVirtualRegDefsInBasicBlock(const MachineInstr &Inst,
193                                           const MachineBasicBlock *MBB) {
194   const MachineOperand &Op1 = Inst.getOperand(1);
195   const MachineOperand &Op2 = Inst.getOperand(2);
196   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
197
198   // We need virtual register definitions.
199   MachineInstr *MI1 = nullptr;
200   MachineInstr *MI2 = nullptr;
201   if (Op1.isReg() && TargetRegisterInfo::isVirtualRegister(Op1.getReg()))
202     MI1 = MRI.getUniqueVRegDef(Op1.getReg());
203   if (Op2.isReg() && TargetRegisterInfo::isVirtualRegister(Op2.getReg()))
204     MI2 = MRI.getUniqueVRegDef(Op2.getReg());
205
206   // And they need to be in the trace (otherwise, they won't have a depth).
207   if (MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB)
208     return true;
209
210   return false;
211 }
212
213 static bool hasReassocSibling(const MachineInstr &Inst, bool &Commuted) {
214   const MachineBasicBlock *MBB = Inst.getParent();
215   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
216   MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
217   MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
218   unsigned AssocOpcode = Inst.getOpcode();
219
220   // If only one operand has the same opcode and it's the second source operand,
221   // the operands must be commuted.
222   Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode;
223   if (Commuted)
224     std::swap(MI1, MI2);
225
226   // 1. The previous instruction must be the same type as Inst.
227   // 2. The previous instruction must have virtual register definitions for its
228   //    operands in the same basic block as Inst.
229   // 3. The previous instruction's result must only be used by Inst.
230   if (MI1->getOpcode() == AssocOpcode &&
231       hasVirtualRegDefsInBasicBlock(*MI1, MBB) &&
232       MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg()))
233     return true;
234
235   return false;
236 }
237
238 // This function does not list all associative and commutative operations, but
239 // only those worth feeding through the machine combiner in an attempt to
240 // reduce the critical path. Mostly, this means floating-point operations,
241 // because they have high latencies (compared to other operations, such and
242 // and/or, which are also associative and commutative, but have low latencies).
243 //
244 // The concept is that these operations can benefit from this kind of
245 // transformation:
246 //
247 // A = ? op ?
248 // B = A op X
249 // C = B op Y
250 // -->
251 // A = ? op ?
252 // B = X op Y
253 // C = A op B
254 //
255 // breaking the dependency between A and B, allowing them to be executed in
256 // parallel (or back-to-back in a pipeline) instead of depending on each other.
257 static bool isAssociativeAndCommutative(unsigned Opcode) {
258   switch (Opcode) {
259   // FP Add:
260   case PPC::FADD:
261   case PPC::FADDS:
262   // FP Multiply:
263   case PPC::FMUL:
264   case PPC::FMULS:
265   // Altivec Add:
266   case PPC::VADDFP:
267   // VSX Add:
268   case PPC::XSADDDP:
269   case PPC::XVADDDP:
270   case PPC::XVADDSP:
271   case PPC::XSADDSP:
272   // VSX Multiply:
273   case PPC::XSMULDP:
274   case PPC::XVMULDP:
275   case PPC::XVMULSP:
276   case PPC::XSMULSP:
277   // QPX Add:
278   case PPC::QVFADD:
279   case PPC::QVFADDS:
280   case PPC::QVFADDSs:
281   // QPX Multiply:
282   case PPC::QVFMUL:
283   case PPC::QVFMULS:
284   case PPC::QVFMULSs:
285     return true;
286   default:
287     return false;
288   }
289 }
290
291 /// Return true if the input instruction is part of a chain of dependent ops
292 /// that are suitable for reassociation, otherwise return false.
293 /// If the instruction's operands must be commuted to have a previous
294 /// instruction of the same type define the first source operand, Commuted will
295 /// be set to true.
296 static bool isReassocCandidate(const MachineInstr &Inst, bool &Commuted) {
297   // 1. The operation must be associative and commutative.
298   // 2. The instruction must have virtual register definitions for its
299   //    operands in the same basic block.
300   // 3. The instruction must have a reassociable sibling.
301   if (isAssociativeAndCommutative(Inst.getOpcode()) &&
302       hasVirtualRegDefsInBasicBlock(Inst, Inst.getParent()) &&
303       hasReassocSibling(Inst, Commuted))
304     return true;
305
306   return false;
307 }
308
309 bool PPCInstrInfo::getMachineCombinerPatterns(MachineInstr &Root,
310         SmallVectorImpl<MachineCombinerPattern::MC_PATTERN> &Patterns) const {
311   // Using the machine combiner in this way is potentially expensive, so
312   // restrict to when aggressive optimizations are desired.
313   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
314     return false;
315
316   // FP reassociation is only legal when we don't need strict IEEE semantics.
317   if (!Root.getParent()->getParent()->getTarget().Options.UnsafeFPMath)
318     return false;
319
320   // Look for this reassociation pattern:
321   //   B = A op X (Prev)
322   //   C = B op Y (Root)
323
324   // FIXME: We should also match FMA operations here, where we consider the
325   // 'part' of the FMA, either the addition or the multiplication, paired with
326   // an actual addition or multiplication.
327
328   bool Commute;
329   if (isReassocCandidate(Root, Commute)) {
330     // We found a sequence of instructions that may be suitable for a
331     // reassociation of operands to increase ILP. Specify each commutation
332     // possibility for the Prev instruction in the sequence and let the
333     // machine combiner decide if changing the operands is worthwhile.
334     if (Commute) {
335       Patterns.push_back(MachineCombinerPattern::MC_REASSOC_AX_YB);
336       Patterns.push_back(MachineCombinerPattern::MC_REASSOC_XA_YB);
337     } else {
338       Patterns.push_back(MachineCombinerPattern::MC_REASSOC_AX_BY);
339       Patterns.push_back(MachineCombinerPattern::MC_REASSOC_XA_BY);
340     }
341     return true;
342   }
343
344   return false;
345 }
346
347 /// Attempt the following reassociation to reduce critical path length:
348 ///   B = A op X (Prev)
349 ///   C = B op Y (Root)
350 ///   ===>
351 ///   B = X op Y
352 ///   C = A op B
353 static void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
354                            MachineCombinerPattern::MC_PATTERN Pattern,
355                            SmallVectorImpl<MachineInstr *> &InsInstrs,
356                            SmallVectorImpl<MachineInstr *> &DelInstrs,
357                            DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) {
358   MachineFunction *MF = Root.getParent()->getParent();
359   MachineRegisterInfo &MRI = MF->getRegInfo();
360   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
361   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
362   const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI);
363
364   // This array encodes the operand index for each parameter because the
365   // operands may be commuted. Each row corresponds to a pattern value,
366   // and each column specifies the index of A, B, X, Y.
367   unsigned OpIdx[4][4] = {
368     { 1, 1, 2, 2 },
369     { 1, 2, 2, 1 },
370     { 2, 1, 1, 2 },
371     { 2, 2, 1, 1 }
372   };
373
374   MachineOperand &OpA = Prev.getOperand(OpIdx[Pattern][0]);
375   MachineOperand &OpB = Root.getOperand(OpIdx[Pattern][1]);
376   MachineOperand &OpX = Prev.getOperand(OpIdx[Pattern][2]);
377   MachineOperand &OpY = Root.getOperand(OpIdx[Pattern][3]);
378   MachineOperand &OpC = Root.getOperand(0);
379
380   unsigned RegA = OpA.getReg();
381   unsigned RegB = OpB.getReg();
382   unsigned RegX = OpX.getReg();
383   unsigned RegY = OpY.getReg();
384   unsigned RegC = OpC.getReg();
385
386   if (TargetRegisterInfo::isVirtualRegister(RegA))
387     MRI.constrainRegClass(RegA, RC);
388   if (TargetRegisterInfo::isVirtualRegister(RegB))
389     MRI.constrainRegClass(RegB, RC);
390   if (TargetRegisterInfo::isVirtualRegister(RegX))
391     MRI.constrainRegClass(RegX, RC);
392   if (TargetRegisterInfo::isVirtualRegister(RegY))
393     MRI.constrainRegClass(RegY, RC);
394   if (TargetRegisterInfo::isVirtualRegister(RegC))
395     MRI.constrainRegClass(RegC, RC);
396
397   // Create a new virtual register for the result of (X op Y) instead of
398   // recycling RegB because the MachineCombiner's computation of the critical
399   // path requires a new register definition rather than an existing one.
400   unsigned NewVR = MRI.createVirtualRegister(RC);
401   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
402
403   unsigned Opcode = Root.getOpcode();
404   bool KillA = OpA.isKill();
405   bool KillX = OpX.isKill();
406   bool KillY = OpY.isKill();
407
408   // Create new instructions for insertion.
409   MachineInstrBuilder MIB1 =
410     BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR)
411       .addReg(RegX, getKillRegState(KillX))
412       .addReg(RegY, getKillRegState(KillY));
413   InsInstrs.push_back(MIB1);
414
415   MachineInstrBuilder MIB2 =
416     BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC)
417       .addReg(RegA, getKillRegState(KillA))
418       .addReg(NewVR, getKillRegState(true));
419   InsInstrs.push_back(MIB2);
420
421   // Record old instructions for deletion.
422   DelInstrs.push_back(&Prev);
423   DelInstrs.push_back(&Root);
424 }
425
426 void PPCInstrInfo::genAlternativeCodeSequence(
427     MachineInstr &Root,
428     MachineCombinerPattern::MC_PATTERN Pattern,
429     SmallVectorImpl<MachineInstr *> &InsInstrs,
430     SmallVectorImpl<MachineInstr *> &DelInstrs,
431     DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const {
432   MachineRegisterInfo &MRI = Root.getParent()->getParent()->getRegInfo();
433
434   // Select the previous instruction in the sequence based on the input pattern.
435   MachineInstr *Prev = nullptr;
436   switch (Pattern) {
437     case MachineCombinerPattern::MC_REASSOC_AX_BY:
438     case MachineCombinerPattern::MC_REASSOC_XA_BY:
439       Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
440       break;
441     case MachineCombinerPattern::MC_REASSOC_AX_YB:
442     case MachineCombinerPattern::MC_REASSOC_XA_YB:
443       Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
444   }
445   assert(Prev && "Unknown pattern for machine combiner");
446
447   reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg);
448   return;
449 }
450
451 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
452 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
453                                          unsigned &SrcReg, unsigned &DstReg,
454                                          unsigned &SubIdx) const {
455   switch (MI.getOpcode()) {
456   default: return false;
457   case PPC::EXTSW:
458   case PPC::EXTSW_32_64:
459     SrcReg = MI.getOperand(1).getReg();
460     DstReg = MI.getOperand(0).getReg();
461     SubIdx = PPC::sub_32;
462     return true;
463   }
464 }
465
466 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
467                                            int &FrameIndex) const {
468   // Note: This list must be kept consistent with LoadRegFromStackSlot.
469   switch (MI->getOpcode()) {
470   default: break;
471   case PPC::LD:
472   case PPC::LWZ:
473   case PPC::LFS:
474   case PPC::LFD:
475   case PPC::RESTORE_CR:
476   case PPC::RESTORE_CRBIT:
477   case PPC::LVX:
478   case PPC::LXVD2X:
479   case PPC::QVLFDX:
480   case PPC::QVLFSXs:
481   case PPC::QVLFDXb:
482   case PPC::RESTORE_VRSAVE:
483     // Check for the operands added by addFrameReference (the immediate is the
484     // offset which defaults to 0).
485     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
486         MI->getOperand(2).isFI()) {
487       FrameIndex = MI->getOperand(2).getIndex();
488       return MI->getOperand(0).getReg();
489     }
490     break;
491   }
492   return 0;
493 }
494
495 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
496                                           int &FrameIndex) const {
497   // Note: This list must be kept consistent with StoreRegToStackSlot.
498   switch (MI->getOpcode()) {
499   default: break;
500   case PPC::STD:
501   case PPC::STW:
502   case PPC::STFS:
503   case PPC::STFD:
504   case PPC::SPILL_CR:
505   case PPC::SPILL_CRBIT:
506   case PPC::STVX:
507   case PPC::STXVD2X:
508   case PPC::QVSTFDX:
509   case PPC::QVSTFSXs:
510   case PPC::QVSTFDXb:
511   case PPC::SPILL_VRSAVE:
512     // Check for the operands added by addFrameReference (the immediate is the
513     // offset which defaults to 0).
514     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
515         MI->getOperand(2).isFI()) {
516       FrameIndex = MI->getOperand(2).getIndex();
517       return MI->getOperand(0).getReg();
518     }
519     break;
520   }
521   return 0;
522 }
523
524 // commuteInstruction - We can commute rlwimi instructions, but only if the
525 // rotate amt is zero.  We also have to munge the immediates a bit.
526 MachineInstr *
527 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
528   MachineFunction &MF = *MI->getParent()->getParent();
529
530   // Normal instructions can be commuted the obvious way.
531   if (MI->getOpcode() != PPC::RLWIMI &&
532       MI->getOpcode() != PPC::RLWIMIo)
533     return TargetInstrInfo::commuteInstruction(MI, NewMI);
534   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
535   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
536   // changing the relative order of the mask operands might change what happens
537   // to the high-bits of the mask (and, thus, the result).
538
539   // Cannot commute if it has a non-zero rotate count.
540   if (MI->getOperand(3).getImm() != 0)
541     return nullptr;
542
543   // If we have a zero rotate count, we have:
544   //   M = mask(MB,ME)
545   //   Op0 = (Op1 & ~M) | (Op2 & M)
546   // Change this to:
547   //   M = mask((ME+1)&31, (MB-1)&31)
548   //   Op0 = (Op2 & ~M) | (Op1 & M)
549
550   // Swap op1/op2
551   unsigned Reg0 = MI->getOperand(0).getReg();
552   unsigned Reg1 = MI->getOperand(1).getReg();
553   unsigned Reg2 = MI->getOperand(2).getReg();
554   unsigned SubReg1 = MI->getOperand(1).getSubReg();
555   unsigned SubReg2 = MI->getOperand(2).getSubReg();
556   bool Reg1IsKill = MI->getOperand(1).isKill();
557   bool Reg2IsKill = MI->getOperand(2).isKill();
558   bool ChangeReg0 = false;
559   // If machine instrs are no longer in two-address forms, update
560   // destination register as well.
561   if (Reg0 == Reg1) {
562     // Must be two address instruction!
563     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
564            "Expecting a two-address instruction!");
565     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
566     Reg2IsKill = false;
567     ChangeReg0 = true;
568   }
569
570   // Masks.
571   unsigned MB = MI->getOperand(4).getImm();
572   unsigned ME = MI->getOperand(5).getImm();
573
574   if (NewMI) {
575     // Create a new instruction.
576     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
577     bool Reg0IsDead = MI->getOperand(0).isDead();
578     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
579       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
580       .addReg(Reg2, getKillRegState(Reg2IsKill))
581       .addReg(Reg1, getKillRegState(Reg1IsKill))
582       .addImm((ME+1) & 31)
583       .addImm((MB-1) & 31);
584   }
585
586   if (ChangeReg0) {
587     MI->getOperand(0).setReg(Reg2);
588     MI->getOperand(0).setSubReg(SubReg2);
589   }
590   MI->getOperand(2).setReg(Reg1);
591   MI->getOperand(1).setReg(Reg2);
592   MI->getOperand(2).setSubReg(SubReg1);
593   MI->getOperand(1).setSubReg(SubReg2);
594   MI->getOperand(2).setIsKill(Reg1IsKill);
595   MI->getOperand(1).setIsKill(Reg2IsKill);
596
597   // Swap the mask around.
598   MI->getOperand(4).setImm((ME+1) & 31);
599   MI->getOperand(5).setImm((MB-1) & 31);
600   return MI;
601 }
602
603 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
604                                          unsigned &SrcOpIdx2) const {
605   // For VSX A-Type FMA instructions, it is the first two operands that can be
606   // commuted, however, because the non-encoded tied input operand is listed
607   // first, the operands to swap are actually the second and third.
608
609   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
610   if (AltOpc == -1)
611     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
612
613   SrcOpIdx1 = 2;
614   SrcOpIdx2 = 3;
615   return true;
616 }
617
618 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
619                               MachineBasicBlock::iterator MI) const {
620   // This function is used for scheduling, and the nop wanted here is the type
621   // that terminates dispatch groups on the POWER cores.
622   unsigned Directive = Subtarget.getDarwinDirective();
623   unsigned Opcode;
624   switch (Directive) {
625   default:            Opcode = PPC::NOP; break;
626   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
627   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
628   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
629   }
630
631   DebugLoc DL;
632   BuildMI(MBB, MI, DL, get(Opcode));
633 }
634
635 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
636 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
637   NopInst.setOpcode(PPC::NOP);
638 }
639
640 // Branch analysis.
641 // Note: If the condition register is set to CTR or CTR8 then this is a
642 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
643 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
644                                  MachineBasicBlock *&FBB,
645                                  SmallVectorImpl<MachineOperand> &Cond,
646                                  bool AllowModify) const {
647   bool isPPC64 = Subtarget.isPPC64();
648
649   // If the block has no terminators, it just falls into the block after it.
650   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
651   if (I == MBB.end())
652     return false;
653
654   if (!isUnpredicatedTerminator(I))
655     return false;
656
657   // Get the last instruction in the block.
658   MachineInstr *LastInst = I;
659
660   // If there is only one terminator instruction, process it.
661   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
662     if (LastInst->getOpcode() == PPC::B) {
663       if (!LastInst->getOperand(0).isMBB())
664         return true;
665       TBB = LastInst->getOperand(0).getMBB();
666       return false;
667     } else if (LastInst->getOpcode() == PPC::BCC) {
668       if (!LastInst->getOperand(2).isMBB())
669         return true;
670       // Block ends with fall-through condbranch.
671       TBB = LastInst->getOperand(2).getMBB();
672       Cond.push_back(LastInst->getOperand(0));
673       Cond.push_back(LastInst->getOperand(1));
674       return false;
675     } else if (LastInst->getOpcode() == PPC::BC) {
676       if (!LastInst->getOperand(1).isMBB())
677         return true;
678       // Block ends with fall-through condbranch.
679       TBB = LastInst->getOperand(1).getMBB();
680       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
681       Cond.push_back(LastInst->getOperand(0));
682       return false;
683     } else if (LastInst->getOpcode() == PPC::BCn) {
684       if (!LastInst->getOperand(1).isMBB())
685         return true;
686       // Block ends with fall-through condbranch.
687       TBB = LastInst->getOperand(1).getMBB();
688       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
689       Cond.push_back(LastInst->getOperand(0));
690       return false;
691     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
692                LastInst->getOpcode() == PPC::BDNZ) {
693       if (!LastInst->getOperand(0).isMBB())
694         return true;
695       if (DisableCTRLoopAnal)
696         return true;
697       TBB = LastInst->getOperand(0).getMBB();
698       Cond.push_back(MachineOperand::CreateImm(1));
699       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
700                                                true));
701       return false;
702     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
703                LastInst->getOpcode() == PPC::BDZ) {
704       if (!LastInst->getOperand(0).isMBB())
705         return true;
706       if (DisableCTRLoopAnal)
707         return true;
708       TBB = LastInst->getOperand(0).getMBB();
709       Cond.push_back(MachineOperand::CreateImm(0));
710       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
711                                                true));
712       return false;
713     }
714
715     // Otherwise, don't know what this is.
716     return true;
717   }
718
719   // Get the instruction before it if it's a terminator.
720   MachineInstr *SecondLastInst = I;
721
722   // If there are three terminators, we don't know what sort of block this is.
723   if (SecondLastInst && I != MBB.begin() &&
724       isUnpredicatedTerminator(--I))
725     return true;
726
727   // If the block ends with PPC::B and PPC:BCC, handle it.
728   if (SecondLastInst->getOpcode() == PPC::BCC &&
729       LastInst->getOpcode() == PPC::B) {
730     if (!SecondLastInst->getOperand(2).isMBB() ||
731         !LastInst->getOperand(0).isMBB())
732       return true;
733     TBB =  SecondLastInst->getOperand(2).getMBB();
734     Cond.push_back(SecondLastInst->getOperand(0));
735     Cond.push_back(SecondLastInst->getOperand(1));
736     FBB = LastInst->getOperand(0).getMBB();
737     return false;
738   } else if (SecondLastInst->getOpcode() == PPC::BC &&
739       LastInst->getOpcode() == PPC::B) {
740     if (!SecondLastInst->getOperand(1).isMBB() ||
741         !LastInst->getOperand(0).isMBB())
742       return true;
743     TBB =  SecondLastInst->getOperand(1).getMBB();
744     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
745     Cond.push_back(SecondLastInst->getOperand(0));
746     FBB = LastInst->getOperand(0).getMBB();
747     return false;
748   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
749       LastInst->getOpcode() == PPC::B) {
750     if (!SecondLastInst->getOperand(1).isMBB() ||
751         !LastInst->getOperand(0).isMBB())
752       return true;
753     TBB =  SecondLastInst->getOperand(1).getMBB();
754     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
755     Cond.push_back(SecondLastInst->getOperand(0));
756     FBB = LastInst->getOperand(0).getMBB();
757     return false;
758   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
759               SecondLastInst->getOpcode() == PPC::BDNZ) &&
760       LastInst->getOpcode() == PPC::B) {
761     if (!SecondLastInst->getOperand(0).isMBB() ||
762         !LastInst->getOperand(0).isMBB())
763       return true;
764     if (DisableCTRLoopAnal)
765       return true;
766     TBB = SecondLastInst->getOperand(0).getMBB();
767     Cond.push_back(MachineOperand::CreateImm(1));
768     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
769                                              true));
770     FBB = LastInst->getOperand(0).getMBB();
771     return false;
772   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
773               SecondLastInst->getOpcode() == PPC::BDZ) &&
774       LastInst->getOpcode() == PPC::B) {
775     if (!SecondLastInst->getOperand(0).isMBB() ||
776         !LastInst->getOperand(0).isMBB())
777       return true;
778     if (DisableCTRLoopAnal)
779       return true;
780     TBB = SecondLastInst->getOperand(0).getMBB();
781     Cond.push_back(MachineOperand::CreateImm(0));
782     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
783                                              true));
784     FBB = LastInst->getOperand(0).getMBB();
785     return false;
786   }
787
788   // If the block ends with two PPC:Bs, handle it.  The second one is not
789   // executed, so remove it.
790   if (SecondLastInst->getOpcode() == PPC::B &&
791       LastInst->getOpcode() == PPC::B) {
792     if (!SecondLastInst->getOperand(0).isMBB())
793       return true;
794     TBB = SecondLastInst->getOperand(0).getMBB();
795     I = LastInst;
796     if (AllowModify)
797       I->eraseFromParent();
798     return false;
799   }
800
801   // Otherwise, can't handle this.
802   return true;
803 }
804
805 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
806   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
807   if (I == MBB.end())
808     return 0;
809
810   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
811       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
812       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
813       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
814     return 0;
815
816   // Remove the branch.
817   I->eraseFromParent();
818
819   I = MBB.end();
820
821   if (I == MBB.begin()) return 1;
822   --I;
823   if (I->getOpcode() != PPC::BCC &&
824       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
825       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
826       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
827     return 1;
828
829   // Remove the branch.
830   I->eraseFromParent();
831   return 2;
832 }
833
834 unsigned
835 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
836                            MachineBasicBlock *FBB,
837                            ArrayRef<MachineOperand> Cond,
838                            DebugLoc DL) const {
839   // Shouldn't be a fall through.
840   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
841   assert((Cond.size() == 2 || Cond.size() == 0) &&
842          "PPC branch conditions have two components!");
843
844   bool isPPC64 = Subtarget.isPPC64();
845
846   // One-way branch.
847   if (!FBB) {
848     if (Cond.empty())   // Unconditional branch
849       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
850     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
851       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
852                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
853                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
854     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
855       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
856     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
857       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
858     else                // Conditional branch
859       BuildMI(&MBB, DL, get(PPC::BCC))
860         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
861     return 1;
862   }
863
864   // Two-way Conditional Branch.
865   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
866     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
867                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
868                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
869   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
870     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
871   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
872     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
873   else
874     BuildMI(&MBB, DL, get(PPC::BCC))
875       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
876   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
877   return 2;
878 }
879
880 // Select analysis.
881 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
882                 ArrayRef<MachineOperand> Cond,
883                 unsigned TrueReg, unsigned FalseReg,
884                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
885   if (!Subtarget.hasISEL())
886     return false;
887
888   if (Cond.size() != 2)
889     return false;
890
891   // If this is really a bdnz-like condition, then it cannot be turned into a
892   // select.
893   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
894     return false;
895
896   // Check register classes.
897   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
898   const TargetRegisterClass *RC =
899     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
900   if (!RC)
901     return false;
902
903   // isel is for regular integer GPRs only.
904   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
905       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
906       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
907       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
908     return false;
909
910   // FIXME: These numbers are for the A2, how well they work for other cores is
911   // an open question. On the A2, the isel instruction has a 2-cycle latency
912   // but single-cycle throughput. These numbers are used in combination with
913   // the MispredictPenalty setting from the active SchedMachineModel.
914   CondCycles = 1;
915   TrueCycles = 1;
916   FalseCycles = 1;
917
918   return true;
919 }
920
921 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
922                                 MachineBasicBlock::iterator MI, DebugLoc dl,
923                                 unsigned DestReg, ArrayRef<MachineOperand> Cond,
924                                 unsigned TrueReg, unsigned FalseReg) const {
925   assert(Cond.size() == 2 &&
926          "PPC branch conditions have two components!");
927
928   assert(Subtarget.hasISEL() &&
929          "Cannot insert select on target without ISEL support");
930
931   // Get the register classes.
932   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
933   const TargetRegisterClass *RC =
934     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
935   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
936
937   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
938                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
939   assert((Is64Bit ||
940           PPC::GPRCRegClass.hasSubClassEq(RC) ||
941           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
942          "isel is for regular integer GPRs only");
943
944   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
945   unsigned SelectPred = Cond[0].getImm();
946
947   unsigned SubIdx;
948   bool SwapOps;
949   switch (SelectPred) {
950   default: llvm_unreachable("invalid predicate for isel");
951   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
952   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
953   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
954   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
955   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
956   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
957   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
958   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
959   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
960   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
961   }
962
963   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
964            SecondReg = SwapOps ? TrueReg  : FalseReg;
965
966   // The first input register of isel cannot be r0. If it is a member
967   // of a register class that can be r0, then copy it first (the
968   // register allocator should eliminate the copy).
969   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
970       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
971     const TargetRegisterClass *FirstRC =
972       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
973         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
974     unsigned OldFirstReg = FirstReg;
975     FirstReg = MRI.createVirtualRegister(FirstRC);
976     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
977       .addReg(OldFirstReg);
978   }
979
980   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
981     .addReg(FirstReg).addReg(SecondReg)
982     .addReg(Cond[1].getReg(), 0, SubIdx);
983 }
984
985 static unsigned getCRBitValue(unsigned CRBit) {
986   unsigned Ret = 4;
987   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
988       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
989       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
990       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
991     Ret = 3;
992   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
993       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
994       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
995       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
996     Ret = 2;
997   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
998       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
999       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
1000       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
1001     Ret = 1;
1002   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
1003       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
1004       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
1005       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
1006     Ret = 0;
1007
1008   assert(Ret != 4 && "Invalid CR bit register");
1009   return Ret;
1010 }
1011
1012 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
1013                                MachineBasicBlock::iterator I, DebugLoc DL,
1014                                unsigned DestReg, unsigned SrcReg,
1015                                bool KillSrc) const {
1016   // We can end up with self copies and similar things as a result of VSX copy
1017   // legalization. Promote them here.
1018   const TargetRegisterInfo *TRI = &getRegisterInfo();
1019   if (PPC::F8RCRegClass.contains(DestReg) &&
1020       PPC::VSRCRegClass.contains(SrcReg)) {
1021     unsigned SuperReg =
1022       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
1023
1024     if (VSXSelfCopyCrash && SrcReg == SuperReg)
1025       llvm_unreachable("nop VSX copy");
1026
1027     DestReg = SuperReg;
1028   } else if (PPC::VRRCRegClass.contains(DestReg) &&
1029              PPC::VSRCRegClass.contains(SrcReg)) {
1030     unsigned SuperReg =
1031       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
1032
1033     if (VSXSelfCopyCrash && SrcReg == SuperReg)
1034       llvm_unreachable("nop VSX copy");
1035
1036     DestReg = SuperReg;
1037   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
1038              PPC::VSRCRegClass.contains(DestReg)) {
1039     unsigned SuperReg =
1040       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
1041
1042     if (VSXSelfCopyCrash && DestReg == SuperReg)
1043       llvm_unreachable("nop VSX copy");
1044
1045     SrcReg = SuperReg;
1046   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
1047              PPC::VSRCRegClass.contains(DestReg)) {
1048     unsigned SuperReg =
1049       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
1050
1051     if (VSXSelfCopyCrash && DestReg == SuperReg)
1052       llvm_unreachable("nop VSX copy");
1053
1054     SrcReg = SuperReg;
1055   }
1056
1057   // Different class register copy
1058   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
1059       PPC::GPRCRegClass.contains(DestReg)) {
1060     unsigned CRReg = getCRFromCRBit(SrcReg);
1061     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
1062        .addReg(CRReg), getKillRegState(KillSrc);
1063     // Rotate the CR bit in the CR fields to be the least significant bit and
1064     // then mask with 0x1 (MB = ME = 31).
1065     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
1066        .addReg(DestReg, RegState::Kill)
1067        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
1068        .addImm(31)
1069        .addImm(31);
1070     return;
1071   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
1072       PPC::G8RCRegClass.contains(DestReg)) {
1073     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg)
1074        .addReg(SrcReg), getKillRegState(KillSrc);
1075     return;
1076   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
1077       PPC::GPRCRegClass.contains(DestReg)) {
1078     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
1079        .addReg(SrcReg), getKillRegState(KillSrc);
1080     return;
1081    }
1082
1083   unsigned Opc;
1084   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
1085     Opc = PPC::OR;
1086   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
1087     Opc = PPC::OR8;
1088   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
1089     Opc = PPC::FMR;
1090   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
1091     Opc = PPC::MCRF;
1092   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
1093     Opc = PPC::VOR;
1094   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
1095     // There are two different ways this can be done:
1096     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1097     //      issue in VSU pipeline 0.
1098     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1099     //      can go to either pipeline.
1100     // We'll always use xxlor here, because in practically all cases where
1101     // copies are generated, they are close enough to some use that the
1102     // lower-latency form is preferable.
1103     Opc = PPC::XXLOR;
1104   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1105            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1106     Opc = PPC::XXLORf;
1107   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
1108     Opc = PPC::QVFMR;
1109   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
1110     Opc = PPC::QVFMRs;
1111   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
1112     Opc = PPC::QVFMRb;
1113   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1114     Opc = PPC::CROR;
1115   else
1116     llvm_unreachable("Impossible reg-to-reg copy");
1117
1118   const MCInstrDesc &MCID = get(Opc);
1119   if (MCID.getNumOperands() == 3)
1120     BuildMI(MBB, I, DL, MCID, DestReg)
1121       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1122   else
1123     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1124 }
1125
1126 // This function returns true if a CR spill is necessary and false otherwise.
1127 bool
1128 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
1129                                   unsigned SrcReg, bool isKill,
1130                                   int FrameIdx,
1131                                   const TargetRegisterClass *RC,
1132                                   SmallVectorImpl<MachineInstr*> &NewMIs,
1133                                   bool &NonRI, bool &SpillsVRS) const{
1134   // Note: If additional store instructions are added here,
1135   // update isStoreToStackSlot.
1136
1137   DebugLoc DL;
1138   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1139       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1140     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
1141                                        .addReg(SrcReg,
1142                                                getKillRegState(isKill)),
1143                                        FrameIdx));
1144   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1145              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1146     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
1147                                        .addReg(SrcReg,
1148                                                getKillRegState(isKill)),
1149                                        FrameIdx));
1150   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1151     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
1152                                        .addReg(SrcReg,
1153                                                getKillRegState(isKill)),
1154                                        FrameIdx));
1155   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1156     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
1157                                        .addReg(SrcReg,
1158                                                getKillRegState(isKill)),
1159                                        FrameIdx));
1160   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1161     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
1162                                        .addReg(SrcReg,
1163                                                getKillRegState(isKill)),
1164                                        FrameIdx));
1165     return true;
1166   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1167     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
1168                                        .addReg(SrcReg,
1169                                                getKillRegState(isKill)),
1170                                        FrameIdx));
1171     return true;
1172   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1173     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
1174                                        .addReg(SrcReg,
1175                                                getKillRegState(isKill)),
1176                                        FrameIdx));
1177     NonRI = true;
1178   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1179     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
1180                                        .addReg(SrcReg,
1181                                                getKillRegState(isKill)),
1182                                        FrameIdx));
1183     NonRI = true;
1184   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1185     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
1186                                        .addReg(SrcReg,
1187                                                getKillRegState(isKill)),
1188                                        FrameIdx));
1189     NonRI = true;
1190   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1191     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSSPX))
1192                                        .addReg(SrcReg,
1193                                                getKillRegState(isKill)),
1194                                        FrameIdx));
1195     NonRI = true;
1196   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1197     assert(Subtarget.isDarwin() &&
1198            "VRSAVE only needs spill/restore on Darwin");
1199     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
1200                                        .addReg(SrcReg,
1201                                                getKillRegState(isKill)),
1202                                        FrameIdx));
1203     SpillsVRS = true;
1204   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1205     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
1206                                        .addReg(SrcReg,
1207                                                getKillRegState(isKill)),
1208                                        FrameIdx));
1209     NonRI = true;
1210   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1211     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
1212                                        .addReg(SrcReg,
1213                                                getKillRegState(isKill)),
1214                                        FrameIdx));
1215     NonRI = true;
1216   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1217     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
1218                                        .addReg(SrcReg,
1219                                                getKillRegState(isKill)),
1220                                        FrameIdx));
1221     NonRI = true;
1222   } else {
1223     llvm_unreachable("Unknown regclass!");
1224   }
1225
1226   return false;
1227 }
1228
1229 void
1230 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1231                                   MachineBasicBlock::iterator MI,
1232                                   unsigned SrcReg, bool isKill, int FrameIdx,
1233                                   const TargetRegisterClass *RC,
1234                                   const TargetRegisterInfo *TRI) const {
1235   MachineFunction &MF = *MBB.getParent();
1236   SmallVector<MachineInstr*, 4> NewMIs;
1237
1238   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1239   FuncInfo->setHasSpills();
1240
1241   bool NonRI = false, SpillsVRS = false;
1242   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
1243                           NonRI, SpillsVRS))
1244     FuncInfo->setSpillsCR();
1245
1246   if (SpillsVRS)
1247     FuncInfo->setSpillsVRSAVE();
1248
1249   if (NonRI)
1250     FuncInfo->setHasNonRISpills();
1251
1252   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1253     MBB.insert(MI, NewMIs[i]);
1254
1255   const MachineFrameInfo &MFI = *MF.getFrameInfo();
1256   MachineMemOperand *MMO = MF.getMachineMemOperand(
1257       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1258       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1259       MFI.getObjectAlignment(FrameIdx));
1260   NewMIs.back()->addMemOperand(MF, MMO);
1261 }
1262
1263 bool
1264 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
1265                                    unsigned DestReg, int FrameIdx,
1266                                    const TargetRegisterClass *RC,
1267                                    SmallVectorImpl<MachineInstr*> &NewMIs,
1268                                    bool &NonRI, bool &SpillsVRS) const{
1269   // Note: If additional load instructions are added here,
1270   // update isLoadFromStackSlot.
1271
1272   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1273       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1274     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
1275                                                DestReg), FrameIdx));
1276   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1277              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1278     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
1279                                        FrameIdx));
1280   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1281     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
1282                                        FrameIdx));
1283   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1284     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
1285                                        FrameIdx));
1286   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1287     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1288                                                get(PPC::RESTORE_CR), DestReg),
1289                                        FrameIdx));
1290     return true;
1291   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1292     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1293                                                get(PPC::RESTORE_CRBIT), DestReg),
1294                                        FrameIdx));
1295     return true;
1296   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1297     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
1298                                        FrameIdx));
1299     NonRI = true;
1300   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1301     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
1302                                        FrameIdx));
1303     NonRI = true;
1304   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1305     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
1306                                        FrameIdx));
1307     NonRI = true;
1308   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1309     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSSPX), DestReg),
1310                                        FrameIdx));
1311     NonRI = true;
1312   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1313     assert(Subtarget.isDarwin() &&
1314            "VRSAVE only needs spill/restore on Darwin");
1315     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1316                                                get(PPC::RESTORE_VRSAVE),
1317                                                DestReg),
1318                                        FrameIdx));
1319     SpillsVRS = true;
1320   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1321     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
1322                                        FrameIdx));
1323     NonRI = true;
1324   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1325     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
1326                                        FrameIdx));
1327     NonRI = true;
1328   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1329     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
1330                                        FrameIdx));
1331     NonRI = true;
1332   } else {
1333     llvm_unreachable("Unknown regclass!");
1334   }
1335
1336   return false;
1337 }
1338
1339 void
1340 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1341                                    MachineBasicBlock::iterator MI,
1342                                    unsigned DestReg, int FrameIdx,
1343                                    const TargetRegisterClass *RC,
1344                                    const TargetRegisterInfo *TRI) const {
1345   MachineFunction &MF = *MBB.getParent();
1346   SmallVector<MachineInstr*, 4> NewMIs;
1347   DebugLoc DL;
1348   if (MI != MBB.end()) DL = MI->getDebugLoc();
1349
1350   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1351   FuncInfo->setHasSpills();
1352
1353   bool NonRI = false, SpillsVRS = false;
1354   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
1355                            NonRI, SpillsVRS))
1356     FuncInfo->setSpillsCR();
1357
1358   if (SpillsVRS)
1359     FuncInfo->setSpillsVRSAVE();
1360
1361   if (NonRI)
1362     FuncInfo->setHasNonRISpills();
1363
1364   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1365     MBB.insert(MI, NewMIs[i]);
1366
1367   const MachineFrameInfo &MFI = *MF.getFrameInfo();
1368   MachineMemOperand *MMO = MF.getMachineMemOperand(
1369       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1370       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1371       MFI.getObjectAlignment(FrameIdx));
1372   NewMIs.back()->addMemOperand(MF, MMO);
1373 }
1374
1375 bool PPCInstrInfo::
1376 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1377   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1378   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1379     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1380   else
1381     // Leave the CR# the same, but invert the condition.
1382     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1383   return false;
1384 }
1385
1386 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
1387                              unsigned Reg, MachineRegisterInfo *MRI) const {
1388   // For some instructions, it is legal to fold ZERO into the RA register field.
1389   // A zero immediate should always be loaded with a single li.
1390   unsigned DefOpc = DefMI->getOpcode();
1391   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1392     return false;
1393   if (!DefMI->getOperand(1).isImm())
1394     return false;
1395   if (DefMI->getOperand(1).getImm() != 0)
1396     return false;
1397
1398   // Note that we cannot here invert the arguments of an isel in order to fold
1399   // a ZERO into what is presented as the second argument. All we have here
1400   // is the condition bit, and that might come from a CR-logical bit operation.
1401
1402   const MCInstrDesc &UseMCID = UseMI->getDesc();
1403
1404   // Only fold into real machine instructions.
1405   if (UseMCID.isPseudo())
1406     return false;
1407
1408   unsigned UseIdx;
1409   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1410     if (UseMI->getOperand(UseIdx).isReg() &&
1411         UseMI->getOperand(UseIdx).getReg() == Reg)
1412       break;
1413
1414   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1415   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1416
1417   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1418
1419   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1420   // register (which might also be specified as a pointer class kind).
1421   if (UseInfo->isLookupPtrRegClass()) {
1422     if (UseInfo->RegClass /* Kind */ != 1)
1423       return false;
1424   } else {
1425     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1426         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1427       return false;
1428   }
1429
1430   // Make sure this is not tied to an output register (or otherwise
1431   // constrained). This is true for ST?UX registers, for example, which
1432   // are tied to their output registers.
1433   if (UseInfo->Constraints != 0)
1434     return false;
1435
1436   unsigned ZeroReg;
1437   if (UseInfo->isLookupPtrRegClass()) {
1438     bool isPPC64 = Subtarget.isPPC64();
1439     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1440   } else {
1441     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1442               PPC::ZERO8 : PPC::ZERO;
1443   }
1444
1445   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1446   UseMI->getOperand(UseIdx).setReg(ZeroReg);
1447
1448   if (DeleteDef)
1449     DefMI->eraseFromParent();
1450
1451   return true;
1452 }
1453
1454 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1455   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1456        I != IE; ++I)
1457     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1458       return true;
1459   return false;
1460 }
1461
1462 // We should make sure that, if we're going to predicate both sides of a
1463 // condition (a diamond), that both sides don't define the counter register. We
1464 // can predicate counter-decrement-based branches, but while that predicates
1465 // the branching, it does not predicate the counter decrement. If we tried to
1466 // merge the triangle into one predicated block, we'd decrement the counter
1467 // twice.
1468 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1469                      unsigned NumT, unsigned ExtraT,
1470                      MachineBasicBlock &FMBB,
1471                      unsigned NumF, unsigned ExtraF,
1472                      const BranchProbability &Probability) const {
1473   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1474 }
1475
1476
1477 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1478   // The predicated branches are identified by their type, not really by the
1479   // explicit presence of a predicate. Furthermore, some of them can be
1480   // predicated more than once. Because if conversion won't try to predicate
1481   // any instruction which already claims to be predicated (by returning true
1482   // here), always return false. In doing so, we let isPredicable() be the
1483   // final word on whether not the instruction can be (further) predicated.
1484
1485   return false;
1486 }
1487
1488 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1489   if (!MI->isTerminator())
1490     return false;
1491
1492   // Conditional branch is a special case.
1493   if (MI->isBranch() && !MI->isBarrier())
1494     return true;
1495
1496   return !isPredicated(MI);
1497 }
1498
1499 bool PPCInstrInfo::PredicateInstruction(MachineInstr *MI,
1500                                         ArrayRef<MachineOperand> Pred) const {
1501   unsigned OpC = MI->getOpcode();
1502   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1503     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1504       bool isPPC64 = Subtarget.isPPC64();
1505       MI->setDesc(get(Pred[0].getImm() ?
1506                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1507                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
1508     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1509       MI->setDesc(get(PPC::BCLR));
1510       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1511         .addReg(Pred[1].getReg());
1512     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1513       MI->setDesc(get(PPC::BCLRn));
1514       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1515         .addReg(Pred[1].getReg());
1516     } else {
1517       MI->setDesc(get(PPC::BCCLR));
1518       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1519         .addImm(Pred[0].getImm())
1520         .addReg(Pred[1].getReg());
1521     }
1522
1523     return true;
1524   } else if (OpC == PPC::B) {
1525     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1526       bool isPPC64 = Subtarget.isPPC64();
1527       MI->setDesc(get(Pred[0].getImm() ?
1528                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1529                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
1530     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1531       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1532       MI->RemoveOperand(0);
1533
1534       MI->setDesc(get(PPC::BC));
1535       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1536         .addReg(Pred[1].getReg())
1537         .addMBB(MBB);
1538     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1539       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1540       MI->RemoveOperand(0);
1541
1542       MI->setDesc(get(PPC::BCn));
1543       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1544         .addReg(Pred[1].getReg())
1545         .addMBB(MBB);
1546     } else {
1547       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1548       MI->RemoveOperand(0);
1549
1550       MI->setDesc(get(PPC::BCC));
1551       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1552         .addImm(Pred[0].getImm())
1553         .addReg(Pred[1].getReg())
1554         .addMBB(MBB);
1555     }
1556
1557     return true;
1558   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1559              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1560     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1561       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1562
1563     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1564     bool isPPC64 = Subtarget.isPPC64();
1565
1566     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1567       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1568                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
1569       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1570         .addReg(Pred[1].getReg());
1571       return true;
1572     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1573       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1574                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
1575       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1576         .addReg(Pred[1].getReg());
1577       return true;
1578     }
1579
1580     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1581                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
1582     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1583       .addImm(Pred[0].getImm())
1584       .addReg(Pred[1].getReg());
1585     return true;
1586   }
1587
1588   return false;
1589 }
1590
1591 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1592                                      ArrayRef<MachineOperand> Pred2) const {
1593   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1594   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1595
1596   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1597     return false;
1598   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1599     return false;
1600
1601   // P1 can only subsume P2 if they test the same condition register.
1602   if (Pred1[1].getReg() != Pred2[1].getReg())
1603     return false;
1604
1605   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1606   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1607
1608   if (P1 == P2)
1609     return true;
1610
1611   // Does P1 subsume P2, e.g. GE subsumes GT.
1612   if (P1 == PPC::PRED_LE &&
1613       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1614     return true;
1615   if (P1 == PPC::PRED_GE &&
1616       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1617     return true;
1618
1619   return false;
1620 }
1621
1622 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1623                                     std::vector<MachineOperand> &Pred) const {
1624   // Note: At the present time, the contents of Pred from this function is
1625   // unused by IfConversion. This implementation follows ARM by pushing the
1626   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1627   // predicate, instructions defining CTR or CTR8 are also included as
1628   // predicate-defining instructions.
1629
1630   const TargetRegisterClass *RCs[] =
1631     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1632       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1633
1634   bool Found = false;
1635   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1636     const MachineOperand &MO = MI->getOperand(i);
1637     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1638       const TargetRegisterClass *RC = RCs[c];
1639       if (MO.isReg()) {
1640         if (MO.isDef() && RC->contains(MO.getReg())) {
1641           Pred.push_back(MO);
1642           Found = true;
1643         }
1644       } else if (MO.isRegMask()) {
1645         for (TargetRegisterClass::iterator I = RC->begin(),
1646              IE = RC->end(); I != IE; ++I)
1647           if (MO.clobbersPhysReg(*I)) {
1648             Pred.push_back(MO);
1649             Found = true;
1650           }
1651       }
1652     }
1653   }
1654
1655   return Found;
1656 }
1657
1658 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1659   unsigned OpC = MI->getOpcode();
1660   switch (OpC) {
1661   default:
1662     return false;
1663   case PPC::B:
1664   case PPC::BLR:
1665   case PPC::BLR8:
1666   case PPC::BCTR:
1667   case PPC::BCTR8:
1668   case PPC::BCTRL:
1669   case PPC::BCTRL8:
1670     return true;
1671   }
1672 }
1673
1674 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1675                                   unsigned &SrcReg, unsigned &SrcReg2,
1676                                   int &Mask, int &Value) const {
1677   unsigned Opc = MI->getOpcode();
1678
1679   switch (Opc) {
1680   default: return false;
1681   case PPC::CMPWI:
1682   case PPC::CMPLWI:
1683   case PPC::CMPDI:
1684   case PPC::CMPLDI:
1685     SrcReg = MI->getOperand(1).getReg();
1686     SrcReg2 = 0;
1687     Value = MI->getOperand(2).getImm();
1688     Mask = 0xFFFF;
1689     return true;
1690   case PPC::CMPW:
1691   case PPC::CMPLW:
1692   case PPC::CMPD:
1693   case PPC::CMPLD:
1694   case PPC::FCMPUS:
1695   case PPC::FCMPUD:
1696     SrcReg = MI->getOperand(1).getReg();
1697     SrcReg2 = MI->getOperand(2).getReg();
1698     return true;
1699   }
1700 }
1701
1702 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1703                                         unsigned SrcReg, unsigned SrcReg2,
1704                                         int Mask, int Value,
1705                                         const MachineRegisterInfo *MRI) const {
1706   if (DisableCmpOpt)
1707     return false;
1708
1709   int OpC = CmpInstr->getOpcode();
1710   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1711
1712   // FP record forms set CR1 based on the execption status bits, not a
1713   // comparison with zero.
1714   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1715     return false;
1716
1717   // The record forms set the condition register based on a signed comparison
1718   // with zero (so says the ISA manual). This is not as straightforward as it
1719   // seems, however, because this is always a 64-bit comparison on PPC64, even
1720   // for instructions that are 32-bit in nature (like slw for example).
1721   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1722   // for equality checks (as those don't depend on the sign). On PPC64,
1723   // we are restricted to equality for unsigned 64-bit comparisons and for
1724   // signed 32-bit comparisons the applicability is more restricted.
1725   bool isPPC64 = Subtarget.isPPC64();
1726   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1727   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1728   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1729
1730   // Get the unique definition of SrcReg.
1731   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1732   if (!MI) return false;
1733   int MIOpC = MI->getOpcode();
1734
1735   bool equalityOnly = false;
1736   bool noSub = false;
1737   if (isPPC64) {
1738     if (is32BitSignedCompare) {
1739       // We can perform this optimization only if MI is sign-extending.
1740       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1741           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1742           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1743           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1744           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1745         noSub = true;
1746       } else
1747         return false;
1748     } else if (is32BitUnsignedCompare) {
1749       // We can perform this optimization, equality only, if MI is
1750       // zero-extending.
1751       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1752           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1753           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1754         noSub = true;
1755         equalityOnly = true;
1756       } else
1757         return false;
1758     } else
1759       equalityOnly = is64BitUnsignedCompare;
1760   } else
1761     equalityOnly = is32BitUnsignedCompare;
1762
1763   if (equalityOnly) {
1764     // We need to check the uses of the condition register in order to reject
1765     // non-equality comparisons.
1766     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1767          IE = MRI->use_instr_end(); I != IE; ++I) {
1768       MachineInstr *UseMI = &*I;
1769       if (UseMI->getOpcode() == PPC::BCC) {
1770         unsigned Pred = UseMI->getOperand(0).getImm();
1771         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1772           return false;
1773       } else if (UseMI->getOpcode() == PPC::ISEL ||
1774                  UseMI->getOpcode() == PPC::ISEL8) {
1775         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1776         if (SubIdx != PPC::sub_eq)
1777           return false;
1778       } else
1779         return false;
1780     }
1781   }
1782
1783   MachineBasicBlock::iterator I = CmpInstr;
1784
1785   // Scan forward to find the first use of the compare.
1786   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1787        I != EL; ++I) {
1788     bool FoundUse = false;
1789     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1790          JE = MRI->use_instr_end(); J != JE; ++J)
1791       if (&*J == &*I) {
1792         FoundUse = true;
1793         break;
1794       }
1795
1796     if (FoundUse)
1797       break;
1798   }
1799
1800   // There are two possible candidates which can be changed to set CR[01].
1801   // One is MI, the other is a SUB instruction.
1802   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1803   MachineInstr *Sub = nullptr;
1804   if (SrcReg2 != 0)
1805     // MI is not a candidate for CMPrr.
1806     MI = nullptr;
1807   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1808   // same BB as the comparison. This is to allow the check below to avoid calls
1809   // (and other explicit clobbers); instead we should really check for these
1810   // more explicitly (in at least a few predecessors).
1811   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1812     // PPC does not have a record-form SUBri.
1813     return false;
1814   }
1815
1816   // Search for Sub.
1817   const TargetRegisterInfo *TRI = &getRegisterInfo();
1818   --I;
1819
1820   // Get ready to iterate backward from CmpInstr.
1821   MachineBasicBlock::iterator E = MI,
1822                               B = CmpInstr->getParent()->begin();
1823
1824   for (; I != E && !noSub; --I) {
1825     const MachineInstr &Instr = *I;
1826     unsigned IOpC = Instr.getOpcode();
1827
1828     if (&*I != CmpInstr && (
1829         Instr.modifiesRegister(PPC::CR0, TRI) ||
1830         Instr.readsRegister(PPC::CR0, TRI)))
1831       // This instruction modifies or uses the record condition register after
1832       // the one we want to change. While we could do this transformation, it
1833       // would likely not be profitable. This transformation removes one
1834       // instruction, and so even forcing RA to generate one move probably
1835       // makes it unprofitable.
1836       return false;
1837
1838     // Check whether CmpInstr can be made redundant by the current instruction.
1839     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1840          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1841         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1842         ((Instr.getOperand(1).getReg() == SrcReg &&
1843           Instr.getOperand(2).getReg() == SrcReg2) ||
1844         (Instr.getOperand(1).getReg() == SrcReg2 &&
1845          Instr.getOperand(2).getReg() == SrcReg))) {
1846       Sub = &*I;
1847       break;
1848     }
1849
1850     if (I == B)
1851       // The 'and' is below the comparison instruction.
1852       return false;
1853   }
1854
1855   // Return false if no candidates exist.
1856   if (!MI && !Sub)
1857     return false;
1858
1859   // The single candidate is called MI.
1860   if (!MI) MI = Sub;
1861
1862   int NewOpC = -1;
1863   MIOpC = MI->getOpcode();
1864   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1865     NewOpC = MIOpC;
1866   else {
1867     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1868     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1869       NewOpC = MIOpC;
1870   }
1871
1872   // FIXME: On the non-embedded POWER architectures, only some of the record
1873   // forms are fast, and we should use only the fast ones.
1874
1875   // The defining instruction has a record form (or is already a record
1876   // form). It is possible, however, that we'll need to reverse the condition
1877   // code of the users.
1878   if (NewOpC == -1)
1879     return false;
1880
1881   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1882   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1883
1884   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1885   // needs to be updated to be based on SUB.  Push the condition code
1886   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1887   // condition code of these operands will be modified.
1888   bool ShouldSwap = false;
1889   if (Sub) {
1890     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1891       Sub->getOperand(2).getReg() == SrcReg;
1892
1893     // The operands to subf are the opposite of sub, so only in the fixed-point
1894     // case, invert the order.
1895     ShouldSwap = !ShouldSwap;
1896   }
1897
1898   if (ShouldSwap)
1899     for (MachineRegisterInfo::use_instr_iterator
1900          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1901          I != IE; ++I) {
1902       MachineInstr *UseMI = &*I;
1903       if (UseMI->getOpcode() == PPC::BCC) {
1904         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1905         assert((!equalityOnly ||
1906                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1907                "Invalid predicate for equality-only optimization");
1908         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1909                                 PPC::getSwappedPredicate(Pred)));
1910       } else if (UseMI->getOpcode() == PPC::ISEL ||
1911                  UseMI->getOpcode() == PPC::ISEL8) {
1912         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1913         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1914                "Invalid CR bit for equality-only optimization");
1915
1916         if (NewSubReg == PPC::sub_lt)
1917           NewSubReg = PPC::sub_gt;
1918         else if (NewSubReg == PPC::sub_gt)
1919           NewSubReg = PPC::sub_lt;
1920
1921         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1922                                                  NewSubReg));
1923       } else // We need to abort on a user we don't understand.
1924         return false;
1925     }
1926
1927   // Create a new virtual register to hold the value of the CR set by the
1928   // record-form instruction. If the instruction was not previously in
1929   // record form, then set the kill flag on the CR.
1930   CmpInstr->eraseFromParent();
1931
1932   MachineBasicBlock::iterator MII = MI;
1933   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1934           get(TargetOpcode::COPY), CRReg)
1935     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1936
1937   if (MIOpC != NewOpC) {
1938     // We need to be careful here: we're replacing one instruction with
1939     // another, and we need to make sure that we get all of the right
1940     // implicit uses and defs. On the other hand, the caller may be holding
1941     // an iterator to this instruction, and so we can't delete it (this is
1942     // specifically the case if this is the instruction directly after the
1943     // compare).
1944
1945     const MCInstrDesc &NewDesc = get(NewOpC);
1946     MI->setDesc(NewDesc);
1947
1948     if (NewDesc.ImplicitDefs)
1949       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1950            *ImpDefs; ++ImpDefs)
1951         if (!MI->definesRegister(*ImpDefs))
1952           MI->addOperand(*MI->getParent()->getParent(),
1953                          MachineOperand::CreateReg(*ImpDefs, true, true));
1954     if (NewDesc.ImplicitUses)
1955       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1956            *ImpUses; ++ImpUses)
1957         if (!MI->readsRegister(*ImpUses))
1958           MI->addOperand(*MI->getParent()->getParent(),
1959                          MachineOperand::CreateReg(*ImpUses, false, true));
1960   }
1961
1962   // Modify the condition code of operands in OperandsToUpdate.
1963   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1964   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1965   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1966     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1967
1968   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1969     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1970
1971   return true;
1972 }
1973
1974 /// GetInstSize - Return the number of bytes of code the specified
1975 /// instruction may be.  This returns the maximum number of bytes.
1976 ///
1977 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1978   unsigned Opcode = MI->getOpcode();
1979
1980   if (Opcode == PPC::INLINEASM) {
1981     const MachineFunction *MF = MI->getParent()->getParent();
1982     const char *AsmStr = MI->getOperand(0).getSymbolName();
1983     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1984   } else if (Opcode == TargetOpcode::STACKMAP) {
1985     return MI->getOperand(1).getImm();
1986   } else if (Opcode == TargetOpcode::PATCHPOINT) {
1987     PatchPointOpers Opers(MI);
1988     return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
1989   } else {
1990     const MCInstrDesc &Desc = get(Opcode);
1991     return Desc.getSize();
1992   }
1993 }
1994
1995 std::pair<unsigned, unsigned>
1996 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1997   const unsigned Mask = PPCII::MO_ACCESS_MASK;
1998   return std::make_pair(TF & Mask, TF & ~Mask);
1999 }
2000
2001 ArrayRef<std::pair<unsigned, const char *>>
2002 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2003   using namespace PPCII;
2004   static const std::pair<unsigned, const char *> TargetFlags[] = {
2005       {MO_LO, "ppc-lo"},
2006       {MO_HA, "ppc-ha"},
2007       {MO_TPREL_LO, "ppc-tprel-lo"},
2008       {MO_TPREL_HA, "ppc-tprel-ha"},
2009       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2010       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2011       {MO_TOC_LO, "ppc-toc-lo"},
2012       {MO_TLS, "ppc-tls"}};
2013   return makeArrayRef(TargetFlags);
2014 }
2015
2016 ArrayRef<std::pair<unsigned, const char *>>
2017 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2018   using namespace PPCII;
2019   static const std::pair<unsigned, const char *> TargetFlags[] = {
2020       {MO_PLT_OR_STUB, "ppc-plt-or-stub"},
2021       {MO_PIC_FLAG, "ppc-pic"},
2022       {MO_NLP_FLAG, "ppc-nlp"},
2023       {MO_NLP_HIDDEN_FLAG, "ppc-nlp-hidden"}};
2024   return makeArrayRef(TargetFlags);
2025 }
2026