1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the PowerPC implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCInstrInfo.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCHazardRecognizers.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/CodeGen/ScheduleDAG.h"
30 #include "llvm/CodeGen/SlotIndexes.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "ppc-instr-info"
43 
44 #define GET_INSTRMAP_INFO
45 #define GET_INSTRINFO_CTOR_DTOR
46 #include "PPCGenInstrInfo.inc"
47 
48 STATISTIC(NumStoreSPILLVSRRCAsVec,
49           "Number of spillvsrrc spilled to stack as vec");
50 STATISTIC(NumStoreSPILLVSRRCAsGpr,
51           "Number of spillvsrrc spilled to stack as gpr");
52 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
53 STATISTIC(CmpIselsConverted,
54           "Number of ISELs that depend on comparison of constants converted");
55 STATISTIC(MissedConvertibleImmediateInstrs,
56           "Number of compare-immediate instructions fed by constants");
57 STATISTIC(NumRcRotatesConvertedToRcAnd,
58           "Number of record-form rotates converted to record-form andi");
59 
60 static cl::
61 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
62             cl::desc("Disable analysis for CTR loops"));
63 
64 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
65 cl::desc("Disable compare instruction optimization"), cl::Hidden);
66 
67 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
68 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
69 cl::Hidden);
70 
71 static cl::opt<bool>
72 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
73   cl::desc("Use the old (incorrect) instruction latency calculation"));
74 
75 // Index into the OpcodesForSpill array.
76 enum SpillOpcodeKey {
77   SOK_Int4Spill,
78   SOK_Int8Spill,
79   SOK_Float8Spill,
80   SOK_Float4Spill,
81   SOK_CRSpill,
82   SOK_CRBitSpill,
83   SOK_VRVectorSpill,
84   SOK_VSXVectorSpill,
85   SOK_VectorFloat8Spill,
86   SOK_VectorFloat4Spill,
87   SOK_VRSaveSpill,
88   SOK_QuadFloat8Spill,
89   SOK_QuadFloat4Spill,
90   SOK_QuadBitSpill,
91   SOK_SpillToVSR,
92   SOK_SPESpill,
93   SOK_LastOpcodeSpill  // This must be last on the enum.
94 };
95 
96 // Pin the vtable to this file.
97 void PPCInstrInfo::anchor() {}
98 
99 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
100     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
101                       /* CatchRetOpcode */ -1,
102                       STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
103       Subtarget(STI), RI(STI.getTargetMachine()) {}
104 
105 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
106 /// this target when scheduling the DAG.
107 ScheduleHazardRecognizer *
108 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
109                                            const ScheduleDAG *DAG) const {
110   unsigned Directive =
111       static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
112   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
113       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
114     const InstrItineraryData *II =
115         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
116     return new ScoreboardHazardRecognizer(II, DAG);
117   }
118 
119   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
120 }
121 
122 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
123 /// to use for this target when scheduling the DAG.
124 ScheduleHazardRecognizer *
125 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
126                                                  const ScheduleDAG *DAG) const {
127   unsigned Directive =
128       DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
129 
130   // FIXME: Leaving this as-is until we have POWER9 scheduling info
131   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
132     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
133 
134   // Most subtargets use a PPC970 recognizer.
135   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
136       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
137     assert(DAG->TII && "No InstrInfo?");
138 
139     return new PPCHazardRecognizer970(*DAG);
140   }
141 
142   return new ScoreboardHazardRecognizer(II, DAG);
143 }
144 
145 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
146                                        const MachineInstr &MI,
147                                        unsigned *PredCost) const {
148   if (!ItinData || UseOldLatencyCalc)
149     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
150 
151   // The default implementation of getInstrLatency calls getStageLatency, but
152   // getStageLatency does not do the right thing for us. While we have
153   // itinerary, most cores are fully pipelined, and so the itineraries only
154   // express the first part of the pipeline, not every stage. Instead, we need
155   // to use the listed output operand cycle number (using operand 0 here, which
156   // is an output).
157 
158   unsigned Latency = 1;
159   unsigned DefClass = MI.getDesc().getSchedClass();
160   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
161     const MachineOperand &MO = MI.getOperand(i);
162     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
163       continue;
164 
165     int Cycle = ItinData->getOperandCycle(DefClass, i);
166     if (Cycle < 0)
167       continue;
168 
169     Latency = std::max(Latency, (unsigned) Cycle);
170   }
171 
172   return Latency;
173 }
174 
175 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
176                                     const MachineInstr &DefMI, unsigned DefIdx,
177                                     const MachineInstr &UseMI,
178                                     unsigned UseIdx) const {
179   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
180                                                    UseMI, UseIdx);
181 
182   if (!DefMI.getParent())
183     return Latency;
184 
185   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
186   Register Reg = DefMO.getReg();
187 
188   bool IsRegCR;
189   if (Register::isVirtualRegister(Reg)) {
190     const MachineRegisterInfo *MRI =
191         &DefMI.getParent()->getParent()->getRegInfo();
192     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
193               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
194   } else {
195     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
196               PPC::CRBITRCRegClass.contains(Reg);
197   }
198 
199   if (UseMI.isBranch() && IsRegCR) {
200     if (Latency < 0)
201       Latency = getInstrLatency(ItinData, DefMI);
202 
203     // On some cores, there is an additional delay between writing to a condition
204     // register, and using it from a branch.
205     unsigned Directive = Subtarget.getCPUDirective();
206     switch (Directive) {
207     default: break;
208     case PPC::DIR_7400:
209     case PPC::DIR_750:
210     case PPC::DIR_970:
211     case PPC::DIR_E5500:
212     case PPC::DIR_PWR4:
213     case PPC::DIR_PWR5:
214     case PPC::DIR_PWR5X:
215     case PPC::DIR_PWR6:
216     case PPC::DIR_PWR6X:
217     case PPC::DIR_PWR7:
218     case PPC::DIR_PWR8:
219     // FIXME: Is this needed for POWER9?
220       Latency += 2;
221       break;
222     }
223   }
224 
225   return Latency;
226 }
227 
228 // This function does not list all associative and commutative operations, but
229 // only those worth feeding through the machine combiner in an attempt to
230 // reduce the critical path. Mostly, this means floating-point operations,
231 // because they have high latencies (compared to other operations, such and
232 // and/or, which are also associative and commutative, but have low latencies).
233 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
234   switch (Inst.getOpcode()) {
235   // FP Add:
236   case PPC::FADD:
237   case PPC::FADDS:
238   // FP Multiply:
239   case PPC::FMUL:
240   case PPC::FMULS:
241   // Altivec Add:
242   case PPC::VADDFP:
243   // VSX Add:
244   case PPC::XSADDDP:
245   case PPC::XVADDDP:
246   case PPC::XVADDSP:
247   case PPC::XSADDSP:
248   // VSX Multiply:
249   case PPC::XSMULDP:
250   case PPC::XVMULDP:
251   case PPC::XVMULSP:
252   case PPC::XSMULSP:
253   // QPX Add:
254   case PPC::QVFADD:
255   case PPC::QVFADDS:
256   case PPC::QVFADDSs:
257   // QPX Multiply:
258   case PPC::QVFMUL:
259   case PPC::QVFMULS:
260   case PPC::QVFMULSs:
261     return true;
262   default:
263     return false;
264   }
265 }
266 
267 bool PPCInstrInfo::getMachineCombinerPatterns(
268     MachineInstr &Root,
269     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
270   // Using the machine combiner in this way is potentially expensive, so
271   // restrict to when aggressive optimizations are desired.
272   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
273     return false;
274 
275   // FP reassociation is only legal when we don't need strict IEEE semantics.
276   if (!Root.getParent()->getParent()->getTarget().Options.UnsafeFPMath)
277     return false;
278 
279   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
280 }
281 
282 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
283 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
284                                          Register &SrcReg, Register &DstReg,
285                                          unsigned &SubIdx) const {
286   switch (MI.getOpcode()) {
287   default: return false;
288   case PPC::EXTSW:
289   case PPC::EXTSW_32:
290   case PPC::EXTSW_32_64:
291     SrcReg = MI.getOperand(1).getReg();
292     DstReg = MI.getOperand(0).getReg();
293     SubIdx = PPC::sub_32;
294     return true;
295   }
296 }
297 
298 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
299                                            int &FrameIndex) const {
300   unsigned Opcode = MI.getOpcode();
301   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
302   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
303 
304   if (End != std::find(OpcodesForSpill, End, Opcode)) {
305     // Check for the operands added by addFrameReference (the immediate is the
306     // offset which defaults to 0).
307     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
308         MI.getOperand(2).isFI()) {
309       FrameIndex = MI.getOperand(2).getIndex();
310       return MI.getOperand(0).getReg();
311     }
312   }
313   return 0;
314 }
315 
316 // For opcodes with the ReMaterializable flag set, this function is called to
317 // verify the instruction is really rematable.
318 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
319                                                      AliasAnalysis *AA) const {
320   switch (MI.getOpcode()) {
321   default:
322     // This function should only be called for opcodes with the ReMaterializable
323     // flag set.
324     llvm_unreachable("Unknown rematerializable operation!");
325     break;
326   case PPC::LI:
327   case PPC::LI8:
328   case PPC::LIS:
329   case PPC::LIS8:
330   case PPC::QVGPCI:
331   case PPC::ADDIStocHA:
332   case PPC::ADDIStocHA8:
333   case PPC::ADDItocL:
334   case PPC::LOAD_STACK_GUARD:
335   case PPC::XXLXORz:
336   case PPC::XXLXORspz:
337   case PPC::XXLXORdpz:
338   case PPC::XXLEQVOnes:
339   case PPC::V_SET0B:
340   case PPC::V_SET0H:
341   case PPC::V_SET0:
342   case PPC::V_SETALLONESB:
343   case PPC::V_SETALLONESH:
344   case PPC::V_SETALLONES:
345   case PPC::CRSET:
346   case PPC::CRUNSET:
347     return true;
348   }
349   return false;
350 }
351 
352 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
353                                           int &FrameIndex) const {
354   unsigned Opcode = MI.getOpcode();
355   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
356   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
357 
358   if (End != std::find(OpcodesForSpill, End, Opcode)) {
359     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
360         MI.getOperand(2).isFI()) {
361       FrameIndex = MI.getOperand(2).getIndex();
362       return MI.getOperand(0).getReg();
363     }
364   }
365   return 0;
366 }
367 
368 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
369                                                    unsigned OpIdx1,
370                                                    unsigned OpIdx2) const {
371   MachineFunction &MF = *MI.getParent()->getParent();
372 
373   // Normal instructions can be commuted the obvious way.
374   if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
375     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
376   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
377   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
378   // changing the relative order of the mask operands might change what happens
379   // to the high-bits of the mask (and, thus, the result).
380 
381   // Cannot commute if it has a non-zero rotate count.
382   if (MI.getOperand(3).getImm() != 0)
383     return nullptr;
384 
385   // If we have a zero rotate count, we have:
386   //   M = mask(MB,ME)
387   //   Op0 = (Op1 & ~M) | (Op2 & M)
388   // Change this to:
389   //   M = mask((ME+1)&31, (MB-1)&31)
390   //   Op0 = (Op2 & ~M) | (Op1 & M)
391 
392   // Swap op1/op2
393   assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
394          "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
395   Register Reg0 = MI.getOperand(0).getReg();
396   Register Reg1 = MI.getOperand(1).getReg();
397   Register Reg2 = MI.getOperand(2).getReg();
398   unsigned SubReg1 = MI.getOperand(1).getSubReg();
399   unsigned SubReg2 = MI.getOperand(2).getSubReg();
400   bool Reg1IsKill = MI.getOperand(1).isKill();
401   bool Reg2IsKill = MI.getOperand(2).isKill();
402   bool ChangeReg0 = false;
403   // If machine instrs are no longer in two-address forms, update
404   // destination register as well.
405   if (Reg0 == Reg1) {
406     // Must be two address instruction!
407     assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
408            "Expecting a two-address instruction!");
409     assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
410     Reg2IsKill = false;
411     ChangeReg0 = true;
412   }
413 
414   // Masks.
415   unsigned MB = MI.getOperand(4).getImm();
416   unsigned ME = MI.getOperand(5).getImm();
417 
418   // We can't commute a trivial mask (there is no way to represent an all-zero
419   // mask).
420   if (MB == 0 && ME == 31)
421     return nullptr;
422 
423   if (NewMI) {
424     // Create a new instruction.
425     Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
426     bool Reg0IsDead = MI.getOperand(0).isDead();
427     return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
428         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
429         .addReg(Reg2, getKillRegState(Reg2IsKill))
430         .addReg(Reg1, getKillRegState(Reg1IsKill))
431         .addImm((ME + 1) & 31)
432         .addImm((MB - 1) & 31);
433   }
434 
435   if (ChangeReg0) {
436     MI.getOperand(0).setReg(Reg2);
437     MI.getOperand(0).setSubReg(SubReg2);
438   }
439   MI.getOperand(2).setReg(Reg1);
440   MI.getOperand(1).setReg(Reg2);
441   MI.getOperand(2).setSubReg(SubReg1);
442   MI.getOperand(1).setSubReg(SubReg2);
443   MI.getOperand(2).setIsKill(Reg1IsKill);
444   MI.getOperand(1).setIsKill(Reg2IsKill);
445 
446   // Swap the mask around.
447   MI.getOperand(4).setImm((ME + 1) & 31);
448   MI.getOperand(5).setImm((MB - 1) & 31);
449   return &MI;
450 }
451 
452 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
453                                          unsigned &SrcOpIdx1,
454                                          unsigned &SrcOpIdx2) const {
455   // For VSX A-Type FMA instructions, it is the first two operands that can be
456   // commuted, however, because the non-encoded tied input operand is listed
457   // first, the operands to swap are actually the second and third.
458 
459   int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
460   if (AltOpc == -1)
461     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
462 
463   // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
464   // and SrcOpIdx2.
465   return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
466 }
467 
468 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
469                               MachineBasicBlock::iterator MI) const {
470   // This function is used for scheduling, and the nop wanted here is the type
471   // that terminates dispatch groups on the POWER cores.
472   unsigned Directive = Subtarget.getCPUDirective();
473   unsigned Opcode;
474   switch (Directive) {
475   default:            Opcode = PPC::NOP; break;
476   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
477   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
478   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
479   // FIXME: Update when POWER9 scheduling model is ready.
480   case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
481   }
482 
483   DebugLoc DL;
484   BuildMI(MBB, MI, DL, get(Opcode));
485 }
486 
487 /// Return the noop instruction to use for a noop.
488 void PPCInstrInfo::getNoop(MCInst &NopInst) const {
489   NopInst.setOpcode(PPC::NOP);
490 }
491 
492 // Branch analysis.
493 // Note: If the condition register is set to CTR or CTR8 then this is a
494 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
495 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
496                                  MachineBasicBlock *&TBB,
497                                  MachineBasicBlock *&FBB,
498                                  SmallVectorImpl<MachineOperand> &Cond,
499                                  bool AllowModify) const {
500   bool isPPC64 = Subtarget.isPPC64();
501 
502   // If the block has no terminators, it just falls into the block after it.
503   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
504   if (I == MBB.end())
505     return false;
506 
507   if (!isUnpredicatedTerminator(*I))
508     return false;
509 
510   if (AllowModify) {
511     // If the BB ends with an unconditional branch to the fallthrough BB,
512     // we eliminate the branch instruction.
513     if (I->getOpcode() == PPC::B &&
514         MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
515       I->eraseFromParent();
516 
517       // We update iterator after deleting the last branch.
518       I = MBB.getLastNonDebugInstr();
519       if (I == MBB.end() || !isUnpredicatedTerminator(*I))
520         return false;
521     }
522   }
523 
524   // Get the last instruction in the block.
525   MachineInstr &LastInst = *I;
526 
527   // If there is only one terminator instruction, process it.
528   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
529     if (LastInst.getOpcode() == PPC::B) {
530       if (!LastInst.getOperand(0).isMBB())
531         return true;
532       TBB = LastInst.getOperand(0).getMBB();
533       return false;
534     } else if (LastInst.getOpcode() == PPC::BCC) {
535       if (!LastInst.getOperand(2).isMBB())
536         return true;
537       // Block ends with fall-through condbranch.
538       TBB = LastInst.getOperand(2).getMBB();
539       Cond.push_back(LastInst.getOperand(0));
540       Cond.push_back(LastInst.getOperand(1));
541       return false;
542     } else if (LastInst.getOpcode() == PPC::BC) {
543       if (!LastInst.getOperand(1).isMBB())
544         return true;
545       // Block ends with fall-through condbranch.
546       TBB = LastInst.getOperand(1).getMBB();
547       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
548       Cond.push_back(LastInst.getOperand(0));
549       return false;
550     } else if (LastInst.getOpcode() == PPC::BCn) {
551       if (!LastInst.getOperand(1).isMBB())
552         return true;
553       // Block ends with fall-through condbranch.
554       TBB = LastInst.getOperand(1).getMBB();
555       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
556       Cond.push_back(LastInst.getOperand(0));
557       return false;
558     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
559                LastInst.getOpcode() == PPC::BDNZ) {
560       if (!LastInst.getOperand(0).isMBB())
561         return true;
562       if (DisableCTRLoopAnal)
563         return true;
564       TBB = LastInst.getOperand(0).getMBB();
565       Cond.push_back(MachineOperand::CreateImm(1));
566       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
567                                                true));
568       return false;
569     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
570                LastInst.getOpcode() == PPC::BDZ) {
571       if (!LastInst.getOperand(0).isMBB())
572         return true;
573       if (DisableCTRLoopAnal)
574         return true;
575       TBB = LastInst.getOperand(0).getMBB();
576       Cond.push_back(MachineOperand::CreateImm(0));
577       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
578                                                true));
579       return false;
580     }
581 
582     // Otherwise, don't know what this is.
583     return true;
584   }
585 
586   // Get the instruction before it if it's a terminator.
587   MachineInstr &SecondLastInst = *I;
588 
589   // If there are three terminators, we don't know what sort of block this is.
590   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
591     return true;
592 
593   // If the block ends with PPC::B and PPC:BCC, handle it.
594   if (SecondLastInst.getOpcode() == PPC::BCC &&
595       LastInst.getOpcode() == PPC::B) {
596     if (!SecondLastInst.getOperand(2).isMBB() ||
597         !LastInst.getOperand(0).isMBB())
598       return true;
599     TBB = SecondLastInst.getOperand(2).getMBB();
600     Cond.push_back(SecondLastInst.getOperand(0));
601     Cond.push_back(SecondLastInst.getOperand(1));
602     FBB = LastInst.getOperand(0).getMBB();
603     return false;
604   } else if (SecondLastInst.getOpcode() == PPC::BC &&
605              LastInst.getOpcode() == PPC::B) {
606     if (!SecondLastInst.getOperand(1).isMBB() ||
607         !LastInst.getOperand(0).isMBB())
608       return true;
609     TBB = SecondLastInst.getOperand(1).getMBB();
610     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
611     Cond.push_back(SecondLastInst.getOperand(0));
612     FBB = LastInst.getOperand(0).getMBB();
613     return false;
614   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
615              LastInst.getOpcode() == PPC::B) {
616     if (!SecondLastInst.getOperand(1).isMBB() ||
617         !LastInst.getOperand(0).isMBB())
618       return true;
619     TBB = SecondLastInst.getOperand(1).getMBB();
620     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
621     Cond.push_back(SecondLastInst.getOperand(0));
622     FBB = LastInst.getOperand(0).getMBB();
623     return false;
624   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
625               SecondLastInst.getOpcode() == PPC::BDNZ) &&
626              LastInst.getOpcode() == PPC::B) {
627     if (!SecondLastInst.getOperand(0).isMBB() ||
628         !LastInst.getOperand(0).isMBB())
629       return true;
630     if (DisableCTRLoopAnal)
631       return true;
632     TBB = SecondLastInst.getOperand(0).getMBB();
633     Cond.push_back(MachineOperand::CreateImm(1));
634     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
635                                              true));
636     FBB = LastInst.getOperand(0).getMBB();
637     return false;
638   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
639               SecondLastInst.getOpcode() == PPC::BDZ) &&
640              LastInst.getOpcode() == PPC::B) {
641     if (!SecondLastInst.getOperand(0).isMBB() ||
642         !LastInst.getOperand(0).isMBB())
643       return true;
644     if (DisableCTRLoopAnal)
645       return true;
646     TBB = SecondLastInst.getOperand(0).getMBB();
647     Cond.push_back(MachineOperand::CreateImm(0));
648     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
649                                              true));
650     FBB = LastInst.getOperand(0).getMBB();
651     return false;
652   }
653 
654   // If the block ends with two PPC:Bs, handle it.  The second one is not
655   // executed, so remove it.
656   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
657     if (!SecondLastInst.getOperand(0).isMBB())
658       return true;
659     TBB = SecondLastInst.getOperand(0).getMBB();
660     I = LastInst;
661     if (AllowModify)
662       I->eraseFromParent();
663     return false;
664   }
665 
666   // Otherwise, can't handle this.
667   return true;
668 }
669 
670 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
671                                     int *BytesRemoved) const {
672   assert(!BytesRemoved && "code size not handled");
673 
674   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
675   if (I == MBB.end())
676     return 0;
677 
678   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
679       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
680       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
681       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
682     return 0;
683 
684   // Remove the branch.
685   I->eraseFromParent();
686 
687   I = MBB.end();
688 
689   if (I == MBB.begin()) return 1;
690   --I;
691   if (I->getOpcode() != PPC::BCC &&
692       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
693       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
694       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
695     return 1;
696 
697   // Remove the branch.
698   I->eraseFromParent();
699   return 2;
700 }
701 
702 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
703                                     MachineBasicBlock *TBB,
704                                     MachineBasicBlock *FBB,
705                                     ArrayRef<MachineOperand> Cond,
706                                     const DebugLoc &DL,
707                                     int *BytesAdded) const {
708   // Shouldn't be a fall through.
709   assert(TBB && "insertBranch must not be told to insert a fallthrough");
710   assert((Cond.size() == 2 || Cond.size() == 0) &&
711          "PPC branch conditions have two components!");
712   assert(!BytesAdded && "code size not handled");
713 
714   bool isPPC64 = Subtarget.isPPC64();
715 
716   // One-way branch.
717   if (!FBB) {
718     if (Cond.empty())   // Unconditional branch
719       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
720     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
721       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
722                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
723                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
724     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
725       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
726     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
727       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
728     else                // Conditional branch
729       BuildMI(&MBB, DL, get(PPC::BCC))
730           .addImm(Cond[0].getImm())
731           .add(Cond[1])
732           .addMBB(TBB);
733     return 1;
734   }
735 
736   // Two-way Conditional Branch.
737   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
738     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
739                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
740                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
741   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
742     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
743   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
744     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
745   else
746     BuildMI(&MBB, DL, get(PPC::BCC))
747         .addImm(Cond[0].getImm())
748         .add(Cond[1])
749         .addMBB(TBB);
750   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
751   return 2;
752 }
753 
754 // Select analysis.
755 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
756                                    ArrayRef<MachineOperand> Cond,
757                                    Register DstReg, Register TrueReg,
758                                    Register FalseReg, int &CondCycles,
759                                    int &TrueCycles, int &FalseCycles) const {
760   if (Cond.size() != 2)
761     return false;
762 
763   // If this is really a bdnz-like condition, then it cannot be turned into a
764   // select.
765   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
766     return false;
767 
768   // Check register classes.
769   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
770   const TargetRegisterClass *RC =
771     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
772   if (!RC)
773     return false;
774 
775   // isel is for regular integer GPRs only.
776   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
777       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
778       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
779       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
780     return false;
781 
782   // FIXME: These numbers are for the A2, how well they work for other cores is
783   // an open question. On the A2, the isel instruction has a 2-cycle latency
784   // but single-cycle throughput. These numbers are used in combination with
785   // the MispredictPenalty setting from the active SchedMachineModel.
786   CondCycles = 1;
787   TrueCycles = 1;
788   FalseCycles = 1;
789 
790   return true;
791 }
792 
793 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
794                                 MachineBasicBlock::iterator MI,
795                                 const DebugLoc &dl, Register DestReg,
796                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
797                                 Register FalseReg) const {
798   assert(Cond.size() == 2 &&
799          "PPC branch conditions have two components!");
800 
801   // Get the register classes.
802   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
803   const TargetRegisterClass *RC =
804     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
805   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
806 
807   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
808                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
809   assert((Is64Bit ||
810           PPC::GPRCRegClass.hasSubClassEq(RC) ||
811           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
812          "isel is for regular integer GPRs only");
813 
814   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
815   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
816 
817   unsigned SubIdx = 0;
818   bool SwapOps = false;
819   switch (SelectPred) {
820   case PPC::PRED_EQ:
821   case PPC::PRED_EQ_MINUS:
822   case PPC::PRED_EQ_PLUS:
823       SubIdx = PPC::sub_eq; SwapOps = false; break;
824   case PPC::PRED_NE:
825   case PPC::PRED_NE_MINUS:
826   case PPC::PRED_NE_PLUS:
827       SubIdx = PPC::sub_eq; SwapOps = true; break;
828   case PPC::PRED_LT:
829   case PPC::PRED_LT_MINUS:
830   case PPC::PRED_LT_PLUS:
831       SubIdx = PPC::sub_lt; SwapOps = false; break;
832   case PPC::PRED_GE:
833   case PPC::PRED_GE_MINUS:
834   case PPC::PRED_GE_PLUS:
835       SubIdx = PPC::sub_lt; SwapOps = true; break;
836   case PPC::PRED_GT:
837   case PPC::PRED_GT_MINUS:
838   case PPC::PRED_GT_PLUS:
839       SubIdx = PPC::sub_gt; SwapOps = false; break;
840   case PPC::PRED_LE:
841   case PPC::PRED_LE_MINUS:
842   case PPC::PRED_LE_PLUS:
843       SubIdx = PPC::sub_gt; SwapOps = true; break;
844   case PPC::PRED_UN:
845   case PPC::PRED_UN_MINUS:
846   case PPC::PRED_UN_PLUS:
847       SubIdx = PPC::sub_un; SwapOps = false; break;
848   case PPC::PRED_NU:
849   case PPC::PRED_NU_MINUS:
850   case PPC::PRED_NU_PLUS:
851       SubIdx = PPC::sub_un; SwapOps = true; break;
852   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
853   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
854   }
855 
856   Register FirstReg =  SwapOps ? FalseReg : TrueReg,
857            SecondReg = SwapOps ? TrueReg  : FalseReg;
858 
859   // The first input register of isel cannot be r0. If it is a member
860   // of a register class that can be r0, then copy it first (the
861   // register allocator should eliminate the copy).
862   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
863       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
864     const TargetRegisterClass *FirstRC =
865       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
866         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
867     Register OldFirstReg = FirstReg;
868     FirstReg = MRI.createVirtualRegister(FirstRC);
869     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
870       .addReg(OldFirstReg);
871   }
872 
873   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
874     .addReg(FirstReg).addReg(SecondReg)
875     .addReg(Cond[1].getReg(), 0, SubIdx);
876 }
877 
878 static unsigned getCRBitValue(unsigned CRBit) {
879   unsigned Ret = 4;
880   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
881       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
882       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
883       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
884     Ret = 3;
885   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
886       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
887       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
888       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
889     Ret = 2;
890   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
891       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
892       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
893       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
894     Ret = 1;
895   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
896       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
897       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
898       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
899     Ret = 0;
900 
901   assert(Ret != 4 && "Invalid CR bit register");
902   return Ret;
903 }
904 
905 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
906                                MachineBasicBlock::iterator I,
907                                const DebugLoc &DL, MCRegister DestReg,
908                                MCRegister SrcReg, bool KillSrc) const {
909   // We can end up with self copies and similar things as a result of VSX copy
910   // legalization. Promote them here.
911   const TargetRegisterInfo *TRI = &getRegisterInfo();
912   if (PPC::F8RCRegClass.contains(DestReg) &&
913       PPC::VSRCRegClass.contains(SrcReg)) {
914     MCRegister SuperReg =
915         TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
916 
917     if (VSXSelfCopyCrash && SrcReg == SuperReg)
918       llvm_unreachable("nop VSX copy");
919 
920     DestReg = SuperReg;
921   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
922              PPC::VSRCRegClass.contains(DestReg)) {
923     MCRegister SuperReg =
924         TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
925 
926     if (VSXSelfCopyCrash && DestReg == SuperReg)
927       llvm_unreachable("nop VSX copy");
928 
929     SrcReg = SuperReg;
930   }
931 
932   // Different class register copy
933   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
934       PPC::GPRCRegClass.contains(DestReg)) {
935     MCRegister CRReg = getCRFromCRBit(SrcReg);
936     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
937     getKillRegState(KillSrc);
938     // Rotate the CR bit in the CR fields to be the least significant bit and
939     // then mask with 0x1 (MB = ME = 31).
940     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
941        .addReg(DestReg, RegState::Kill)
942        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
943        .addImm(31)
944        .addImm(31);
945     return;
946   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
947       PPC::G8RCRegClass.contains(DestReg)) {
948     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg);
949     getKillRegState(KillSrc);
950     return;
951   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
952       PPC::GPRCRegClass.contains(DestReg)) {
953     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg);
954     getKillRegState(KillSrc);
955     return;
956   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
957              PPC::VSFRCRegClass.contains(DestReg)) {
958     assert(Subtarget.hasDirectMove() &&
959            "Subtarget doesn't support directmove, don't know how to copy.");
960     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
961     NumGPRtoVSRSpill++;
962     getKillRegState(KillSrc);
963     return;
964   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
965              PPC::G8RCRegClass.contains(DestReg)) {
966     assert(Subtarget.hasDirectMove() &&
967            "Subtarget doesn't support directmove, don't know how to copy.");
968     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
969     getKillRegState(KillSrc);
970     return;
971   } else if (PPC::SPERCRegClass.contains(SrcReg) &&
972              PPC::GPRCRegClass.contains(DestReg)) {
973     BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
974     getKillRegState(KillSrc);
975     return;
976   } else if (PPC::GPRCRegClass.contains(SrcReg) &&
977              PPC::SPERCRegClass.contains(DestReg)) {
978     BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
979     getKillRegState(KillSrc);
980     return;
981   }
982 
983   unsigned Opc;
984   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
985     Opc = PPC::OR;
986   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
987     Opc = PPC::OR8;
988   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
989     Opc = PPC::FMR;
990   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
991     Opc = PPC::MCRF;
992   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
993     Opc = PPC::VOR;
994   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
995     // There are two different ways this can be done:
996     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
997     //      issue in VSU pipeline 0.
998     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
999     //      can go to either pipeline.
1000     // We'll always use xxlor here, because in practically all cases where
1001     // copies are generated, they are close enough to some use that the
1002     // lower-latency form is preferable.
1003     Opc = PPC::XXLOR;
1004   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1005            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1006     Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1007   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
1008     Opc = PPC::QVFMR;
1009   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
1010     Opc = PPC::QVFMRs;
1011   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
1012     Opc = PPC::QVFMRb;
1013   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1014     Opc = PPC::CROR;
1015   else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1016     Opc = PPC::EVOR;
1017   else
1018     llvm_unreachable("Impossible reg-to-reg copy");
1019 
1020   const MCInstrDesc &MCID = get(Opc);
1021   if (MCID.getNumOperands() == 3)
1022     BuildMI(MBB, I, DL, MCID, DestReg)
1023       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1024   else
1025     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1026 }
1027 
1028 unsigned PPCInstrInfo::getStoreOpcodeForSpill(unsigned Reg,
1029                                               const TargetRegisterClass *RC)
1030                                               const {
1031   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1032   int OpcodeIndex = 0;
1033 
1034   if (RC != nullptr) {
1035     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1036         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1037       OpcodeIndex = SOK_Int4Spill;
1038     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1039                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1040       OpcodeIndex = SOK_Int8Spill;
1041     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1042       OpcodeIndex = SOK_Float8Spill;
1043     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1044       OpcodeIndex = SOK_Float4Spill;
1045     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1046       OpcodeIndex = SOK_SPESpill;
1047     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1048       OpcodeIndex = SOK_CRSpill;
1049     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1050       OpcodeIndex = SOK_CRBitSpill;
1051     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1052       OpcodeIndex = SOK_VRVectorSpill;
1053     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1054       OpcodeIndex = SOK_VSXVectorSpill;
1055     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1056       OpcodeIndex = SOK_VectorFloat8Spill;
1057     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1058       OpcodeIndex = SOK_VectorFloat4Spill;
1059     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1060       OpcodeIndex = SOK_VRSaveSpill;
1061     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1062       OpcodeIndex = SOK_QuadFloat8Spill;
1063     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1064       OpcodeIndex = SOK_QuadFloat4Spill;
1065     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1066       OpcodeIndex = SOK_QuadBitSpill;
1067     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1068       OpcodeIndex = SOK_SpillToVSR;
1069     } else {
1070       llvm_unreachable("Unknown regclass!");
1071     }
1072   } else {
1073     if (PPC::GPRCRegClass.contains(Reg) ||
1074         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1075       OpcodeIndex = SOK_Int4Spill;
1076     } else if (PPC::G8RCRegClass.contains(Reg) ||
1077                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1078       OpcodeIndex = SOK_Int8Spill;
1079     } else if (PPC::F8RCRegClass.contains(Reg)) {
1080       OpcodeIndex = SOK_Float8Spill;
1081     } else if (PPC::F4RCRegClass.contains(Reg)) {
1082       OpcodeIndex = SOK_Float4Spill;
1083     } else if (PPC::SPERCRegClass.contains(Reg)) {
1084       OpcodeIndex = SOK_SPESpill;
1085     } else if (PPC::CRRCRegClass.contains(Reg)) {
1086       OpcodeIndex = SOK_CRSpill;
1087     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1088       OpcodeIndex = SOK_CRBitSpill;
1089     } else if (PPC::VRRCRegClass.contains(Reg)) {
1090       OpcodeIndex = SOK_VRVectorSpill;
1091     } else if (PPC::VSRCRegClass.contains(Reg)) {
1092       OpcodeIndex = SOK_VSXVectorSpill;
1093     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1094       OpcodeIndex = SOK_VectorFloat8Spill;
1095     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1096       OpcodeIndex = SOK_VectorFloat4Spill;
1097     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1098       OpcodeIndex = SOK_VRSaveSpill;
1099     } else if (PPC::QFRCRegClass.contains(Reg)) {
1100       OpcodeIndex = SOK_QuadFloat8Spill;
1101     } else if (PPC::QSRCRegClass.contains(Reg)) {
1102       OpcodeIndex = SOK_QuadFloat4Spill;
1103     } else if (PPC::QBRCRegClass.contains(Reg)) {
1104       OpcodeIndex = SOK_QuadBitSpill;
1105     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1106       OpcodeIndex = SOK_SpillToVSR;
1107     } else {
1108       llvm_unreachable("Unknown regclass!");
1109     }
1110   }
1111   return OpcodesForSpill[OpcodeIndex];
1112 }
1113 
1114 unsigned
1115 PPCInstrInfo::getLoadOpcodeForSpill(unsigned Reg,
1116                                     const TargetRegisterClass *RC) const {
1117   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1118   int OpcodeIndex = 0;
1119 
1120   if (RC != nullptr) {
1121     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1122         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1123       OpcodeIndex = SOK_Int4Spill;
1124     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1125                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1126       OpcodeIndex = SOK_Int8Spill;
1127     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1128       OpcodeIndex = SOK_Float8Spill;
1129     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1130       OpcodeIndex = SOK_Float4Spill;
1131     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1132       OpcodeIndex = SOK_SPESpill;
1133     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1134       OpcodeIndex = SOK_CRSpill;
1135     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1136       OpcodeIndex = SOK_CRBitSpill;
1137     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1138       OpcodeIndex = SOK_VRVectorSpill;
1139     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1140       OpcodeIndex = SOK_VSXVectorSpill;
1141     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1142       OpcodeIndex = SOK_VectorFloat8Spill;
1143     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1144       OpcodeIndex = SOK_VectorFloat4Spill;
1145     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1146       OpcodeIndex = SOK_VRSaveSpill;
1147     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1148       OpcodeIndex = SOK_QuadFloat8Spill;
1149     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1150       OpcodeIndex = SOK_QuadFloat4Spill;
1151     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1152       OpcodeIndex = SOK_QuadBitSpill;
1153     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1154       OpcodeIndex = SOK_SpillToVSR;
1155     } else {
1156       llvm_unreachable("Unknown regclass!");
1157     }
1158   } else {
1159     if (PPC::GPRCRegClass.contains(Reg) ||
1160         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1161       OpcodeIndex = SOK_Int4Spill;
1162     } else if (PPC::G8RCRegClass.contains(Reg) ||
1163                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1164       OpcodeIndex = SOK_Int8Spill;
1165     } else if (PPC::F8RCRegClass.contains(Reg)) {
1166       OpcodeIndex = SOK_Float8Spill;
1167     } else if (PPC::F4RCRegClass.contains(Reg)) {
1168       OpcodeIndex = SOK_Float4Spill;
1169     } else if (PPC::SPERCRegClass.contains(Reg)) {
1170       OpcodeIndex = SOK_SPESpill;
1171     } else if (PPC::CRRCRegClass.contains(Reg)) {
1172       OpcodeIndex = SOK_CRSpill;
1173     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1174       OpcodeIndex = SOK_CRBitSpill;
1175     } else if (PPC::VRRCRegClass.contains(Reg)) {
1176       OpcodeIndex = SOK_VRVectorSpill;
1177     } else if (PPC::VSRCRegClass.contains(Reg)) {
1178       OpcodeIndex = SOK_VSXVectorSpill;
1179     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1180       OpcodeIndex = SOK_VectorFloat8Spill;
1181     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1182       OpcodeIndex = SOK_VectorFloat4Spill;
1183     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1184       OpcodeIndex = SOK_VRSaveSpill;
1185     } else if (PPC::QFRCRegClass.contains(Reg)) {
1186       OpcodeIndex = SOK_QuadFloat8Spill;
1187     } else if (PPC::QSRCRegClass.contains(Reg)) {
1188       OpcodeIndex = SOK_QuadFloat4Spill;
1189     } else if (PPC::QBRCRegClass.contains(Reg)) {
1190       OpcodeIndex = SOK_QuadBitSpill;
1191     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1192       OpcodeIndex = SOK_SpillToVSR;
1193     } else {
1194       llvm_unreachable("Unknown regclass!");
1195     }
1196   }
1197   return OpcodesForSpill[OpcodeIndex];
1198 }
1199 
1200 void PPCInstrInfo::StoreRegToStackSlot(
1201     MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1202     const TargetRegisterClass *RC,
1203     SmallVectorImpl<MachineInstr *> &NewMIs) const {
1204   unsigned Opcode = getStoreOpcodeForSpill(PPC::NoRegister, RC);
1205   DebugLoc DL;
1206 
1207   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1208   FuncInfo->setHasSpills();
1209 
1210   NewMIs.push_back(addFrameReference(
1211       BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1212       FrameIdx));
1213 
1214   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1215       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1216     FuncInfo->setSpillsCR();
1217 
1218   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1219     FuncInfo->setSpillsVRSAVE();
1220 
1221   if (isXFormMemOp(Opcode))
1222     FuncInfo->setHasNonRISpills();
1223 }
1224 
1225 void PPCInstrInfo::storeRegToStackSlotNoUpd(
1226     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
1227     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
1228     const TargetRegisterInfo *TRI) const {
1229   MachineFunction &MF = *MBB.getParent();
1230   SmallVector<MachineInstr *, 4> NewMIs;
1231 
1232   StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1233 
1234   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1235     MBB.insert(MI, NewMIs[i]);
1236 
1237   const MachineFrameInfo &MFI = MF.getFrameInfo();
1238   MachineMemOperand *MMO = MF.getMachineMemOperand(
1239       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1240       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1241       MFI.getObjectAlign(FrameIdx));
1242   NewMIs.back()->addMemOperand(MF, MMO);
1243 }
1244 
1245 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1246                                        MachineBasicBlock::iterator MI,
1247                                        Register SrcReg, bool isKill,
1248                                        int FrameIdx,
1249                                        const TargetRegisterClass *RC,
1250                                        const TargetRegisterInfo *TRI) const {
1251   // We need to avoid a situation in which the value from a VRRC register is
1252   // spilled using an Altivec instruction and reloaded into a VSRC register
1253   // using a VSX instruction. The issue with this is that the VSX
1254   // load/store instructions swap the doublewords in the vector and the Altivec
1255   // ones don't. The register classes on the spill/reload may be different if
1256   // the register is defined using an Altivec instruction and is then used by a
1257   // VSX instruction.
1258   RC = updatedRC(RC);
1259   storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI);
1260 }
1261 
1262 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1263                                         unsigned DestReg, int FrameIdx,
1264                                         const TargetRegisterClass *RC,
1265                                         SmallVectorImpl<MachineInstr *> &NewMIs)
1266                                         const {
1267   unsigned Opcode = getLoadOpcodeForSpill(PPC::NoRegister, RC);
1268   NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1269                                      FrameIdx));
1270   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1271 
1272   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1273       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1274     FuncInfo->setSpillsCR();
1275 
1276   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1277     FuncInfo->setSpillsVRSAVE();
1278 
1279   if (isXFormMemOp(Opcode))
1280     FuncInfo->setHasNonRISpills();
1281 }
1282 
1283 void PPCInstrInfo::loadRegFromStackSlotNoUpd(
1284     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
1285     int FrameIdx, const TargetRegisterClass *RC,
1286     const TargetRegisterInfo *TRI) const {
1287   MachineFunction &MF = *MBB.getParent();
1288   SmallVector<MachineInstr*, 4> NewMIs;
1289   DebugLoc DL;
1290   if (MI != MBB.end()) DL = MI->getDebugLoc();
1291 
1292   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1293   FuncInfo->setHasSpills();
1294 
1295   LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1296 
1297   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1298     MBB.insert(MI, NewMIs[i]);
1299 
1300   const MachineFrameInfo &MFI = MF.getFrameInfo();
1301   MachineMemOperand *MMO = MF.getMachineMemOperand(
1302       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1303       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1304       MFI.getObjectAlign(FrameIdx));
1305   NewMIs.back()->addMemOperand(MF, MMO);
1306 }
1307 
1308 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1309                                         MachineBasicBlock::iterator MI,
1310                                         Register DestReg, int FrameIdx,
1311                                         const TargetRegisterClass *RC,
1312                                         const TargetRegisterInfo *TRI) const {
1313   // We need to avoid a situation in which the value from a VRRC register is
1314   // spilled using an Altivec instruction and reloaded into a VSRC register
1315   // using a VSX instruction. The issue with this is that the VSX
1316   // load/store instructions swap the doublewords in the vector and the Altivec
1317   // ones don't. The register classes on the spill/reload may be different if
1318   // the register is defined using an Altivec instruction and is then used by a
1319   // VSX instruction.
1320   RC = updatedRC(RC);
1321 
1322   loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI);
1323 }
1324 
1325 bool PPCInstrInfo::
1326 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1327   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1328   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1329     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1330   else
1331     // Leave the CR# the same, but invert the condition.
1332     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1333   return false;
1334 }
1335 
1336 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1337                                  Register Reg, MachineRegisterInfo *MRI) const {
1338   // For some instructions, it is legal to fold ZERO into the RA register field.
1339   // A zero immediate should always be loaded with a single li.
1340   unsigned DefOpc = DefMI.getOpcode();
1341   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1342     return false;
1343   if (!DefMI.getOperand(1).isImm())
1344     return false;
1345   if (DefMI.getOperand(1).getImm() != 0)
1346     return false;
1347 
1348   // Note that we cannot here invert the arguments of an isel in order to fold
1349   // a ZERO into what is presented as the second argument. All we have here
1350   // is the condition bit, and that might come from a CR-logical bit operation.
1351 
1352   const MCInstrDesc &UseMCID = UseMI.getDesc();
1353 
1354   // Only fold into real machine instructions.
1355   if (UseMCID.isPseudo())
1356     return false;
1357 
1358   unsigned UseIdx;
1359   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1360     if (UseMI.getOperand(UseIdx).isReg() &&
1361         UseMI.getOperand(UseIdx).getReg() == Reg)
1362       break;
1363 
1364   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1365   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1366 
1367   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1368 
1369   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1370   // register (which might also be specified as a pointer class kind).
1371   if (UseInfo->isLookupPtrRegClass()) {
1372     if (UseInfo->RegClass /* Kind */ != 1)
1373       return false;
1374   } else {
1375     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1376         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1377       return false;
1378   }
1379 
1380   // Make sure this is not tied to an output register (or otherwise
1381   // constrained). This is true for ST?UX registers, for example, which
1382   // are tied to their output registers.
1383   if (UseInfo->Constraints != 0)
1384     return false;
1385 
1386   MCRegister ZeroReg;
1387   if (UseInfo->isLookupPtrRegClass()) {
1388     bool isPPC64 = Subtarget.isPPC64();
1389     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1390   } else {
1391     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1392               PPC::ZERO8 : PPC::ZERO;
1393   }
1394 
1395   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1396   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1397 
1398   if (DeleteDef)
1399     DefMI.eraseFromParent();
1400 
1401   return true;
1402 }
1403 
1404 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1405   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1406        I != IE; ++I)
1407     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1408       return true;
1409   return false;
1410 }
1411 
1412 // We should make sure that, if we're going to predicate both sides of a
1413 // condition (a diamond), that both sides don't define the counter register. We
1414 // can predicate counter-decrement-based branches, but while that predicates
1415 // the branching, it does not predicate the counter decrement. If we tried to
1416 // merge the triangle into one predicated block, we'd decrement the counter
1417 // twice.
1418 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1419                      unsigned NumT, unsigned ExtraT,
1420                      MachineBasicBlock &FMBB,
1421                      unsigned NumF, unsigned ExtraF,
1422                      BranchProbability Probability) const {
1423   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1424 }
1425 
1426 
1427 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1428   // The predicated branches are identified by their type, not really by the
1429   // explicit presence of a predicate. Furthermore, some of them can be
1430   // predicated more than once. Because if conversion won't try to predicate
1431   // any instruction which already claims to be predicated (by returning true
1432   // here), always return false. In doing so, we let isPredicable() be the
1433   // final word on whether not the instruction can be (further) predicated.
1434 
1435   return false;
1436 }
1437 
1438 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
1439   if (!MI.isTerminator())
1440     return false;
1441 
1442   // Conditional branch is a special case.
1443   if (MI.isBranch() && !MI.isBarrier())
1444     return true;
1445 
1446   return !isPredicated(MI);
1447 }
1448 
1449 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1450                                         ArrayRef<MachineOperand> Pred) const {
1451   unsigned OpC = MI.getOpcode();
1452   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1453     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1454       bool isPPC64 = Subtarget.isPPC64();
1455       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1456                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1457     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1458       MI.setDesc(get(PPC::BCLR));
1459       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1460     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1461       MI.setDesc(get(PPC::BCLRn));
1462       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1463     } else {
1464       MI.setDesc(get(PPC::BCCLR));
1465       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1466           .addImm(Pred[0].getImm())
1467           .add(Pred[1]);
1468     }
1469 
1470     return true;
1471   } else if (OpC == PPC::B) {
1472     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1473       bool isPPC64 = Subtarget.isPPC64();
1474       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1475                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1476     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1477       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1478       MI.RemoveOperand(0);
1479 
1480       MI.setDesc(get(PPC::BC));
1481       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1482           .add(Pred[1])
1483           .addMBB(MBB);
1484     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1485       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1486       MI.RemoveOperand(0);
1487 
1488       MI.setDesc(get(PPC::BCn));
1489       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1490           .add(Pred[1])
1491           .addMBB(MBB);
1492     } else {
1493       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1494       MI.RemoveOperand(0);
1495 
1496       MI.setDesc(get(PPC::BCC));
1497       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1498           .addImm(Pred[0].getImm())
1499           .add(Pred[1])
1500           .addMBB(MBB);
1501     }
1502 
1503     return true;
1504   } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
1505              OpC == PPC::BCTRL8) {
1506     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1507       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1508 
1509     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1510     bool isPPC64 = Subtarget.isPPC64();
1511 
1512     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1513       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1514                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1515       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1516       return true;
1517     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1518       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1519                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1520       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1521       return true;
1522     }
1523 
1524     MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1525                            : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1526     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1527         .addImm(Pred[0].getImm())
1528         .add(Pred[1]);
1529     return true;
1530   }
1531 
1532   return false;
1533 }
1534 
1535 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1536                                      ArrayRef<MachineOperand> Pred2) const {
1537   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1538   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1539 
1540   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1541     return false;
1542   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1543     return false;
1544 
1545   // P1 can only subsume P2 if they test the same condition register.
1546   if (Pred1[1].getReg() != Pred2[1].getReg())
1547     return false;
1548 
1549   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1550   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1551 
1552   if (P1 == P2)
1553     return true;
1554 
1555   // Does P1 subsume P2, e.g. GE subsumes GT.
1556   if (P1 == PPC::PRED_LE &&
1557       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1558     return true;
1559   if (P1 == PPC::PRED_GE &&
1560       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1561     return true;
1562 
1563   return false;
1564 }
1565 
1566 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1567                                     std::vector<MachineOperand> &Pred) const {
1568   // Note: At the present time, the contents of Pred from this function is
1569   // unused by IfConversion. This implementation follows ARM by pushing the
1570   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1571   // predicate, instructions defining CTR or CTR8 are also included as
1572   // predicate-defining instructions.
1573 
1574   const TargetRegisterClass *RCs[] =
1575     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1576       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1577 
1578   bool Found = false;
1579   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1580     const MachineOperand &MO = MI.getOperand(i);
1581     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1582       const TargetRegisterClass *RC = RCs[c];
1583       if (MO.isReg()) {
1584         if (MO.isDef() && RC->contains(MO.getReg())) {
1585           Pred.push_back(MO);
1586           Found = true;
1587         }
1588       } else if (MO.isRegMask()) {
1589         for (TargetRegisterClass::iterator I = RC->begin(),
1590              IE = RC->end(); I != IE; ++I)
1591           if (MO.clobbersPhysReg(*I)) {
1592             Pred.push_back(MO);
1593             Found = true;
1594           }
1595       }
1596     }
1597   }
1598 
1599   return Found;
1600 }
1601 
1602 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1603                                   Register &SrcReg2, int &Mask,
1604                                   int &Value) const {
1605   unsigned Opc = MI.getOpcode();
1606 
1607   switch (Opc) {
1608   default: return false;
1609   case PPC::CMPWI:
1610   case PPC::CMPLWI:
1611   case PPC::CMPDI:
1612   case PPC::CMPLDI:
1613     SrcReg = MI.getOperand(1).getReg();
1614     SrcReg2 = 0;
1615     Value = MI.getOperand(2).getImm();
1616     Mask = 0xFFFF;
1617     return true;
1618   case PPC::CMPW:
1619   case PPC::CMPLW:
1620   case PPC::CMPD:
1621   case PPC::CMPLD:
1622   case PPC::FCMPUS:
1623   case PPC::FCMPUD:
1624     SrcReg = MI.getOperand(1).getReg();
1625     SrcReg2 = MI.getOperand(2).getReg();
1626     Value = 0;
1627     Mask = 0;
1628     return true;
1629   }
1630 }
1631 
1632 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1633                                         Register SrcReg2, int Mask, int Value,
1634                                         const MachineRegisterInfo *MRI) const {
1635   if (DisableCmpOpt)
1636     return false;
1637 
1638   int OpC = CmpInstr.getOpcode();
1639   Register CRReg = CmpInstr.getOperand(0).getReg();
1640 
1641   // FP record forms set CR1 based on the exception status bits, not a
1642   // comparison with zero.
1643   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1644     return false;
1645 
1646   const TargetRegisterInfo *TRI = &getRegisterInfo();
1647   // The record forms set the condition register based on a signed comparison
1648   // with zero (so says the ISA manual). This is not as straightforward as it
1649   // seems, however, because this is always a 64-bit comparison on PPC64, even
1650   // for instructions that are 32-bit in nature (like slw for example).
1651   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1652   // for equality checks (as those don't depend on the sign). On PPC64,
1653   // we are restricted to equality for unsigned 64-bit comparisons and for
1654   // signed 32-bit comparisons the applicability is more restricted.
1655   bool isPPC64 = Subtarget.isPPC64();
1656   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1657   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1658   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1659 
1660   // Look through copies unless that gets us to a physical register.
1661   Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
1662   if (ActualSrc.isVirtual())
1663     SrcReg = ActualSrc;
1664 
1665   // Get the unique definition of SrcReg.
1666   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1667   if (!MI) return false;
1668 
1669   bool equalityOnly = false;
1670   bool noSub = false;
1671   if (isPPC64) {
1672     if (is32BitSignedCompare) {
1673       // We can perform this optimization only if MI is sign-extending.
1674       if (isSignExtended(*MI))
1675         noSub = true;
1676       else
1677         return false;
1678     } else if (is32BitUnsignedCompare) {
1679       // We can perform this optimization, equality only, if MI is
1680       // zero-extending.
1681       if (isZeroExtended(*MI)) {
1682         noSub = true;
1683         equalityOnly = true;
1684       } else
1685         return false;
1686     } else
1687       equalityOnly = is64BitUnsignedCompare;
1688   } else
1689     equalityOnly = is32BitUnsignedCompare;
1690 
1691   if (equalityOnly) {
1692     // We need to check the uses of the condition register in order to reject
1693     // non-equality comparisons.
1694     for (MachineRegisterInfo::use_instr_iterator
1695          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1696          I != IE; ++I) {
1697       MachineInstr *UseMI = &*I;
1698       if (UseMI->getOpcode() == PPC::BCC) {
1699         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1700         unsigned PredCond = PPC::getPredicateCondition(Pred);
1701         // We ignore hint bits when checking for non-equality comparisons.
1702         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1703           return false;
1704       } else if (UseMI->getOpcode() == PPC::ISEL ||
1705                  UseMI->getOpcode() == PPC::ISEL8) {
1706         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1707         if (SubIdx != PPC::sub_eq)
1708           return false;
1709       } else
1710         return false;
1711     }
1712   }
1713 
1714   MachineBasicBlock::iterator I = CmpInstr;
1715 
1716   // Scan forward to find the first use of the compare.
1717   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1718        ++I) {
1719     bool FoundUse = false;
1720     for (MachineRegisterInfo::use_instr_iterator
1721          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1722          J != JE; ++J)
1723       if (&*J == &*I) {
1724         FoundUse = true;
1725         break;
1726       }
1727 
1728     if (FoundUse)
1729       break;
1730   }
1731 
1732   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1733   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1734 
1735   // There are two possible candidates which can be changed to set CR[01].
1736   // One is MI, the other is a SUB instruction.
1737   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1738   MachineInstr *Sub = nullptr;
1739   if (SrcReg2 != 0)
1740     // MI is not a candidate for CMPrr.
1741     MI = nullptr;
1742   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1743   // same BB as the comparison. This is to allow the check below to avoid calls
1744   // (and other explicit clobbers); instead we should really check for these
1745   // more explicitly (in at least a few predecessors).
1746   else if (MI->getParent() != CmpInstr.getParent())
1747     return false;
1748   else if (Value != 0) {
1749     // The record-form instructions set CR bit based on signed comparison
1750     // against 0. We try to convert a compare against 1 or -1 into a compare
1751     // against 0 to exploit record-form instructions. For example, we change
1752     // the condition "greater than -1" into "greater than or equal to 0"
1753     // and "less than 1" into "less than or equal to 0".
1754 
1755     // Since we optimize comparison based on a specific branch condition,
1756     // we don't optimize if condition code is used by more than once.
1757     if (equalityOnly || !MRI->hasOneUse(CRReg))
1758       return false;
1759 
1760     MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1761     if (UseMI->getOpcode() != PPC::BCC)
1762       return false;
1763 
1764     PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1765     unsigned PredCond = PPC::getPredicateCondition(Pred);
1766     unsigned PredHint = PPC::getPredicateHint(Pred);
1767     int16_t Immed = (int16_t)Value;
1768 
1769     // When modifying the condition in the predicate, we propagate hint bits
1770     // from the original predicate to the new one.
1771     if (Immed == -1 && PredCond == PPC::PRED_GT)
1772       // We convert "greater than -1" into "greater than or equal to 0",
1773       // since we are assuming signed comparison by !equalityOnly
1774       Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
1775     else if (Immed == -1 && PredCond == PPC::PRED_LE)
1776       // We convert "less than or equal to -1" into "less than 0".
1777       Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
1778     else if (Immed == 1 && PredCond == PPC::PRED_LT)
1779       // We convert "less than 1" into "less than or equal to 0".
1780       Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
1781     else if (Immed == 1 && PredCond == PPC::PRED_GE)
1782       // We convert "greater than or equal to 1" into "greater than 0".
1783       Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
1784     else
1785       return false;
1786 
1787     PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
1788   }
1789 
1790   // Search for Sub.
1791   --I;
1792 
1793   // Get ready to iterate backward from CmpInstr.
1794   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1795 
1796   for (; I != E && !noSub; --I) {
1797     const MachineInstr &Instr = *I;
1798     unsigned IOpC = Instr.getOpcode();
1799 
1800     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1801                              Instr.readsRegister(PPC::CR0, TRI)))
1802       // This instruction modifies or uses the record condition register after
1803       // the one we want to change. While we could do this transformation, it
1804       // would likely not be profitable. This transformation removes one
1805       // instruction, and so even forcing RA to generate one move probably
1806       // makes it unprofitable.
1807       return false;
1808 
1809     // Check whether CmpInstr can be made redundant by the current instruction.
1810     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1811          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1812         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1813         ((Instr.getOperand(1).getReg() == SrcReg &&
1814           Instr.getOperand(2).getReg() == SrcReg2) ||
1815         (Instr.getOperand(1).getReg() == SrcReg2 &&
1816          Instr.getOperand(2).getReg() == SrcReg))) {
1817       Sub = &*I;
1818       break;
1819     }
1820 
1821     if (I == B)
1822       // The 'and' is below the comparison instruction.
1823       return false;
1824   }
1825 
1826   // Return false if no candidates exist.
1827   if (!MI && !Sub)
1828     return false;
1829 
1830   // The single candidate is called MI.
1831   if (!MI) MI = Sub;
1832 
1833   int NewOpC = -1;
1834   int MIOpC = MI->getOpcode();
1835   if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
1836       MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
1837     NewOpC = MIOpC;
1838   else {
1839     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1840     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1841       NewOpC = MIOpC;
1842   }
1843 
1844   // FIXME: On the non-embedded POWER architectures, only some of the record
1845   // forms are fast, and we should use only the fast ones.
1846 
1847   // The defining instruction has a record form (or is already a record
1848   // form). It is possible, however, that we'll need to reverse the condition
1849   // code of the users.
1850   if (NewOpC == -1)
1851     return false;
1852 
1853   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1854   // needs to be updated to be based on SUB.  Push the condition code
1855   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1856   // condition code of these operands will be modified.
1857   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1858   // comparison against 0, which may modify predicate.
1859   bool ShouldSwap = false;
1860   if (Sub && Value == 0) {
1861     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1862       Sub->getOperand(2).getReg() == SrcReg;
1863 
1864     // The operands to subf are the opposite of sub, so only in the fixed-point
1865     // case, invert the order.
1866     ShouldSwap = !ShouldSwap;
1867   }
1868 
1869   if (ShouldSwap)
1870     for (MachineRegisterInfo::use_instr_iterator
1871          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1872          I != IE; ++I) {
1873       MachineInstr *UseMI = &*I;
1874       if (UseMI->getOpcode() == PPC::BCC) {
1875         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1876         unsigned PredCond = PPC::getPredicateCondition(Pred);
1877         assert((!equalityOnly ||
1878                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1879                "Invalid predicate for equality-only optimization");
1880         (void)PredCond; // To suppress warning in release build.
1881         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1882                                 PPC::getSwappedPredicate(Pred)));
1883       } else if (UseMI->getOpcode() == PPC::ISEL ||
1884                  UseMI->getOpcode() == PPC::ISEL8) {
1885         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1886         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1887                "Invalid CR bit for equality-only optimization");
1888 
1889         if (NewSubReg == PPC::sub_lt)
1890           NewSubReg = PPC::sub_gt;
1891         else if (NewSubReg == PPC::sub_gt)
1892           NewSubReg = PPC::sub_lt;
1893 
1894         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1895                                                  NewSubReg));
1896       } else // We need to abort on a user we don't understand.
1897         return false;
1898     }
1899   assert(!(Value != 0 && ShouldSwap) &&
1900          "Non-zero immediate support and ShouldSwap"
1901          "may conflict in updating predicate");
1902 
1903   // Create a new virtual register to hold the value of the CR set by the
1904   // record-form instruction. If the instruction was not previously in
1905   // record form, then set the kill flag on the CR.
1906   CmpInstr.eraseFromParent();
1907 
1908   MachineBasicBlock::iterator MII = MI;
1909   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1910           get(TargetOpcode::COPY), CRReg)
1911     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1912 
1913   // Even if CR0 register were dead before, it is alive now since the
1914   // instruction we just built uses it.
1915   MI->clearRegisterDeads(PPC::CR0);
1916 
1917   if (MIOpC != NewOpC) {
1918     // We need to be careful here: we're replacing one instruction with
1919     // another, and we need to make sure that we get all of the right
1920     // implicit uses and defs. On the other hand, the caller may be holding
1921     // an iterator to this instruction, and so we can't delete it (this is
1922     // specifically the case if this is the instruction directly after the
1923     // compare).
1924 
1925     // Rotates are expensive instructions. If we're emitting a record-form
1926     // rotate that can just be an andi/andis, we should just emit that.
1927     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
1928       Register GPRRes = MI->getOperand(0).getReg();
1929       int64_t SH = MI->getOperand(2).getImm();
1930       int64_t MB = MI->getOperand(3).getImm();
1931       int64_t ME = MI->getOperand(4).getImm();
1932       // We can only do this if both the start and end of the mask are in the
1933       // same halfword.
1934       bool MBInLoHWord = MB >= 16;
1935       bool MEInLoHWord = ME >= 16;
1936       uint64_t Mask = ~0LLU;
1937 
1938       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
1939         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
1940         // The mask value needs to shift right 16 if we're emitting andis.
1941         Mask >>= MBInLoHWord ? 0 : 16;
1942         NewOpC = MIOpC == PPC::RLWINM
1943                      ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
1944                      : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
1945       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
1946                  (ME - MB + 1 == SH) && (MB >= 16)) {
1947         // If we are rotating by the exact number of bits as are in the mask
1948         // and the mask is in the least significant bits of the register,
1949         // that's just an andis. (as long as the GPR result has no uses).
1950         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
1951         Mask >>= 16;
1952         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
1953       }
1954       // If we've set the mask, we can transform.
1955       if (Mask != ~0LLU) {
1956         MI->RemoveOperand(4);
1957         MI->RemoveOperand(3);
1958         MI->getOperand(2).setImm(Mask);
1959         NumRcRotatesConvertedToRcAnd++;
1960       }
1961     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
1962       int64_t MB = MI->getOperand(3).getImm();
1963       if (MB >= 48) {
1964         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
1965         NewOpC = PPC::ANDI8_rec;
1966         MI->RemoveOperand(3);
1967         MI->getOperand(2).setImm(Mask);
1968         NumRcRotatesConvertedToRcAnd++;
1969       }
1970     }
1971 
1972     const MCInstrDesc &NewDesc = get(NewOpC);
1973     MI->setDesc(NewDesc);
1974 
1975     if (NewDesc.ImplicitDefs)
1976       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
1977            *ImpDefs; ++ImpDefs)
1978         if (!MI->definesRegister(*ImpDefs))
1979           MI->addOperand(*MI->getParent()->getParent(),
1980                          MachineOperand::CreateReg(*ImpDefs, true, true));
1981     if (NewDesc.ImplicitUses)
1982       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
1983            *ImpUses; ++ImpUses)
1984         if (!MI->readsRegister(*ImpUses))
1985           MI->addOperand(*MI->getParent()->getParent(),
1986                          MachineOperand::CreateReg(*ImpUses, false, true));
1987   }
1988   assert(MI->definesRegister(PPC::CR0) &&
1989          "Record-form instruction does not define cr0?");
1990 
1991   // Modify the condition code of operands in OperandsToUpdate.
1992   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1993   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1994   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1995     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1996 
1997   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1998     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1999 
2000   return true;
2001 }
2002 
2003 /// GetInstSize - Return the number of bytes of code the specified
2004 /// instruction may be.  This returns the maximum number of bytes.
2005 ///
2006 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2007   unsigned Opcode = MI.getOpcode();
2008 
2009   if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2010     const MachineFunction *MF = MI.getParent()->getParent();
2011     const char *AsmStr = MI.getOperand(0).getSymbolName();
2012     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2013   } else if (Opcode == TargetOpcode::STACKMAP) {
2014     StackMapOpers Opers(&MI);
2015     return Opers.getNumPatchBytes();
2016   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2017     PatchPointOpers Opers(&MI);
2018     return Opers.getNumPatchBytes();
2019   } else {
2020     return get(Opcode).getSize();
2021   }
2022 }
2023 
2024 std::pair<unsigned, unsigned>
2025 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2026   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2027   return std::make_pair(TF & Mask, TF & ~Mask);
2028 }
2029 
2030 ArrayRef<std::pair<unsigned, const char *>>
2031 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2032   using namespace PPCII;
2033   static const std::pair<unsigned, const char *> TargetFlags[] = {
2034       {MO_LO, "ppc-lo"},
2035       {MO_HA, "ppc-ha"},
2036       {MO_TPREL_LO, "ppc-tprel-lo"},
2037       {MO_TPREL_HA, "ppc-tprel-ha"},
2038       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2039       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2040       {MO_TOC_LO, "ppc-toc-lo"},
2041       {MO_TLS, "ppc-tls"}};
2042   return makeArrayRef(TargetFlags);
2043 }
2044 
2045 ArrayRef<std::pair<unsigned, const char *>>
2046 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2047   using namespace PPCII;
2048   static const std::pair<unsigned, const char *> TargetFlags[] = {
2049       {MO_PLT, "ppc-plt"},
2050       {MO_PIC_FLAG, "ppc-pic"},
2051       {MO_PCREL_FLAG, "ppc-pcrel"}};
2052   return makeArrayRef(TargetFlags);
2053 }
2054 
2055 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2056 // The VSX versions have the advantage of a full 64-register target whereas
2057 // the FP ones have the advantage of lower latency and higher throughput. So
2058 // what we are after is using the faster instructions in low register pressure
2059 // situations and using the larger register file in high register pressure
2060 // situations.
2061 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2062     unsigned UpperOpcode, LowerOpcode;
2063     switch (MI.getOpcode()) {
2064     case PPC::DFLOADf32:
2065       UpperOpcode = PPC::LXSSP;
2066       LowerOpcode = PPC::LFS;
2067       break;
2068     case PPC::DFLOADf64:
2069       UpperOpcode = PPC::LXSD;
2070       LowerOpcode = PPC::LFD;
2071       break;
2072     case PPC::DFSTOREf32:
2073       UpperOpcode = PPC::STXSSP;
2074       LowerOpcode = PPC::STFS;
2075       break;
2076     case PPC::DFSTOREf64:
2077       UpperOpcode = PPC::STXSD;
2078       LowerOpcode = PPC::STFD;
2079       break;
2080     case PPC::XFLOADf32:
2081       UpperOpcode = PPC::LXSSPX;
2082       LowerOpcode = PPC::LFSX;
2083       break;
2084     case PPC::XFLOADf64:
2085       UpperOpcode = PPC::LXSDX;
2086       LowerOpcode = PPC::LFDX;
2087       break;
2088     case PPC::XFSTOREf32:
2089       UpperOpcode = PPC::STXSSPX;
2090       LowerOpcode = PPC::STFSX;
2091       break;
2092     case PPC::XFSTOREf64:
2093       UpperOpcode = PPC::STXSDX;
2094       LowerOpcode = PPC::STFDX;
2095       break;
2096     case PPC::LIWAX:
2097       UpperOpcode = PPC::LXSIWAX;
2098       LowerOpcode = PPC::LFIWAX;
2099       break;
2100     case PPC::LIWZX:
2101       UpperOpcode = PPC::LXSIWZX;
2102       LowerOpcode = PPC::LFIWZX;
2103       break;
2104     case PPC::STIWX:
2105       UpperOpcode = PPC::STXSIWX;
2106       LowerOpcode = PPC::STFIWX;
2107       break;
2108     default:
2109       llvm_unreachable("Unknown Operation!");
2110     }
2111 
2112     Register TargetReg = MI.getOperand(0).getReg();
2113     unsigned Opcode;
2114     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2115         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2116       Opcode = LowerOpcode;
2117     else
2118       Opcode = UpperOpcode;
2119     MI.setDesc(get(Opcode));
2120     return true;
2121 }
2122 
2123 static bool isAnImmediateOperand(const MachineOperand &MO) {
2124   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2125 }
2126 
2127 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2128   auto &MBB = *MI.getParent();
2129   auto DL = MI.getDebugLoc();
2130 
2131   switch (MI.getOpcode()) {
2132   case TargetOpcode::LOAD_STACK_GUARD: {
2133     assert(Subtarget.isTargetLinux() &&
2134            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2135     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2136     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2137     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2138     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2139         .addImm(Offset)
2140         .addReg(Reg);
2141     return true;
2142   }
2143   case PPC::DFLOADf32:
2144   case PPC::DFLOADf64:
2145   case PPC::DFSTOREf32:
2146   case PPC::DFSTOREf64: {
2147     assert(Subtarget.hasP9Vector() &&
2148            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2149     assert(MI.getOperand(2).isReg() &&
2150            isAnImmediateOperand(MI.getOperand(1)) &&
2151            "D-form op must have register and immediate operands");
2152     return expandVSXMemPseudo(MI);
2153   }
2154   case PPC::XFLOADf32:
2155   case PPC::XFSTOREf32:
2156   case PPC::LIWAX:
2157   case PPC::LIWZX:
2158   case PPC::STIWX: {
2159     assert(Subtarget.hasP8Vector() &&
2160            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2161     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2162            "X-form op must have register and register operands");
2163     return expandVSXMemPseudo(MI);
2164   }
2165   case PPC::XFLOADf64:
2166   case PPC::XFSTOREf64: {
2167     assert(Subtarget.hasVSX() &&
2168            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2169     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2170            "X-form op must have register and register operands");
2171     return expandVSXMemPseudo(MI);
2172   }
2173   case PPC::SPILLTOVSR_LD: {
2174     Register TargetReg = MI.getOperand(0).getReg();
2175     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2176       MI.setDesc(get(PPC::DFLOADf64));
2177       return expandPostRAPseudo(MI);
2178     }
2179     else
2180       MI.setDesc(get(PPC::LD));
2181     return true;
2182   }
2183   case PPC::SPILLTOVSR_ST: {
2184     Register SrcReg = MI.getOperand(0).getReg();
2185     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2186       NumStoreSPILLVSRRCAsVec++;
2187       MI.setDesc(get(PPC::DFSTOREf64));
2188       return expandPostRAPseudo(MI);
2189     } else {
2190       NumStoreSPILLVSRRCAsGpr++;
2191       MI.setDesc(get(PPC::STD));
2192     }
2193     return true;
2194   }
2195   case PPC::SPILLTOVSR_LDX: {
2196     Register TargetReg = MI.getOperand(0).getReg();
2197     if (PPC::VSFRCRegClass.contains(TargetReg))
2198       MI.setDesc(get(PPC::LXSDX));
2199     else
2200       MI.setDesc(get(PPC::LDX));
2201     return true;
2202   }
2203   case PPC::SPILLTOVSR_STX: {
2204     Register SrcReg = MI.getOperand(0).getReg();
2205     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2206       NumStoreSPILLVSRRCAsVec++;
2207       MI.setDesc(get(PPC::STXSDX));
2208     } else {
2209       NumStoreSPILLVSRRCAsGpr++;
2210       MI.setDesc(get(PPC::STDX));
2211     }
2212     return true;
2213   }
2214 
2215   case PPC::CFENCE8: {
2216     auto Val = MI.getOperand(0).getReg();
2217     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2218     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2219         .addImm(PPC::PRED_NE_MINUS)
2220         .addReg(PPC::CR7)
2221         .addImm(1);
2222     MI.setDesc(get(PPC::ISYNC));
2223     MI.RemoveOperand(0);
2224     return true;
2225   }
2226   }
2227   return false;
2228 }
2229 
2230 // Essentially a compile-time implementation of a compare->isel sequence.
2231 // It takes two constants to compare, along with the true/false registers
2232 // and the comparison type (as a subreg to a CR field) and returns one
2233 // of the true/false registers, depending on the comparison results.
2234 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2235                           unsigned TrueReg, unsigned FalseReg,
2236                           unsigned CRSubReg) {
2237   // Signed comparisons. The immediates are assumed to be sign-extended.
2238   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2239     switch (CRSubReg) {
2240     default: llvm_unreachable("Unknown integer comparison type.");
2241     case PPC::sub_lt:
2242       return Imm1 < Imm2 ? TrueReg : FalseReg;
2243     case PPC::sub_gt:
2244       return Imm1 > Imm2 ? TrueReg : FalseReg;
2245     case PPC::sub_eq:
2246       return Imm1 == Imm2 ? TrueReg : FalseReg;
2247     }
2248   }
2249   // Unsigned comparisons.
2250   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2251     switch (CRSubReg) {
2252     default: llvm_unreachable("Unknown integer comparison type.");
2253     case PPC::sub_lt:
2254       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2255     case PPC::sub_gt:
2256       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2257     case PPC::sub_eq:
2258       return Imm1 == Imm2 ? TrueReg : FalseReg;
2259     }
2260   }
2261   return PPC::NoRegister;
2262 }
2263 
2264 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2265                                               unsigned OpNo,
2266                                               int64_t Imm) const {
2267   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2268   // Replace the REG with the Immediate.
2269   Register InUseReg = MI.getOperand(OpNo).getReg();
2270   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2271 
2272   if (MI.implicit_operands().empty())
2273     return;
2274 
2275   // We need to make sure that the MI didn't have any implicit use
2276   // of this REG any more.
2277   const TargetRegisterInfo *TRI = &getRegisterInfo();
2278   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2279   if (UseOpIdx >= 0) {
2280     MachineOperand &MO = MI.getOperand(UseOpIdx);
2281     if (MO.isImplicit())
2282       // The operands must always be in the following order:
2283       // - explicit reg defs,
2284       // - other explicit operands (reg uses, immediates, etc.),
2285       // - implicit reg defs
2286       // - implicit reg uses
2287       // Therefore, removing the implicit operand won't change the explicit
2288       // operands layout.
2289       MI.RemoveOperand(UseOpIdx);
2290   }
2291 }
2292 
2293 // Replace an instruction with one that materializes a constant (and sets
2294 // CR0 if the original instruction was a record-form instruction).
2295 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2296                                       const LoadImmediateInfo &LII) const {
2297   // Remove existing operands.
2298   int OperandToKeep = LII.SetCR ? 1 : 0;
2299   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2300     MI.RemoveOperand(i);
2301 
2302   // Replace the instruction.
2303   if (LII.SetCR) {
2304     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
2305     // Set the immediate.
2306     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2307         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2308     return;
2309   }
2310   else
2311     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2312 
2313   // Set the immediate.
2314   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2315       .addImm(LII.Imm);
2316 }
2317 
2318 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2319                                            bool &SeenIntermediateUse) const {
2320   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2321          "Should be called after register allocation.");
2322   const TargetRegisterInfo *TRI = &getRegisterInfo();
2323   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2324   It++;
2325   SeenIntermediateUse = false;
2326   for (; It != E; ++It) {
2327     if (It->modifiesRegister(Reg, TRI))
2328       return &*It;
2329     if (It->readsRegister(Reg, TRI))
2330       SeenIntermediateUse = true;
2331   }
2332   return nullptr;
2333 }
2334 
2335 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2336   MachineInstr &MI,
2337   unsigned &OpNoForForwarding,
2338   bool &SeenIntermediateUse) const {
2339   OpNoForForwarding = ~0U;
2340   MachineInstr *DefMI = nullptr;
2341   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2342   const TargetRegisterInfo *TRI = &getRegisterInfo();
2343   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2344   // within the basic block to see if the register is defined using an LI/LI8.
2345   if (MRI->isSSA()) {
2346     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2347       if (!MI.getOperand(i).isReg())
2348         continue;
2349       Register Reg = MI.getOperand(i).getReg();
2350       if (!Register::isVirtualRegister(Reg))
2351         continue;
2352       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2353       if (Register::isVirtualRegister(TrueReg)) {
2354         DefMI = MRI->getVRegDef(TrueReg);
2355         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) {
2356           OpNoForForwarding = i;
2357           break;
2358         }
2359       }
2360     }
2361   } else {
2362     // Looking back through the definition for each operand could be expensive,
2363     // so exit early if this isn't an instruction that either has an immediate
2364     // form or is already an immediate form that we can handle.
2365     ImmInstrInfo III;
2366     unsigned Opc = MI.getOpcode();
2367     bool ConvertibleImmForm =
2368         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
2369         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2370         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
2371         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
2372         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2373         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
2374         Opc == PPC::RLWINM8_rec;
2375     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2376                        ? isVFRegister(MI.getOperand(0).getReg())
2377                        : false;
2378     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2379       return nullptr;
2380 
2381     // Don't convert or %X, %Y, %Y since that's just a register move.
2382     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2383         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2384       return nullptr;
2385     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2386       MachineOperand &MO = MI.getOperand(i);
2387       SeenIntermediateUse = false;
2388       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2389         Register Reg = MI.getOperand(i).getReg();
2390         // If we see another use of this reg between the def and the MI,
2391         // we want to flat it so the def isn't deleted.
2392         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2393         if (DefMI) {
2394           // Is this register defined by some form of add-immediate (including
2395           // load-immediate) within this basic block?
2396           switch (DefMI->getOpcode()) {
2397           default:
2398             break;
2399           case PPC::LI:
2400           case PPC::LI8:
2401           case PPC::ADDItocL:
2402           case PPC::ADDI:
2403           case PPC::ADDI8:
2404             OpNoForForwarding = i;
2405             return DefMI;
2406           }
2407         }
2408       }
2409     }
2410   }
2411   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2412 }
2413 
2414 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2415   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2416       // Power 8
2417       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2418        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,
2419        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2420        PPC::SPILLTOVSR_ST, PPC::EVSTDD},
2421       // Power 9
2422       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2423        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,
2424        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2425        PPC::SPILLTOVSR_ST}};
2426 
2427   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2428 }
2429 
2430 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2431   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2432       // Power 8
2433       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2434        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,
2435        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2436        PPC::SPILLTOVSR_LD, PPC::EVLDD},
2437       // Power 9
2438       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2439        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32,
2440        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2441        PPC::SPILLTOVSR_LD}};
2442 
2443   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2444 }
2445 
2446 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI,
2447                                      unsigned RegNo) const {
2448   const MachineRegisterInfo &MRI =
2449       StartMI.getParent()->getParent()->getRegInfo();
2450   if (MRI.isSSA())
2451     return;
2452 
2453   // Instructions between [StartMI, EndMI] should be in same basic block.
2454   assert((StartMI.getParent() == EndMI.getParent()) &&
2455          "Instructions are not in same basic block");
2456 
2457   bool IsKillSet = false;
2458 
2459   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2460     MachineOperand &MO = MI.getOperand(Index);
2461     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2462         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2463       MO.setIsKill(false);
2464   };
2465 
2466   // Set killed flag for EndMI.
2467   // No need to do anything if EndMI defines RegNo.
2468   int UseIndex =
2469       EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2470   if (UseIndex != -1) {
2471     EndMI.getOperand(UseIndex).setIsKill(true);
2472     IsKillSet = true;
2473     // Clear killed flag for other EndMI operands related to RegNo. In some
2474     // upexpected cases, killed may be set multiple times for same register
2475     // operand in same MI.
2476     for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i)
2477       if (i != UseIndex)
2478         clearOperandKillInfo(EndMI, i);
2479   }
2480 
2481   // Walking the inst in reverse order (EndMI -> StartMI].
2482   MachineBasicBlock::reverse_iterator It = EndMI;
2483   MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend();
2484   // EndMI has been handled above, skip it here.
2485   It++;
2486   MachineOperand *MO = nullptr;
2487   for (; It != E; ++It) {
2488     // Skip insturctions which could not be a def/use of RegNo.
2489     if (It->isDebugInstr() || It->isPosition())
2490       continue;
2491 
2492     // Clear killed flag for all It operands related to RegNo. In some
2493     // upexpected cases, killed may be set multiple times for same register
2494     // operand in same MI.
2495     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2496         clearOperandKillInfo(*It, i);
2497 
2498     // If killed is not set, set killed for its last use or set dead for its def
2499     // if no use found.
2500     if (!IsKillSet) {
2501       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2502         // Use found, set it killed.
2503         IsKillSet = true;
2504         MO->setIsKill(true);
2505         continue;
2506       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2507                                                   &getRegisterInfo()))) {
2508         // No use found, set dead for its def.
2509         assert(&*It == &StartMI && "No new def between StartMI and EndMI.");
2510         MO->setIsDead(true);
2511         break;
2512       }
2513     }
2514 
2515     if ((&*It) == &StartMI)
2516       break;
2517   }
2518   // Ensure RegMo liveness is killed after EndMI.
2519   assert((IsKillSet || (MO && MO->isDead())) &&
2520          "RegNo should be killed or dead");
2521 }
2522 
2523 // This opt tries to convert the following imm form to an index form to save an
2524 // add for stack variables.
2525 // Return false if no such pattern found.
2526 //
2527 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
2528 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
2529 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
2530 //
2531 // can be converted to:
2532 //
2533 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
2534 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
2535 //
2536 // In order to eliminate ADD instr, make sure that:
2537 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
2538 //    new ADDI instr and ADDI can only take int16 Imm.
2539 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
2540 //    between ADDI and ADD instr since its original def in ADDI will be changed
2541 //    in new ADDI instr. And also there should be no new def for it between
2542 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
2543 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
2544 //    between ADD and Imm instr since ADD instr will be eliminated.
2545 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
2546 //    moved to Index instr.
2547 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
2548   MachineFunction *MF = MI.getParent()->getParent();
2549   MachineRegisterInfo *MRI = &MF->getRegInfo();
2550   bool PostRA = !MRI->isSSA();
2551   // Do this opt after PEI which is after RA. The reason is stack slot expansion
2552   // in PEI may expose such opportunities since in PEI, stack slot offsets to
2553   // frame base(OffsetAddi) are determined.
2554   if (!PostRA)
2555     return false;
2556   unsigned ToBeDeletedReg = 0;
2557   int64_t OffsetImm = 0;
2558   unsigned XFormOpcode = 0;
2559   ImmInstrInfo III;
2560 
2561   // Check if Imm instr meets requirement.
2562   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
2563                                     III))
2564     return false;
2565 
2566   bool OtherIntermediateUse = false;
2567   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
2568 
2569   // Exit if there is other use between ADD and Imm instr or no def found.
2570   if (OtherIntermediateUse || !ADDMI)
2571     return false;
2572 
2573   // Check if ADD instr meets requirement.
2574   if (!isADDInstrEligibleForFolding(*ADDMI))
2575     return false;
2576 
2577   unsigned ScaleRegIdx = 0;
2578   int64_t OffsetAddi = 0;
2579   MachineInstr *ADDIMI = nullptr;
2580 
2581   // Check if there is a valid ToBeChangedReg in ADDMI.
2582   // 1: It must be killed.
2583   // 2: Its definition must be a valid ADDIMI.
2584   // 3: It must satify int16 offset requirement.
2585   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
2586     ScaleRegIdx = 2;
2587   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
2588     ScaleRegIdx = 1;
2589   else
2590     return false;
2591 
2592   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
2593   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
2594   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
2595   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
2596                        MachineBasicBlock::iterator End) {
2597     for (auto It = ++Start; It != End; It++)
2598       if (It->modifiesRegister(Reg, &getRegisterInfo()))
2599         return true;
2600     return false;
2601   };
2602 
2603   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
2604   // treated as special zero when ScaleReg is R0/X0 register.
2605   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
2606       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
2607     return false;
2608 
2609   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
2610   // and Imm Instr.
2611   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
2612     return false;
2613 
2614   // Now start to do the transformation.
2615   LLVM_DEBUG(dbgs() << "Replace instruction: "
2616                     << "\n");
2617   LLVM_DEBUG(ADDIMI->dump());
2618   LLVM_DEBUG(ADDMI->dump());
2619   LLVM_DEBUG(MI.dump());
2620   LLVM_DEBUG(dbgs() << "with: "
2621                     << "\n");
2622 
2623   // Update ADDI instr.
2624   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
2625 
2626   // Update Imm instr.
2627   MI.setDesc(get(XFormOpcode));
2628   MI.getOperand(III.ImmOpNo)
2629       .ChangeToRegister(ScaleReg, false, false,
2630                         ADDMI->getOperand(ScaleRegIdx).isKill());
2631 
2632   MI.getOperand(III.OpNoForForwarding)
2633       .ChangeToRegister(ToBeChangedReg, false, false, true);
2634 
2635   // Eliminate ADD instr.
2636   ADDMI->eraseFromParent();
2637 
2638   LLVM_DEBUG(ADDIMI->dump());
2639   LLVM_DEBUG(MI.dump());
2640 
2641   return true;
2642 }
2643 
2644 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
2645                                                  int64_t &Imm) const {
2646   unsigned Opc = ADDIMI.getOpcode();
2647 
2648   // Exit if the instruction is not ADDI.
2649   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
2650     return false;
2651 
2652   Imm = ADDIMI.getOperand(2).getImm();
2653 
2654   return true;
2655 }
2656 
2657 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
2658   unsigned Opc = ADDMI.getOpcode();
2659 
2660   // Exit if the instruction is not ADD.
2661   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
2662 }
2663 
2664 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
2665                                                 unsigned &ToBeDeletedReg,
2666                                                 unsigned &XFormOpcode,
2667                                                 int64_t &OffsetImm,
2668                                                 ImmInstrInfo &III) const {
2669   // Only handle load/store.
2670   if (!MI.mayLoadOrStore())
2671     return false;
2672 
2673   unsigned Opc = MI.getOpcode();
2674 
2675   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
2676 
2677   // Exit if instruction has no index form.
2678   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
2679     return false;
2680 
2681   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
2682   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
2683                        III, true))
2684     return false;
2685 
2686   if (!III.IsSummingOperands)
2687     return false;
2688 
2689   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
2690   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
2691   // Only support imm operands, not relocation slots or others.
2692   if (!ImmOperand.isImm())
2693     return false;
2694 
2695   assert(RegOperand.isReg() && "Instruction format is not right");
2696 
2697   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
2698   if (!RegOperand.isKill())
2699     return false;
2700 
2701   ToBeDeletedReg = RegOperand.getReg();
2702   OffsetImm = ImmOperand.getImm();
2703 
2704   return true;
2705 }
2706 
2707 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
2708                                          MachineInstr *&ADDIMI,
2709                                          int64_t &OffsetAddi,
2710                                          int64_t OffsetImm) const {
2711   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
2712   MachineOperand &MO = ADDMI->getOperand(Index);
2713 
2714   if (!MO.isKill())
2715     return false;
2716 
2717   bool OtherIntermediateUse = false;
2718 
2719   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
2720   // Currently handle only one "add + Imminstr" pair case, exit if other
2721   // intermediate use for ToBeChangedReg found.
2722   // TODO: handle the cases where there are other "add + Imminstr" pairs
2723   // with same offset in Imminstr which is like:
2724   //
2725   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
2726   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
2727   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
2728   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
2729   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
2730   //
2731   // can be converted to:
2732   //
2733   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
2734   //                                       (OffsetAddi + OffsetImm)
2735   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
2736   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
2737 
2738   if (OtherIntermediateUse || !ADDIMI)
2739     return false;
2740   // Check if ADDI instr meets requirement.
2741   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
2742     return false;
2743 
2744   if (isInt<16>(OffsetAddi + OffsetImm))
2745     return true;
2746   return false;
2747 }
2748 
2749 // If this instruction has an immediate form and one of its operands is a
2750 // result of a load-immediate or an add-immediate, convert it to
2751 // the immediate form if the constant is in range.
2752 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
2753                                           MachineInstr **KilledDef) const {
2754   MachineFunction *MF = MI.getParent()->getParent();
2755   MachineRegisterInfo *MRI = &MF->getRegInfo();
2756   bool PostRA = !MRI->isSSA();
2757   bool SeenIntermediateUse = true;
2758   unsigned ForwardingOperand = ~0U;
2759   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
2760                                            SeenIntermediateUse);
2761   if (!DefMI)
2762     return false;
2763   assert(ForwardingOperand < MI.getNumOperands() &&
2764          "The forwarding operand needs to be valid at this point");
2765   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
2766   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
2767   Register ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg();
2768   if (KilledDef && KillFwdDefMI)
2769     *KilledDef = DefMI;
2770 
2771   ImmInstrInfo III;
2772   bool IsVFReg = MI.getOperand(0).isReg()
2773                      ? isVFRegister(MI.getOperand(0).getReg())
2774                      : false;
2775   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
2776   // If this is a reg+reg instruction that has a reg+imm form,
2777   // and one of the operands is produced by an add-immediate,
2778   // try to convert it.
2779   if (HasImmForm &&
2780       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
2781                                  KillFwdDefMI))
2782     return true;
2783 
2784   if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) ||
2785       !DefMI->getOperand(1).isImm())
2786     return false;
2787 
2788   int64_t Immediate = DefMI->getOperand(1).getImm();
2789   // Sign-extend to 64-bits.
2790   int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
2791     (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
2792 
2793   // If this is a reg+reg instruction that has a reg+imm form,
2794   // and one of the operands is produced by LI, convert it now.
2795   if (HasImmForm)
2796     return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm);
2797 
2798   bool ReplaceWithLI = false;
2799   bool Is64BitLI = false;
2800   int64_t NewImm = 0;
2801   bool SetCR = false;
2802   unsigned Opc = MI.getOpcode();
2803   switch (Opc) {
2804   default: return false;
2805 
2806   // FIXME: Any branches conditional on such a comparison can be made
2807   // unconditional. At this time, this happens too infrequently to be worth
2808   // the implementation effort, but if that ever changes, we could convert
2809   // such a pattern here.
2810   case PPC::CMPWI:
2811   case PPC::CMPLWI:
2812   case PPC::CMPDI:
2813   case PPC::CMPLDI: {
2814     // Doing this post-RA would require dataflow analysis to reliably find uses
2815     // of the CR register set by the compare.
2816     // No need to fixup killed/dead flag since this transformation is only valid
2817     // before RA.
2818     if (PostRA)
2819       return false;
2820     // If a compare-immediate is fed by an immediate and is itself an input of
2821     // an ISEL (the most common case) into a COPY of the correct register.
2822     bool Changed = false;
2823     Register DefReg = MI.getOperand(0).getReg();
2824     int64_t Comparand = MI.getOperand(2).getImm();
2825     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ?
2826       (Comparand | 0xFFFFFFFFFFFF0000) : Comparand;
2827 
2828     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
2829       unsigned UseOpc = CompareUseMI.getOpcode();
2830       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
2831         continue;
2832       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
2833       Register TrueReg = CompareUseMI.getOperand(1).getReg();
2834       Register FalseReg = CompareUseMI.getOperand(2).getReg();
2835       unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg,
2836                                      FalseReg, CRSubReg);
2837       if (RegToCopy == PPC::NoRegister)
2838         continue;
2839       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
2840       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
2841         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
2842         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
2843         CompareUseMI.RemoveOperand(3);
2844         CompareUseMI.RemoveOperand(2);
2845         continue;
2846       }
2847       LLVM_DEBUG(
2848           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
2849       LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump());
2850       LLVM_DEBUG(dbgs() << "Is converted to:\n");
2851       // Convert to copy and remove unneeded operands.
2852       CompareUseMI.setDesc(get(PPC::COPY));
2853       CompareUseMI.RemoveOperand(3);
2854       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
2855       CmpIselsConverted++;
2856       Changed = true;
2857       LLVM_DEBUG(CompareUseMI.dump());
2858     }
2859     if (Changed)
2860       return true;
2861     // This may end up incremented multiple times since this function is called
2862     // during a fixed-point transformation, but it is only meant to indicate the
2863     // presence of this opportunity.
2864     MissedConvertibleImmediateInstrs++;
2865     return false;
2866   }
2867 
2868   // Immediate forms - may simply be convertable to an LI.
2869   case PPC::ADDI:
2870   case PPC::ADDI8: {
2871     // Does the sum fit in a 16-bit signed field?
2872     int64_t Addend = MI.getOperand(2).getImm();
2873     if (isInt<16>(Addend + SExtImm)) {
2874       ReplaceWithLI = true;
2875       Is64BitLI = Opc == PPC::ADDI8;
2876       NewImm = Addend + SExtImm;
2877       break;
2878     }
2879     return false;
2880   }
2881   case PPC::RLDICL:
2882   case PPC::RLDICL_rec:
2883   case PPC::RLDICL_32:
2884   case PPC::RLDICL_32_64: {
2885     // Use APInt's rotate function.
2886     int64_t SH = MI.getOperand(2).getImm();
2887     int64_t MB = MI.getOperand(3).getImm();
2888     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
2889                 SExtImm, true);
2890     InVal = InVal.rotl(SH);
2891     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
2892     InVal &= Mask;
2893     // Can't replace negative values with an LI as that will sign-extend
2894     // and not clear the left bits. If we're setting the CR bit, we will use
2895     // ANDI_rec which won't sign extend, so that's safe.
2896     if (isUInt<15>(InVal.getSExtValue()) ||
2897         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
2898       ReplaceWithLI = true;
2899       Is64BitLI = Opc != PPC::RLDICL_32;
2900       NewImm = InVal.getSExtValue();
2901       SetCR = Opc == PPC::RLDICL_rec;
2902       break;
2903     }
2904     return false;
2905   }
2906   case PPC::RLWINM:
2907   case PPC::RLWINM8:
2908   case PPC::RLWINM_rec:
2909   case PPC::RLWINM8_rec: {
2910     int64_t SH = MI.getOperand(2).getImm();
2911     int64_t MB = MI.getOperand(3).getImm();
2912     int64_t ME = MI.getOperand(4).getImm();
2913     APInt InVal(32, SExtImm, true);
2914     InVal = InVal.rotl(SH);
2915     // Set the bits (        MB + 32        ) to (        ME + 32        ).
2916     uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2917     InVal &= Mask;
2918     // Can't replace negative values with an LI as that will sign-extend
2919     // and not clear the left bits. If we're setting the CR bit, we will use
2920     // ANDI_rec which won't sign extend, so that's safe.
2921     bool ValueFits = isUInt<15>(InVal.getSExtValue());
2922     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
2923                   isUInt<16>(InVal.getSExtValue()));
2924     if (ValueFits) {
2925       ReplaceWithLI = true;
2926       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
2927       NewImm = InVal.getSExtValue();
2928       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
2929       break;
2930     }
2931     return false;
2932   }
2933   case PPC::ORI:
2934   case PPC::ORI8:
2935   case PPC::XORI:
2936   case PPC::XORI8: {
2937     int64_t LogicalImm = MI.getOperand(2).getImm();
2938     int64_t Result = 0;
2939     if (Opc == PPC::ORI || Opc == PPC::ORI8)
2940       Result = LogicalImm | SExtImm;
2941     else
2942       Result = LogicalImm ^ SExtImm;
2943     if (isInt<16>(Result)) {
2944       ReplaceWithLI = true;
2945       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
2946       NewImm = Result;
2947       break;
2948     }
2949     return false;
2950   }
2951   }
2952 
2953   if (ReplaceWithLI) {
2954     // We need to be careful with CR-setting instructions we're replacing.
2955     if (SetCR) {
2956       // We don't know anything about uses when we're out of SSA, so only
2957       // replace if the new immediate will be reproduced.
2958       bool ImmChanged = (SExtImm & NewImm) != NewImm;
2959       if (PostRA && ImmChanged)
2960         return false;
2961 
2962       if (!PostRA) {
2963         // If the defining load-immediate has no other uses, we can just replace
2964         // the immediate with the new immediate.
2965         if (MRI->hasOneUse(DefMI->getOperand(0).getReg()))
2966           DefMI->getOperand(1).setImm(NewImm);
2967 
2968         // If we're not using the GPR result of the CR-setting instruction, we
2969         // just need to and with zero/non-zero depending on the new immediate.
2970         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
2971           if (NewImm) {
2972             assert(Immediate && "Transformation converted zero to non-zero?");
2973             NewImm = Immediate;
2974           }
2975         }
2976         else if (ImmChanged)
2977           return false;
2978       }
2979     }
2980 
2981     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
2982     LLVM_DEBUG(MI.dump());
2983     LLVM_DEBUG(dbgs() << "Fed by:\n");
2984     LLVM_DEBUG(DefMI->dump());
2985     LoadImmediateInfo LII;
2986     LII.Imm = NewImm;
2987     LII.Is64Bit = Is64BitLI;
2988     LII.SetCR = SetCR;
2989     // If we're setting the CR, the original load-immediate must be kept (as an
2990     // operand to ANDI_rec/ANDI8_rec).
2991     if (KilledDef && SetCR)
2992       *KilledDef = nullptr;
2993     replaceInstrWithLI(MI, LII);
2994 
2995     // Fixup killed/dead flag after transformation.
2996     // Pattern:
2997     // ForwardingOperandReg = LI imm1
2998     // y = op2 imm2, ForwardingOperandReg(killed)
2999     if (IsForwardingOperandKilled)
3000       fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg);
3001 
3002     LLVM_DEBUG(dbgs() << "With:\n");
3003     LLVM_DEBUG(MI.dump());
3004     return true;
3005   }
3006   return false;
3007 }
3008 
3009 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3010                                    ImmInstrInfo &III, bool PostRA) const {
3011   // The vast majority of the instructions would need their operand 2 replaced
3012   // with an immediate when switching to the reg+imm form. A marked exception
3013   // are the update form loads/stores for which a constant operand 2 would need
3014   // to turn into a displacement and move operand 1 to the operand 2 position.
3015   III.ImmOpNo = 2;
3016   III.OpNoForForwarding = 2;
3017   III.ImmWidth = 16;
3018   III.ImmMustBeMultipleOf = 1;
3019   III.TruncateImmTo = 0;
3020   III.IsSummingOperands = false;
3021   switch (Opc) {
3022   default: return false;
3023   case PPC::ADD4:
3024   case PPC::ADD8:
3025     III.SignedImm = true;
3026     III.ZeroIsSpecialOrig = 0;
3027     III.ZeroIsSpecialNew = 1;
3028     III.IsCommutative = true;
3029     III.IsSummingOperands = true;
3030     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3031     break;
3032   case PPC::ADDC:
3033   case PPC::ADDC8:
3034     III.SignedImm = true;
3035     III.ZeroIsSpecialOrig = 0;
3036     III.ZeroIsSpecialNew = 0;
3037     III.IsCommutative = true;
3038     III.IsSummingOperands = true;
3039     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3040     break;
3041   case PPC::ADDC_rec:
3042     III.SignedImm = true;
3043     III.ZeroIsSpecialOrig = 0;
3044     III.ZeroIsSpecialNew = 0;
3045     III.IsCommutative = true;
3046     III.IsSummingOperands = true;
3047     III.ImmOpcode = PPC::ADDIC_rec;
3048     break;
3049   case PPC::SUBFC:
3050   case PPC::SUBFC8:
3051     III.SignedImm = true;
3052     III.ZeroIsSpecialOrig = 0;
3053     III.ZeroIsSpecialNew = 0;
3054     III.IsCommutative = false;
3055     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3056     break;
3057   case PPC::CMPW:
3058   case PPC::CMPD:
3059     III.SignedImm = true;
3060     III.ZeroIsSpecialOrig = 0;
3061     III.ZeroIsSpecialNew = 0;
3062     III.IsCommutative = false;
3063     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3064     break;
3065   case PPC::CMPLW:
3066   case PPC::CMPLD:
3067     III.SignedImm = false;
3068     III.ZeroIsSpecialOrig = 0;
3069     III.ZeroIsSpecialNew = 0;
3070     III.IsCommutative = false;
3071     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3072     break;
3073   case PPC::AND_rec:
3074   case PPC::AND8_rec:
3075   case PPC::OR:
3076   case PPC::OR8:
3077   case PPC::XOR:
3078   case PPC::XOR8:
3079     III.SignedImm = false;
3080     III.ZeroIsSpecialOrig = 0;
3081     III.ZeroIsSpecialNew = 0;
3082     III.IsCommutative = true;
3083     switch(Opc) {
3084     default: llvm_unreachable("Unknown opcode");
3085     case PPC::AND_rec:
3086       III.ImmOpcode = PPC::ANDI_rec;
3087       break;
3088     case PPC::AND8_rec:
3089       III.ImmOpcode = PPC::ANDI8_rec;
3090       break;
3091     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3092     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3093     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3094     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3095     }
3096     break;
3097   case PPC::RLWNM:
3098   case PPC::RLWNM8:
3099   case PPC::RLWNM_rec:
3100   case PPC::RLWNM8_rec:
3101   case PPC::SLW:
3102   case PPC::SLW8:
3103   case PPC::SLW_rec:
3104   case PPC::SLW8_rec:
3105   case PPC::SRW:
3106   case PPC::SRW8:
3107   case PPC::SRW_rec:
3108   case PPC::SRW8_rec:
3109   case PPC::SRAW:
3110   case PPC::SRAW_rec:
3111     III.SignedImm = false;
3112     III.ZeroIsSpecialOrig = 0;
3113     III.ZeroIsSpecialNew = 0;
3114     III.IsCommutative = false;
3115     // This isn't actually true, but the instructions ignore any of the
3116     // upper bits, so any immediate loaded with an LI is acceptable.
3117     // This does not apply to shift right algebraic because a value
3118     // out of range will produce a -1/0.
3119     III.ImmWidth = 16;
3120     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3121         Opc == PPC::RLWNM8_rec)
3122       III.TruncateImmTo = 5;
3123     else
3124       III.TruncateImmTo = 6;
3125     switch(Opc) {
3126     default: llvm_unreachable("Unknown opcode");
3127     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3128     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3129     case PPC::RLWNM_rec:
3130       III.ImmOpcode = PPC::RLWINM_rec;
3131       break;
3132     case PPC::RLWNM8_rec:
3133       III.ImmOpcode = PPC::RLWINM8_rec;
3134       break;
3135     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3136     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3137     case PPC::SLW_rec:
3138       III.ImmOpcode = PPC::RLWINM_rec;
3139       break;
3140     case PPC::SLW8_rec:
3141       III.ImmOpcode = PPC::RLWINM8_rec;
3142       break;
3143     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3144     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3145     case PPC::SRW_rec:
3146       III.ImmOpcode = PPC::RLWINM_rec;
3147       break;
3148     case PPC::SRW8_rec:
3149       III.ImmOpcode = PPC::RLWINM8_rec;
3150       break;
3151     case PPC::SRAW:
3152       III.ImmWidth = 5;
3153       III.TruncateImmTo = 0;
3154       III.ImmOpcode = PPC::SRAWI;
3155       break;
3156     case PPC::SRAW_rec:
3157       III.ImmWidth = 5;
3158       III.TruncateImmTo = 0;
3159       III.ImmOpcode = PPC::SRAWI_rec;
3160       break;
3161     }
3162     break;
3163   case PPC::RLDCL:
3164   case PPC::RLDCL_rec:
3165   case PPC::RLDCR:
3166   case PPC::RLDCR_rec:
3167   case PPC::SLD:
3168   case PPC::SLD_rec:
3169   case PPC::SRD:
3170   case PPC::SRD_rec:
3171   case PPC::SRAD:
3172   case PPC::SRAD_rec:
3173     III.SignedImm = false;
3174     III.ZeroIsSpecialOrig = 0;
3175     III.ZeroIsSpecialNew = 0;
3176     III.IsCommutative = false;
3177     // This isn't actually true, but the instructions ignore any of the
3178     // upper bits, so any immediate loaded with an LI is acceptable.
3179     // This does not apply to shift right algebraic because a value
3180     // out of range will produce a -1/0.
3181     III.ImmWidth = 16;
3182     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3183         Opc == PPC::RLDCR_rec)
3184       III.TruncateImmTo = 6;
3185     else
3186       III.TruncateImmTo = 7;
3187     switch(Opc) {
3188     default: llvm_unreachable("Unknown opcode");
3189     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
3190     case PPC::RLDCL_rec:
3191       III.ImmOpcode = PPC::RLDICL_rec;
3192       break;
3193     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
3194     case PPC::RLDCR_rec:
3195       III.ImmOpcode = PPC::RLDICR_rec;
3196       break;
3197     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
3198     case PPC::SLD_rec:
3199       III.ImmOpcode = PPC::RLDICR_rec;
3200       break;
3201     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
3202     case PPC::SRD_rec:
3203       III.ImmOpcode = PPC::RLDICL_rec;
3204       break;
3205     case PPC::SRAD:
3206       III.ImmWidth = 6;
3207       III.TruncateImmTo = 0;
3208       III.ImmOpcode = PPC::SRADI;
3209        break;
3210     case PPC::SRAD_rec:
3211       III.ImmWidth = 6;
3212       III.TruncateImmTo = 0;
3213       III.ImmOpcode = PPC::SRADI_rec;
3214       break;
3215     }
3216     break;
3217   // Loads and stores:
3218   case PPC::LBZX:
3219   case PPC::LBZX8:
3220   case PPC::LHZX:
3221   case PPC::LHZX8:
3222   case PPC::LHAX:
3223   case PPC::LHAX8:
3224   case PPC::LWZX:
3225   case PPC::LWZX8:
3226   case PPC::LWAX:
3227   case PPC::LDX:
3228   case PPC::LFSX:
3229   case PPC::LFDX:
3230   case PPC::STBX:
3231   case PPC::STBX8:
3232   case PPC::STHX:
3233   case PPC::STHX8:
3234   case PPC::STWX:
3235   case PPC::STWX8:
3236   case PPC::STDX:
3237   case PPC::STFSX:
3238   case PPC::STFDX:
3239     III.SignedImm = true;
3240     III.ZeroIsSpecialOrig = 1;
3241     III.ZeroIsSpecialNew = 2;
3242     III.IsCommutative = true;
3243     III.IsSummingOperands = true;
3244     III.ImmOpNo = 1;
3245     III.OpNoForForwarding = 2;
3246     switch(Opc) {
3247     default: llvm_unreachable("Unknown opcode");
3248     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3249     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3250     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3251     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3252     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3253     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3254     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3255     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3256     case PPC::LWAX:
3257       III.ImmOpcode = PPC::LWA;
3258       III.ImmMustBeMultipleOf = 4;
3259       break;
3260     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3261     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3262     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3263     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3264     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3265     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3266     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3267     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3268     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3269     case PPC::STDX:
3270       III.ImmOpcode = PPC::STD;
3271       III.ImmMustBeMultipleOf = 4;
3272       break;
3273     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3274     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3275     }
3276     break;
3277   case PPC::LBZUX:
3278   case PPC::LBZUX8:
3279   case PPC::LHZUX:
3280   case PPC::LHZUX8:
3281   case PPC::LHAUX:
3282   case PPC::LHAUX8:
3283   case PPC::LWZUX:
3284   case PPC::LWZUX8:
3285   case PPC::LDUX:
3286   case PPC::LFSUX:
3287   case PPC::LFDUX:
3288   case PPC::STBUX:
3289   case PPC::STBUX8:
3290   case PPC::STHUX:
3291   case PPC::STHUX8:
3292   case PPC::STWUX:
3293   case PPC::STWUX8:
3294   case PPC::STDUX:
3295   case PPC::STFSUX:
3296   case PPC::STFDUX:
3297     III.SignedImm = true;
3298     III.ZeroIsSpecialOrig = 2;
3299     III.ZeroIsSpecialNew = 3;
3300     III.IsCommutative = false;
3301     III.IsSummingOperands = true;
3302     III.ImmOpNo = 2;
3303     III.OpNoForForwarding = 3;
3304     switch(Opc) {
3305     default: llvm_unreachable("Unknown opcode");
3306     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3307     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3308     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3309     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3310     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3311     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3312     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3313     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3314     case PPC::LDUX:
3315       III.ImmOpcode = PPC::LDU;
3316       III.ImmMustBeMultipleOf = 4;
3317       break;
3318     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3319     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3320     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3321     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3322     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3323     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3324     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3325     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3326     case PPC::STDUX:
3327       III.ImmOpcode = PPC::STDU;
3328       III.ImmMustBeMultipleOf = 4;
3329       break;
3330     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3331     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3332     }
3333     break;
3334   // Power9 and up only. For some of these, the X-Form version has access to all
3335   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3336   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3337   // into or stored from is one of the VR registers.
3338   case PPC::LXVX:
3339   case PPC::LXSSPX:
3340   case PPC::LXSDX:
3341   case PPC::STXVX:
3342   case PPC::STXSSPX:
3343   case PPC::STXSDX:
3344   case PPC::XFLOADf32:
3345   case PPC::XFLOADf64:
3346   case PPC::XFSTOREf32:
3347   case PPC::XFSTOREf64:
3348     if (!Subtarget.hasP9Vector())
3349       return false;
3350     III.SignedImm = true;
3351     III.ZeroIsSpecialOrig = 1;
3352     III.ZeroIsSpecialNew = 2;
3353     III.IsCommutative = true;
3354     III.IsSummingOperands = true;
3355     III.ImmOpNo = 1;
3356     III.OpNoForForwarding = 2;
3357     III.ImmMustBeMultipleOf = 4;
3358     switch(Opc) {
3359     default: llvm_unreachable("Unknown opcode");
3360     case PPC::LXVX:
3361       III.ImmOpcode = PPC::LXV;
3362       III.ImmMustBeMultipleOf = 16;
3363       break;
3364     case PPC::LXSSPX:
3365       if (PostRA) {
3366         if (IsVFReg)
3367           III.ImmOpcode = PPC::LXSSP;
3368         else {
3369           III.ImmOpcode = PPC::LFS;
3370           III.ImmMustBeMultipleOf = 1;
3371         }
3372         break;
3373       }
3374       LLVM_FALLTHROUGH;
3375     case PPC::XFLOADf32:
3376       III.ImmOpcode = PPC::DFLOADf32;
3377       break;
3378     case PPC::LXSDX:
3379       if (PostRA) {
3380         if (IsVFReg)
3381           III.ImmOpcode = PPC::LXSD;
3382         else {
3383           III.ImmOpcode = PPC::LFD;
3384           III.ImmMustBeMultipleOf = 1;
3385         }
3386         break;
3387       }
3388       LLVM_FALLTHROUGH;
3389     case PPC::XFLOADf64:
3390       III.ImmOpcode = PPC::DFLOADf64;
3391       break;
3392     case PPC::STXVX:
3393       III.ImmOpcode = PPC::STXV;
3394       III.ImmMustBeMultipleOf = 16;
3395       break;
3396     case PPC::STXSSPX:
3397       if (PostRA) {
3398         if (IsVFReg)
3399           III.ImmOpcode = PPC::STXSSP;
3400         else {
3401           III.ImmOpcode = PPC::STFS;
3402           III.ImmMustBeMultipleOf = 1;
3403         }
3404         break;
3405       }
3406       LLVM_FALLTHROUGH;
3407     case PPC::XFSTOREf32:
3408       III.ImmOpcode = PPC::DFSTOREf32;
3409       break;
3410     case PPC::STXSDX:
3411       if (PostRA) {
3412         if (IsVFReg)
3413           III.ImmOpcode = PPC::STXSD;
3414         else {
3415           III.ImmOpcode = PPC::STFD;
3416           III.ImmMustBeMultipleOf = 1;
3417         }
3418         break;
3419       }
3420       LLVM_FALLTHROUGH;
3421     case PPC::XFSTOREf64:
3422       III.ImmOpcode = PPC::DFSTOREf64;
3423       break;
3424     }
3425     break;
3426   }
3427   return true;
3428 }
3429 
3430 // Utility function for swaping two arbitrary operands of an instruction.
3431 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3432   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3433 
3434   unsigned MaxOp = std::max(Op1, Op2);
3435   unsigned MinOp = std::min(Op1, Op2);
3436   MachineOperand MOp1 = MI.getOperand(MinOp);
3437   MachineOperand MOp2 = MI.getOperand(MaxOp);
3438   MI.RemoveOperand(std::max(Op1, Op2));
3439   MI.RemoveOperand(std::min(Op1, Op2));
3440 
3441   // If the operands we are swapping are the two at the end (the common case)
3442   // we can just remove both and add them in the opposite order.
3443   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3444     MI.addOperand(MOp2);
3445     MI.addOperand(MOp1);
3446   } else {
3447     // Store all operands in a temporary vector, remove them and re-add in the
3448     // right order.
3449     SmallVector<MachineOperand, 2> MOps;
3450     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3451     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3452       MOps.push_back(MI.getOperand(i));
3453       MI.RemoveOperand(i);
3454     }
3455     // MOp2 needs to be added next.
3456     MI.addOperand(MOp2);
3457     // Now add the rest.
3458     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3459       if (i == MaxOp)
3460         MI.addOperand(MOp1);
3461       else {
3462         MI.addOperand(MOps.back());
3463         MOps.pop_back();
3464       }
3465     }
3466   }
3467 }
3468 
3469 // Check if the 'MI' that has the index OpNoForForwarding
3470 // meets the requirement described in the ImmInstrInfo.
3471 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3472                                                const ImmInstrInfo &III,
3473                                                unsigned OpNoForForwarding
3474                                                ) const {
3475   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3476   // would not work pre-RA, we can only do the check post RA.
3477   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3478   if (MRI.isSSA())
3479     return false;
3480 
3481   // Cannot do the transform if MI isn't summing the operands.
3482   if (!III.IsSummingOperands)
3483     return false;
3484 
3485   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3486   if (!III.ZeroIsSpecialOrig)
3487     return false;
3488 
3489   // We cannot do the transform if the operand we are trying to replace
3490   // isn't the same as the operand the instruction allows.
3491   if (OpNoForForwarding != III.OpNoForForwarding)
3492     return false;
3493 
3494   // Check if the instruction we are trying to transform really has
3495   // the special zero register as its operand.
3496   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3497       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3498     return false;
3499 
3500   // This machine instruction is convertible if it is,
3501   // 1. summing the operands.
3502   // 2. one of the operands is special zero register.
3503   // 3. the operand we are trying to replace is allowed by the MI.
3504   return true;
3505 }
3506 
3507 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3508 // accordingly.
3509 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3510                                                const ImmInstrInfo &III,
3511                                                MachineOperand *&ImmMO,
3512                                                MachineOperand *&RegMO) const {
3513   unsigned Opc = DefMI.getOpcode();
3514   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3515     return false;
3516 
3517   assert(DefMI.getNumOperands() >= 3 &&
3518          "Add inst must have at least three operands");
3519   RegMO = &DefMI.getOperand(1);
3520   ImmMO = &DefMI.getOperand(2);
3521 
3522   // This DefMI is elgible for forwarding if it is:
3523   // 1. add inst
3524   // 2. one of the operands is Imm/CPI/Global.
3525   return isAnImmediateOperand(*ImmMO);
3526 }
3527 
3528 bool PPCInstrInfo::isRegElgibleForForwarding(
3529     const MachineOperand &RegMO, const MachineInstr &DefMI,
3530     const MachineInstr &MI, bool KillDefMI,
3531     bool &IsFwdFeederRegKilled) const {
3532   // x = addi y, imm
3533   // ...
3534   // z = lfdx 0, x   -> z = lfd imm(y)
3535   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3536   // of "y" between the DEF of "x" and "z".
3537   // The query is only valid post RA.
3538   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3539   if (MRI.isSSA())
3540     return false;
3541 
3542   Register Reg = RegMO.getReg();
3543 
3544   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3545   MachineBasicBlock::const_reverse_iterator It = MI;
3546   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3547   It++;
3548   for (; It != E; ++It) {
3549     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3550       return false;
3551     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3552       IsFwdFeederRegKilled = true;
3553     // Made it to DefMI without encountering a clobber.
3554     if ((&*It) == &DefMI)
3555       break;
3556   }
3557   assert((&*It) == &DefMI && "DefMI is missing");
3558 
3559   // If DefMI also defines the register to be forwarded, we can only forward it
3560   // if DefMI is being erased.
3561   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3562     return KillDefMI;
3563 
3564   return true;
3565 }
3566 
3567 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3568                                              const MachineInstr &DefMI,
3569                                              const ImmInstrInfo &III,
3570                                              int64_t &Imm) const {
3571   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3572   if (DefMI.getOpcode() == PPC::ADDItocL) {
3573     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3574     // However, we know that, it is 16-bit width, and has the alignment of 4.
3575     // Check if the instruction met the requirement.
3576     if (III.ImmMustBeMultipleOf > 4 ||
3577        III.TruncateImmTo || III.ImmWidth != 16)
3578       return false;
3579 
3580     // Going from XForm to DForm loads means that the displacement needs to be
3581     // not just an immediate but also a multiple of 4, or 16 depending on the
3582     // load. A DForm load cannot be represented if it is a multiple of say 2.
3583     // XForm loads do not have this restriction.
3584     if (ImmMO.isGlobal() &&
3585         ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf)
3586       return false;
3587 
3588     return true;
3589   }
3590 
3591   if (ImmMO.isImm()) {
3592     // It is Imm, we need to check if the Imm fit the range.
3593     int64_t Immediate = ImmMO.getImm();
3594     // Sign-extend to 64-bits.
3595     Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
3596       (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
3597 
3598     if (Imm % III.ImmMustBeMultipleOf)
3599       return false;
3600     if (III.TruncateImmTo)
3601       Imm &= ((1 << III.TruncateImmTo) - 1);
3602     if (III.SignedImm) {
3603       APInt ActualValue(64, Imm, true);
3604       if (!ActualValue.isSignedIntN(III.ImmWidth))
3605         return false;
3606     } else {
3607       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3608       if ((uint64_t)Imm > UnsignedMax)
3609         return false;
3610     }
3611   }
3612   else
3613     return false;
3614 
3615   // This ImmMO is forwarded if it meets the requriement describle
3616   // in ImmInstrInfo
3617   return true;
3618 }
3619 
3620 // If an X-Form instruction is fed by an add-immediate and one of its operands
3621 // is the literal zero, attempt to forward the source of the add-immediate to
3622 // the corresponding D-Form instruction with the displacement coming from
3623 // the immediate being added.
3624 bool PPCInstrInfo::transformToImmFormFedByAdd(
3625     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
3626     MachineInstr &DefMI, bool KillDefMI) const {
3627   //         RegMO ImmMO
3628   //           |    |
3629   // x = addi reg, imm  <----- DefMI
3630   // y = op    0 ,  x   <----- MI
3631   //                |
3632   //         OpNoForForwarding
3633   // Check if the MI meet the requirement described in the III.
3634   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
3635     return false;
3636 
3637   // Check if the DefMI meet the requirement
3638   // described in the III. If yes, set the ImmMO and RegMO accordingly.
3639   MachineOperand *ImmMO = nullptr;
3640   MachineOperand *RegMO = nullptr;
3641   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
3642     return false;
3643   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
3644 
3645   // As we get the Imm operand now, we need to check if the ImmMO meet
3646   // the requirement described in the III. If yes set the Imm.
3647   int64_t Imm = 0;
3648   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
3649     return false;
3650 
3651   bool IsFwdFeederRegKilled = false;
3652   // Check if the RegMO can be forwarded to MI.
3653   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
3654                                  IsFwdFeederRegKilled))
3655     return false;
3656 
3657   // Get killed info in case fixup needed after transformation.
3658   unsigned ForwardKilledOperandReg = ~0U;
3659   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3660   bool PostRA = !MRI.isSSA();
3661   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
3662     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
3663 
3664   // We know that, the MI and DefMI both meet the pattern, and
3665   // the Imm also meet the requirement with the new Imm-form.
3666   // It is safe to do the transformation now.
3667   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3668   LLVM_DEBUG(MI.dump());
3669   LLVM_DEBUG(dbgs() << "Fed by:\n");
3670   LLVM_DEBUG(DefMI.dump());
3671 
3672   // Update the base reg first.
3673   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
3674                                                         false, false,
3675                                                         RegMO->isKill());
3676 
3677   // Then, update the imm.
3678   if (ImmMO->isImm()) {
3679     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
3680     // directly.
3681     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
3682   }
3683   else {
3684     // Otherwise, it is Constant Pool Index(CPI) or Global,
3685     // which is relocation in fact. We need to replace the special zero
3686     // register with ImmMO.
3687     // Before that, we need to fixup the target flags for imm.
3688     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
3689     if (DefMI.getOpcode() == PPC::ADDItocL)
3690       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
3691 
3692     // MI didn't have the interface such as MI.setOperand(i) though
3693     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
3694     // ImmMO, we need to remove ZERO operand and all the operands behind it,
3695     // and, add the ImmMO, then, move back all the operands behind ZERO.
3696     SmallVector<MachineOperand, 2> MOps;
3697     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
3698       MOps.push_back(MI.getOperand(i));
3699       MI.RemoveOperand(i);
3700     }
3701 
3702     // Remove the last MO in the list, which is ZERO operand in fact.
3703     MOps.pop_back();
3704     // Add the imm operand.
3705     MI.addOperand(*ImmMO);
3706     // Now add the rest back.
3707     for (auto &MO : MOps)
3708       MI.addOperand(MO);
3709   }
3710 
3711   // Update the opcode.
3712   MI.setDesc(get(III.ImmOpcode));
3713 
3714   // Fix up killed/dead flag after transformation.
3715   // Pattern 1:
3716   // x = ADD KilledFwdFeederReg, imm
3717   // n = opn KilledFwdFeederReg(killed), regn
3718   // y = XOP 0, x
3719   // Pattern 2:
3720   // x = ADD reg(killed), imm
3721   // y = XOP 0, x
3722   if (IsFwdFeederRegKilled || RegMO->isKill())
3723     fixupIsDeadOrKill(DefMI, MI, RegMO->getReg());
3724   // Pattern 3:
3725   // ForwardKilledOperandReg = ADD reg, imm
3726   // y = XOP 0, ForwardKilledOperandReg(killed)
3727   if (ForwardKilledOperandReg != ~0U)
3728     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3729 
3730   LLVM_DEBUG(dbgs() << "With:\n");
3731   LLVM_DEBUG(MI.dump());
3732 
3733   return true;
3734 }
3735 
3736 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
3737                                              const ImmInstrInfo &III,
3738                                              unsigned ConstantOpNo,
3739                                              MachineInstr &DefMI,
3740                                              int64_t Imm) const {
3741   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3742   bool PostRA = !MRI.isSSA();
3743   // Exit early if we can't convert this.
3744   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
3745     return false;
3746   if (Imm % III.ImmMustBeMultipleOf)
3747     return false;
3748   if (III.TruncateImmTo)
3749     Imm &= ((1 << III.TruncateImmTo) - 1);
3750   if (III.SignedImm) {
3751     APInt ActualValue(64, Imm, true);
3752     if (!ActualValue.isSignedIntN(III.ImmWidth))
3753       return false;
3754   } else {
3755     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3756     if ((uint64_t)Imm > UnsignedMax)
3757       return false;
3758   }
3759 
3760   // If we're post-RA, the instructions don't agree on whether register zero is
3761   // special, we can transform this as long as the register operand that will
3762   // end up in the location where zero is special isn't R0.
3763   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3764     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
3765       III.ZeroIsSpecialNew + 1;
3766     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
3767     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3768     // If R0 is in the operand where zero is special for the new instruction,
3769     // it is unsafe to transform if the constant operand isn't that operand.
3770     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
3771         ConstantOpNo != III.ZeroIsSpecialNew)
3772       return false;
3773     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
3774         ConstantOpNo != PosForOrigZero)
3775       return false;
3776   }
3777 
3778   // Get killed info in case fixup needed after transformation.
3779   unsigned ForwardKilledOperandReg = ~0U;
3780   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
3781     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
3782 
3783   unsigned Opc = MI.getOpcode();
3784   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
3785                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
3786                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
3787                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
3788   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
3789                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
3790   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
3791                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
3792   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
3793                     Opc == PPC::SRD_rec;
3794 
3795   MI.setDesc(get(III.ImmOpcode));
3796   if (ConstantOpNo == III.OpNoForForwarding) {
3797     // Converting shifts to immediate form is a bit tricky since they may do
3798     // one of three things:
3799     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
3800     // 2. If the shift amount is zero, the result is unchanged (save for maybe
3801     //    setting CR0)
3802     // 3. If the shift amount is in [1, OpSize), it's just a shift
3803     if (SpecialShift32 || SpecialShift64) {
3804       LoadImmediateInfo LII;
3805       LII.Imm = 0;
3806       LII.SetCR = SetCR;
3807       LII.Is64Bit = SpecialShift64;
3808       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
3809       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
3810         replaceInstrWithLI(MI, LII);
3811       // Shifts by zero don't change the value. If we don't need to set CR0,
3812       // just convert this to a COPY. Can't do this post-RA since we've already
3813       // cleaned up the copies.
3814       else if (!SetCR && ShAmt == 0 && !PostRA) {
3815         MI.RemoveOperand(2);
3816         MI.setDesc(get(PPC::COPY));
3817       } else {
3818         // The 32 bit and 64 bit instructions are quite different.
3819         if (SpecialShift32) {
3820           // Left shifts use (N, 0, 31-N).
3821           // Right shifts use (32-N, N, 31) if 0 < N < 32.
3822           //              use (0, 0, 31)    if N == 0.
3823           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
3824           uint64_t MB = RightShift ? ShAmt : 0;
3825           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
3826           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3827           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
3828             .addImm(ME);
3829         } else {
3830           // Left shifts use (N, 63-N).
3831           // Right shifts use (64-N, N) if 0 < N < 64.
3832           //              use (0, 0)    if N == 0.
3833           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
3834           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
3835           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3836           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
3837         }
3838       }
3839     } else
3840       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3841   }
3842   // Convert commutative instructions (switch the operands and convert the
3843   // desired one to an immediate.
3844   else if (III.IsCommutative) {
3845     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3846     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
3847   } else
3848     llvm_unreachable("Should have exited early!");
3849 
3850   // For instructions for which the constant register replaces a different
3851   // operand than where the immediate goes, we need to swap them.
3852   if (III.OpNoForForwarding != III.ImmOpNo)
3853     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
3854 
3855   // If the special R0/X0 register index are different for original instruction
3856   // and new instruction, we need to fix up the register class in new
3857   // instruction.
3858   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3859     if (III.ZeroIsSpecialNew) {
3860       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
3861       // need to fix up register class.
3862       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3863       if (Register::isVirtualRegister(RegToModify)) {
3864         const TargetRegisterClass *NewRC =
3865           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
3866           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
3867         MRI.setRegClass(RegToModify, NewRC);
3868       }
3869     }
3870   }
3871 
3872   // Fix up killed/dead flag after transformation.
3873   // Pattern:
3874   // ForwardKilledOperandReg = LI imm
3875   // y = XOP reg, ForwardKilledOperandReg(killed)
3876   if (ForwardKilledOperandReg != ~0U)
3877     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3878   return true;
3879 }
3880 
3881 const TargetRegisterClass *
3882 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
3883   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
3884     return &PPC::VSRCRegClass;
3885   return RC;
3886 }
3887 
3888 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
3889   return PPC::getRecordFormOpcode(Opcode);
3890 }
3891 
3892 // This function returns true if the machine instruction
3893 // always outputs a value by sign-extending a 32 bit value,
3894 // i.e. 0 to 31-th bits are same as 32-th bit.
3895 static bool isSignExtendingOp(const MachineInstr &MI) {
3896   int Opcode = MI.getOpcode();
3897   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
3898       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
3899       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
3900       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
3901       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
3902       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
3903       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
3904       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3905       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
3906       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
3907       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
3908       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
3909       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
3910       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
3911       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
3912       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
3913       Opcode == PPC::EXTSB8_32_64)
3914     return true;
3915 
3916   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
3917     return true;
3918 
3919   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3920        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
3921       MI.getOperand(3).getImm() > 0 &&
3922       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3923     return true;
3924 
3925   return false;
3926 }
3927 
3928 // This function returns true if the machine instruction
3929 // always outputs zeros in higher 32 bits.
3930 static bool isZeroExtendingOp(const MachineInstr &MI) {
3931   int Opcode = MI.getOpcode();
3932   // The 16-bit immediate is sign-extended in li/lis.
3933   // If the most significant bit is zero, all higher bits are zero.
3934   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
3935       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
3936     int64_t Imm = MI.getOperand(1).getImm();
3937     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
3938       return true;
3939   }
3940 
3941   // We have some variations of rotate-and-mask instructions
3942   // that clear higher 32-bits.
3943   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
3944        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
3945        Opcode == PPC::RLDICL_32_64) &&
3946       MI.getOperand(3).getImm() >= 32)
3947     return true;
3948 
3949   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
3950       MI.getOperand(3).getImm() >= 32 &&
3951       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
3952     return true;
3953 
3954   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3955        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
3956        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
3957       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3958     return true;
3959 
3960   // There are other instructions that clear higher 32-bits.
3961   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
3962       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
3963       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
3964       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
3965       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
3966       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
3967       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
3968       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
3969       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
3970       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
3971       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
3972       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
3973       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
3974       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
3975       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
3976       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
3977       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
3978       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
3979       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3980       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
3981       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
3982       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
3983       Opcode == PPC::MFVSRWZ)
3984     return true;
3985 
3986   return false;
3987 }
3988 
3989 // This function returns true if the input MachineInstr is a TOC save
3990 // instruction.
3991 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
3992   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
3993     return false;
3994   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
3995   unsigned StackOffset = MI.getOperand(1).getImm();
3996   Register StackReg = MI.getOperand(2).getReg();
3997   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
3998     return true;
3999 
4000   return false;
4001 }
4002 
4003 // We limit the max depth to track incoming values of PHIs or binary ops
4004 // (e.g. AND) to avoid excessive cost.
4005 const unsigned MAX_DEPTH = 1;
4006 
4007 bool
4008 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
4009                                    const unsigned Depth) const {
4010   const MachineFunction *MF = MI.getParent()->getParent();
4011   const MachineRegisterInfo *MRI = &MF->getRegInfo();
4012 
4013   // If we know this instruction returns sign- or zero-extended result,
4014   // return true.
4015   if (SignExt ? isSignExtendingOp(MI):
4016                 isZeroExtendingOp(MI))
4017     return true;
4018 
4019   switch (MI.getOpcode()) {
4020   case PPC::COPY: {
4021     Register SrcReg = MI.getOperand(1).getReg();
4022 
4023     // In both ELFv1 and v2 ABI, method parameters and the return value
4024     // are sign- or zero-extended.
4025     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
4026       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
4027       // We check the ZExt/SExt flags for a method parameter.
4028       if (MI.getParent()->getBasicBlock() ==
4029           &MF->getFunction().getEntryBlock()) {
4030         Register VReg = MI.getOperand(0).getReg();
4031         if (MF->getRegInfo().isLiveIn(VReg))
4032           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
4033                            FuncInfo->isLiveInZExt(VReg);
4034       }
4035 
4036       // For a method return value, we check the ZExt/SExt flags in attribute.
4037       // We assume the following code sequence for method call.
4038       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
4039       //   BL8_NOP @func,...
4040       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
4041       //   %5 = COPY %x3; G8RC:%5
4042       if (SrcReg == PPC::X3) {
4043         const MachineBasicBlock *MBB = MI.getParent();
4044         MachineBasicBlock::const_instr_iterator II =
4045           MachineBasicBlock::const_instr_iterator(&MI);
4046         if (II != MBB->instr_begin() &&
4047             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
4048           const MachineInstr &CallMI = *(--II);
4049           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
4050             const Function *CalleeFn =
4051               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
4052             if (!CalleeFn)
4053               return false;
4054             const IntegerType *IntTy =
4055               dyn_cast<IntegerType>(CalleeFn->getReturnType());
4056             const AttributeSet &Attrs =
4057               CalleeFn->getAttributes().getRetAttributes();
4058             if (IntTy && IntTy->getBitWidth() <= 32)
4059               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
4060                                                   Attribute::ZExt);
4061           }
4062         }
4063       }
4064     }
4065 
4066     // If this is a copy from another register, we recursively check source.
4067     if (!Register::isVirtualRegister(SrcReg))
4068       return false;
4069     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4070     if (SrcMI != NULL)
4071       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4072 
4073     return false;
4074   }
4075 
4076   case PPC::ANDI_rec:
4077   case PPC::ANDIS_rec:
4078   case PPC::ORI:
4079   case PPC::ORIS:
4080   case PPC::XORI:
4081   case PPC::XORIS:
4082   case PPC::ANDI8_rec:
4083   case PPC::ANDIS8_rec:
4084   case PPC::ORI8:
4085   case PPC::ORIS8:
4086   case PPC::XORI8:
4087   case PPC::XORIS8: {
4088     // logical operation with 16-bit immediate does not change the upper bits.
4089     // So, we track the operand register as we do for register copy.
4090     Register SrcReg = MI.getOperand(1).getReg();
4091     if (!Register::isVirtualRegister(SrcReg))
4092       return false;
4093     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4094     if (SrcMI != NULL)
4095       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4096 
4097     return false;
4098   }
4099 
4100   // If all incoming values are sign-/zero-extended,
4101   // the output of OR, ISEL or PHI is also sign-/zero-extended.
4102   case PPC::OR:
4103   case PPC::OR8:
4104   case PPC::ISEL:
4105   case PPC::PHI: {
4106     if (Depth >= MAX_DEPTH)
4107       return false;
4108 
4109     // The input registers for PHI are operand 1, 3, ...
4110     // The input registers for others are operand 1 and 2.
4111     unsigned E = 3, D = 1;
4112     if (MI.getOpcode() == PPC::PHI) {
4113       E = MI.getNumOperands();
4114       D = 2;
4115     }
4116 
4117     for (unsigned I = 1; I != E; I += D) {
4118       if (MI.getOperand(I).isReg()) {
4119         Register SrcReg = MI.getOperand(I).getReg();
4120         if (!Register::isVirtualRegister(SrcReg))
4121           return false;
4122         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4123         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
4124           return false;
4125       }
4126       else
4127         return false;
4128     }
4129     return true;
4130   }
4131 
4132   // If at least one of the incoming values of an AND is zero extended
4133   // then the output is also zero-extended. If both of the incoming values
4134   // are sign-extended then the output is also sign extended.
4135   case PPC::AND:
4136   case PPC::AND8: {
4137     if (Depth >= MAX_DEPTH)
4138        return false;
4139 
4140     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
4141 
4142     Register SrcReg1 = MI.getOperand(1).getReg();
4143     Register SrcReg2 = MI.getOperand(2).getReg();
4144 
4145     if (!Register::isVirtualRegister(SrcReg1) ||
4146         !Register::isVirtualRegister(SrcReg2))
4147       return false;
4148 
4149     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
4150     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
4151     if (!MISrc1 || !MISrc2)
4152         return false;
4153 
4154     if(SignExt)
4155         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
4156                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4157     else
4158         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
4159                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4160   }
4161 
4162   default:
4163     break;
4164   }
4165   return false;
4166 }
4167 
4168 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
4169   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
4170 }
4171 
4172 namespace {
4173 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
4174   MachineInstr *Loop, *EndLoop, *LoopCount;
4175   MachineFunction *MF;
4176   const TargetInstrInfo *TII;
4177   int64_t TripCount;
4178 
4179 public:
4180   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
4181                        MachineInstr *LoopCount)
4182       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
4183         MF(Loop->getParent()->getParent()),
4184         TII(MF->getSubtarget().getInstrInfo()) {
4185     // Inspect the Loop instruction up-front, as it may be deleted when we call
4186     // createTripCountGreaterCondition.
4187     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
4188       TripCount = LoopCount->getOperand(1).getImm();
4189     else
4190       TripCount = -1;
4191   }
4192 
4193   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
4194     // Only ignore the terminator.
4195     return MI == EndLoop;
4196   }
4197 
4198   Optional<bool>
4199   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
4200                                   SmallVectorImpl<MachineOperand> &Cond) override {
4201     if (TripCount == -1) {
4202       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4203       // so we don't need to generate any thing here.
4204       Cond.push_back(MachineOperand::CreateImm(0));
4205       Cond.push_back(MachineOperand::CreateReg(
4206           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
4207           true));
4208       return {};
4209     }
4210 
4211     return TripCount > TC;
4212   }
4213 
4214   void setPreheader(MachineBasicBlock *NewPreheader) override {
4215     // Do nothing. We want the LOOP setup instruction to stay in the *old*
4216     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
4217   }
4218 
4219   void adjustTripCount(int TripCountAdjust) override {
4220     // If the loop trip count is a compile-time value, then just change the
4221     // value.
4222     if (LoopCount->getOpcode() == PPC::LI8 ||
4223         LoopCount->getOpcode() == PPC::LI) {
4224       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
4225       LoopCount->getOperand(1).setImm(TripCount);
4226       return;
4227     }
4228 
4229     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4230     // so we don't need to generate any thing here.
4231   }
4232 
4233   void disposed() override {
4234     Loop->eraseFromParent();
4235     // Ensure the loop setup instruction is deleted too.
4236     LoopCount->eraseFromParent();
4237   }
4238 };
4239 } // namespace
4240 
4241 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4242 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4243   // We really "analyze" only hardware loops right now.
4244   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4245   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4246   if (Preheader == LoopBB)
4247     Preheader = *std::next(LoopBB->pred_begin());
4248   MachineFunction *MF = Preheader->getParent();
4249 
4250   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
4251     SmallPtrSet<MachineBasicBlock *, 8> Visited;
4252     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
4253       Register LoopCountReg = LoopInst->getOperand(0).getReg();
4254       MachineRegisterInfo &MRI = MF->getRegInfo();
4255       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
4256       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
4257     }
4258   }
4259   return nullptr;
4260 }
4261 
4262 MachineInstr *PPCInstrInfo::findLoopInstr(
4263     MachineBasicBlock &PreHeader,
4264     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
4265 
4266   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
4267 
4268   // The loop set-up instruction should be in preheader
4269   for (auto &I : PreHeader.instrs())
4270     if (I.getOpcode() == LOOPi)
4271       return &I;
4272   return nullptr;
4273 }
4274 
4275 // Return true if get the base operand, byte offset of an instruction and the
4276 // memory width. Width is the size of memory that is being loaded/stored.
4277 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
4278     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
4279     unsigned &Width, const TargetRegisterInfo *TRI) const {
4280   if (!LdSt.mayLoadOrStore())
4281     return false;
4282 
4283   // Handle only loads/stores with base register followed by immediate offset.
4284   if (LdSt.getNumExplicitOperands() != 3)
4285     return false;
4286   if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg())
4287     return false;
4288 
4289   if (!LdSt.hasOneMemOperand())
4290     return false;
4291 
4292   Width = (*LdSt.memoperands_begin())->getSize();
4293   Offset = LdSt.getOperand(1).getImm();
4294   BaseReg = &LdSt.getOperand(2);
4295   return true;
4296 }
4297 
4298 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
4299     const MachineInstr &MIa, const MachineInstr &MIb) const {
4300   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
4301   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
4302 
4303   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
4304       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4305     return false;
4306 
4307   // Retrieve the base register, offset from the base register and width. Width
4308   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
4309   // base registers are identical, and the offset of a lower memory access +
4310   // the width doesn't overlap the offset of a higher memory access,
4311   // then the memory accesses are different.
4312   const TargetRegisterInfo *TRI = &getRegisterInfo();
4313   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
4314   int64_t OffsetA = 0, OffsetB = 0;
4315   unsigned int WidthA = 0, WidthB = 0;
4316   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
4317       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
4318     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
4319       int LowOffset = std::min(OffsetA, OffsetB);
4320       int HighOffset = std::max(OffsetA, OffsetB);
4321       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4322       if (LowOffset + LowWidth <= HighOffset)
4323         return true;
4324     }
4325   }
4326   return false;
4327 }
4328