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