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