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