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   // This transformation should not be performed if `nsw` is missing and is not
2145   // `equalityOnly` comparison. Since if there is overflow, sub_lt, sub_gt in
2146   // CRReg do not reflect correct order. If `equalityOnly` is true, sub_eq in
2147   // CRReg can reflect if compared values are equal, this optz is still valid.
2148   if (!equalityOnly && (NewOpC == PPC::SUBF_rec || NewOpC == PPC::SUBF8_rec) &&
2149       Sub && !Sub->getFlag(MachineInstr::NoSWrap))
2150     return false;
2151 
2152   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
2153   // needs to be updated to be based on SUB.  Push the condition code
2154   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
2155   // condition code of these operands will be modified.
2156   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
2157   // comparison against 0, which may modify predicate.
2158   bool ShouldSwap = false;
2159   if (Sub && Value == 0) {
2160     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2161       Sub->getOperand(2).getReg() == SrcReg;
2162 
2163     // The operands to subf are the opposite of sub, so only in the fixed-point
2164     // case, invert the order.
2165     ShouldSwap = !ShouldSwap;
2166   }
2167 
2168   if (ShouldSwap)
2169     for (MachineRegisterInfo::use_instr_iterator
2170          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2171          I != IE; ++I) {
2172       MachineInstr *UseMI = &*I;
2173       if (UseMI->getOpcode() == PPC::BCC) {
2174         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
2175         unsigned PredCond = PPC::getPredicateCondition(Pred);
2176         assert((!equalityOnly ||
2177                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
2178                "Invalid predicate for equality-only optimization");
2179         (void)PredCond; // To suppress warning in release build.
2180         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
2181                                 PPC::getSwappedPredicate(Pred)));
2182       } else if (UseMI->getOpcode() == PPC::ISEL ||
2183                  UseMI->getOpcode() == PPC::ISEL8) {
2184         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
2185         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
2186                "Invalid CR bit for equality-only optimization");
2187 
2188         if (NewSubReg == PPC::sub_lt)
2189           NewSubReg = PPC::sub_gt;
2190         else if (NewSubReg == PPC::sub_gt)
2191           NewSubReg = PPC::sub_lt;
2192 
2193         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
2194                                                  NewSubReg));
2195       } else // We need to abort on a user we don't understand.
2196         return false;
2197     }
2198   assert(!(Value != 0 && ShouldSwap) &&
2199          "Non-zero immediate support and ShouldSwap"
2200          "may conflict in updating predicate");
2201 
2202   // Create a new virtual register to hold the value of the CR set by the
2203   // record-form instruction. If the instruction was not previously in
2204   // record form, then set the kill flag on the CR.
2205   CmpInstr.eraseFromParent();
2206 
2207   MachineBasicBlock::iterator MII = MI;
2208   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
2209           get(TargetOpcode::COPY), CRReg)
2210     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
2211 
2212   // Even if CR0 register were dead before, it is alive now since the
2213   // instruction we just built uses it.
2214   MI->clearRegisterDeads(PPC::CR0);
2215 
2216   if (MIOpC != NewOpC) {
2217     // We need to be careful here: we're replacing one instruction with
2218     // another, and we need to make sure that we get all of the right
2219     // implicit uses and defs. On the other hand, the caller may be holding
2220     // an iterator to this instruction, and so we can't delete it (this is
2221     // specifically the case if this is the instruction directly after the
2222     // compare).
2223 
2224     // Rotates are expensive instructions. If we're emitting a record-form
2225     // rotate that can just be an andi/andis, we should just emit that.
2226     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
2227       Register GPRRes = MI->getOperand(0).getReg();
2228       int64_t SH = MI->getOperand(2).getImm();
2229       int64_t MB = MI->getOperand(3).getImm();
2230       int64_t ME = MI->getOperand(4).getImm();
2231       // We can only do this if both the start and end of the mask are in the
2232       // same halfword.
2233       bool MBInLoHWord = MB >= 16;
2234       bool MEInLoHWord = ME >= 16;
2235       uint64_t Mask = ~0LLU;
2236 
2237       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
2238         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2239         // The mask value needs to shift right 16 if we're emitting andis.
2240         Mask >>= MBInLoHWord ? 0 : 16;
2241         NewOpC = MIOpC == PPC::RLWINM
2242                      ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
2243                      : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
2244       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
2245                  (ME - MB + 1 == SH) && (MB >= 16)) {
2246         // If we are rotating by the exact number of bits as are in the mask
2247         // and the mask is in the least significant bits of the register,
2248         // that's just an andis. (as long as the GPR result has no uses).
2249         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
2250         Mask >>= 16;
2251         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
2252       }
2253       // If we've set the mask, we can transform.
2254       if (Mask != ~0LLU) {
2255         MI->RemoveOperand(4);
2256         MI->RemoveOperand(3);
2257         MI->getOperand(2).setImm(Mask);
2258         NumRcRotatesConvertedToRcAnd++;
2259       }
2260     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
2261       int64_t MB = MI->getOperand(3).getImm();
2262       if (MB >= 48) {
2263         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2264         NewOpC = PPC::ANDI8_rec;
2265         MI->RemoveOperand(3);
2266         MI->getOperand(2).setImm(Mask);
2267         NumRcRotatesConvertedToRcAnd++;
2268       }
2269     }
2270 
2271     const MCInstrDesc &NewDesc = get(NewOpC);
2272     MI->setDesc(NewDesc);
2273 
2274     if (NewDesc.ImplicitDefs)
2275       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
2276            *ImpDefs; ++ImpDefs)
2277         if (!MI->definesRegister(*ImpDefs))
2278           MI->addOperand(*MI->getParent()->getParent(),
2279                          MachineOperand::CreateReg(*ImpDefs, true, true));
2280     if (NewDesc.ImplicitUses)
2281       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
2282            *ImpUses; ++ImpUses)
2283         if (!MI->readsRegister(*ImpUses))
2284           MI->addOperand(*MI->getParent()->getParent(),
2285                          MachineOperand::CreateReg(*ImpUses, false, true));
2286   }
2287   assert(MI->definesRegister(PPC::CR0) &&
2288          "Record-form instruction does not define cr0?");
2289 
2290   // Modify the condition code of operands in OperandsToUpdate.
2291   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2292   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2293   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2294     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2295 
2296   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2297     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2298 
2299   return true;
2300 }
2301 
2302 bool PPCInstrInfo::getMemOperandsWithOffsetWidth(
2303     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2304     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
2305     const TargetRegisterInfo *TRI) const {
2306   const MachineOperand *BaseOp;
2307   OffsetIsScalable = false;
2308   if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))
2309     return false;
2310   BaseOps.push_back(BaseOp);
2311   return true;
2312 }
2313 
2314 static bool isLdStSafeToCluster(const MachineInstr &LdSt,
2315                                 const TargetRegisterInfo *TRI) {
2316   // If this is a volatile load/store, don't mess with it.
2317   if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
2318     return false;
2319 
2320   if (LdSt.getOperand(2).isFI())
2321     return true;
2322 
2323   assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
2324   // Can't cluster if the instruction modifies the base register
2325   // or it is update form. e.g. ld r2,3(r2)
2326   if (LdSt.modifiesRegister(LdSt.getOperand(2).getReg(), TRI))
2327     return false;
2328 
2329   return true;
2330 }
2331 
2332 // Only cluster instruction pair that have the same opcode, and they are
2333 // clusterable according to PowerPC specification.
2334 static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
2335                                      const PPCSubtarget &Subtarget) {
2336   switch (FirstOpc) {
2337   default:
2338     return false;
2339   case PPC::STD:
2340   case PPC::STFD:
2341   case PPC::STXSD:
2342   case PPC::DFSTOREf64:
2343     return FirstOpc == SecondOpc;
2344   // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
2345   // 32bit and 64bit instruction selection. They are clusterable pair though
2346   // they are different opcode.
2347   case PPC::STW:
2348   case PPC::STW8:
2349     return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
2350   }
2351 }
2352 
2353 bool PPCInstrInfo::shouldClusterMemOps(
2354     ArrayRef<const MachineOperand *> BaseOps1,
2355     ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
2356     unsigned NumBytes) const {
2357 
2358   assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
2359   const MachineOperand &BaseOp1 = *BaseOps1.front();
2360   const MachineOperand &BaseOp2 = *BaseOps2.front();
2361   assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
2362          "Only base registers and frame indices are supported.");
2363 
2364   // The NumLoads means the number of loads that has been clustered.
2365   // Don't cluster memory op if there are already two ops clustered at least.
2366   if (NumLoads > 2)
2367     return false;
2368 
2369   // Cluster the load/store only when they have the same base
2370   // register or FI.
2371   if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
2372       (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
2373       (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
2374     return false;
2375 
2376   // Check if the load/store are clusterable according to the PowerPC
2377   // specification.
2378   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
2379   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
2380   unsigned FirstOpc = FirstLdSt.getOpcode();
2381   unsigned SecondOpc = SecondLdSt.getOpcode();
2382   const TargetRegisterInfo *TRI = &getRegisterInfo();
2383   // Cluster the load/store only when they have the same opcode, and they are
2384   // clusterable opcode according to PowerPC specification.
2385   if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
2386     return false;
2387 
2388   // Can't cluster load/store that have ordered or volatile memory reference.
2389   if (!isLdStSafeToCluster(FirstLdSt, TRI) ||
2390       !isLdStSafeToCluster(SecondLdSt, TRI))
2391     return false;
2392 
2393   int64_t Offset1 = 0, Offset2 = 0;
2394   unsigned Width1 = 0, Width2 = 0;
2395   const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
2396   if (!getMemOperandWithOffsetWidth(FirstLdSt, Base1, Offset1, Width1, TRI) ||
2397       !getMemOperandWithOffsetWidth(SecondLdSt, Base2, Offset2, Width2, TRI) ||
2398       Width1 != Width2)
2399     return false;
2400 
2401   assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
2402          "getMemOperandWithOffsetWidth return incorrect base op");
2403   // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
2404   assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
2405   return Offset1 + Width1 == Offset2;
2406 }
2407 
2408 /// GetInstSize - Return the number of bytes of code the specified
2409 /// instruction may be.  This returns the maximum number of bytes.
2410 ///
2411 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2412   unsigned Opcode = MI.getOpcode();
2413 
2414   if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2415     const MachineFunction *MF = MI.getParent()->getParent();
2416     const char *AsmStr = MI.getOperand(0).getSymbolName();
2417     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2418   } else if (Opcode == TargetOpcode::STACKMAP) {
2419     StackMapOpers Opers(&MI);
2420     return Opers.getNumPatchBytes();
2421   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2422     PatchPointOpers Opers(&MI);
2423     return Opers.getNumPatchBytes();
2424   } else {
2425     return get(Opcode).getSize();
2426   }
2427 }
2428 
2429 std::pair<unsigned, unsigned>
2430 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2431   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2432   return std::make_pair(TF & Mask, TF & ~Mask);
2433 }
2434 
2435 ArrayRef<std::pair<unsigned, const char *>>
2436 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2437   using namespace PPCII;
2438   static const std::pair<unsigned, const char *> TargetFlags[] = {
2439       {MO_LO, "ppc-lo"},
2440       {MO_HA, "ppc-ha"},
2441       {MO_TPREL_LO, "ppc-tprel-lo"},
2442       {MO_TPREL_HA, "ppc-tprel-ha"},
2443       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2444       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2445       {MO_TOC_LO, "ppc-toc-lo"},
2446       {MO_TLS, "ppc-tls"}};
2447   return makeArrayRef(TargetFlags);
2448 }
2449 
2450 ArrayRef<std::pair<unsigned, const char *>>
2451 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2452   using namespace PPCII;
2453   static const std::pair<unsigned, const char *> TargetFlags[] = {
2454       {MO_PLT, "ppc-plt"},
2455       {MO_PIC_FLAG, "ppc-pic"},
2456       {MO_PCREL_FLAG, "ppc-pcrel"},
2457       {MO_GOT_FLAG, "ppc-got"},
2458       {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
2459       {MO_TLSGD_FLAG, "ppc-tlsgd"},
2460       {MO_TLSLD_FLAG, "ppc-tlsld"},
2461       {MO_TPREL_FLAG, "ppc-tprel"},
2462       {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
2463       {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
2464       {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"}};
2465   return makeArrayRef(TargetFlags);
2466 }
2467 
2468 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2469 // The VSX versions have the advantage of a full 64-register target whereas
2470 // the FP ones have the advantage of lower latency and higher throughput. So
2471 // what we are after is using the faster instructions in low register pressure
2472 // situations and using the larger register file in high register pressure
2473 // situations.
2474 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2475     unsigned UpperOpcode, LowerOpcode;
2476     switch (MI.getOpcode()) {
2477     case PPC::DFLOADf32:
2478       UpperOpcode = PPC::LXSSP;
2479       LowerOpcode = PPC::LFS;
2480       break;
2481     case PPC::DFLOADf64:
2482       UpperOpcode = PPC::LXSD;
2483       LowerOpcode = PPC::LFD;
2484       break;
2485     case PPC::DFSTOREf32:
2486       UpperOpcode = PPC::STXSSP;
2487       LowerOpcode = PPC::STFS;
2488       break;
2489     case PPC::DFSTOREf64:
2490       UpperOpcode = PPC::STXSD;
2491       LowerOpcode = PPC::STFD;
2492       break;
2493     case PPC::XFLOADf32:
2494       UpperOpcode = PPC::LXSSPX;
2495       LowerOpcode = PPC::LFSX;
2496       break;
2497     case PPC::XFLOADf64:
2498       UpperOpcode = PPC::LXSDX;
2499       LowerOpcode = PPC::LFDX;
2500       break;
2501     case PPC::XFSTOREf32:
2502       UpperOpcode = PPC::STXSSPX;
2503       LowerOpcode = PPC::STFSX;
2504       break;
2505     case PPC::XFSTOREf64:
2506       UpperOpcode = PPC::STXSDX;
2507       LowerOpcode = PPC::STFDX;
2508       break;
2509     case PPC::LIWAX:
2510       UpperOpcode = PPC::LXSIWAX;
2511       LowerOpcode = PPC::LFIWAX;
2512       break;
2513     case PPC::LIWZX:
2514       UpperOpcode = PPC::LXSIWZX;
2515       LowerOpcode = PPC::LFIWZX;
2516       break;
2517     case PPC::STIWX:
2518       UpperOpcode = PPC::STXSIWX;
2519       LowerOpcode = PPC::STFIWX;
2520       break;
2521     default:
2522       llvm_unreachable("Unknown Operation!");
2523     }
2524 
2525     Register TargetReg = MI.getOperand(0).getReg();
2526     unsigned Opcode;
2527     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2528         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2529       Opcode = LowerOpcode;
2530     else
2531       Opcode = UpperOpcode;
2532     MI.setDesc(get(Opcode));
2533     return true;
2534 }
2535 
2536 static bool isAnImmediateOperand(const MachineOperand &MO) {
2537   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2538 }
2539 
2540 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2541   auto &MBB = *MI.getParent();
2542   auto DL = MI.getDebugLoc();
2543 
2544   switch (MI.getOpcode()) {
2545   case PPC::BUILD_UACC: {
2546     MCRegister ACC = MI.getOperand(0).getReg();
2547     MCRegister UACC = MI.getOperand(1).getReg();
2548     if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
2549       MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
2550       MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
2551       // FIXME: This can easily be improved to look up to the top of the MBB
2552       // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
2553       // we can just re-target any such XXLOR's to DstVSR + offset.
2554       for (int VecNo = 0; VecNo < 4; VecNo++)
2555         BuildMI(MBB, MI, DL, get(PPC::XXLOR), DstVSR + VecNo)
2556             .addReg(SrcVSR + VecNo)
2557             .addReg(SrcVSR + VecNo);
2558     }
2559     // BUILD_UACC is expanded to 4 copies of the underlying vsx regisers.
2560     // So after building the 4 copies, we can replace the BUILD_UACC instruction
2561     // with a NOP.
2562     LLVM_FALLTHROUGH;
2563   }
2564   case PPC::KILL_PAIR: {
2565     MI.setDesc(get(PPC::UNENCODED_NOP));
2566     MI.RemoveOperand(1);
2567     MI.RemoveOperand(0);
2568     return true;
2569   }
2570   case TargetOpcode::LOAD_STACK_GUARD: {
2571     assert(Subtarget.isTargetLinux() &&
2572            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2573     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2574     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2575     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2576     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2577         .addImm(Offset)
2578         .addReg(Reg);
2579     return true;
2580   }
2581   case PPC::DFLOADf32:
2582   case PPC::DFLOADf64:
2583   case PPC::DFSTOREf32:
2584   case PPC::DFSTOREf64: {
2585     assert(Subtarget.hasP9Vector() &&
2586            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2587     assert(MI.getOperand(2).isReg() &&
2588            isAnImmediateOperand(MI.getOperand(1)) &&
2589            "D-form op must have register and immediate operands");
2590     return expandVSXMemPseudo(MI);
2591   }
2592   case PPC::XFLOADf32:
2593   case PPC::XFSTOREf32:
2594   case PPC::LIWAX:
2595   case PPC::LIWZX:
2596   case PPC::STIWX: {
2597     assert(Subtarget.hasP8Vector() &&
2598            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
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::XFLOADf64:
2604   case PPC::XFSTOREf64: {
2605     assert(Subtarget.hasVSX() &&
2606            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2607     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2608            "X-form op must have register and register operands");
2609     return expandVSXMemPseudo(MI);
2610   }
2611   case PPC::SPILLTOVSR_LD: {
2612     Register TargetReg = MI.getOperand(0).getReg();
2613     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2614       MI.setDesc(get(PPC::DFLOADf64));
2615       return expandPostRAPseudo(MI);
2616     }
2617     else
2618       MI.setDesc(get(PPC::LD));
2619     return true;
2620   }
2621   case PPC::SPILLTOVSR_ST: {
2622     Register SrcReg = MI.getOperand(0).getReg();
2623     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2624       NumStoreSPILLVSRRCAsVec++;
2625       MI.setDesc(get(PPC::DFSTOREf64));
2626       return expandPostRAPseudo(MI);
2627     } else {
2628       NumStoreSPILLVSRRCAsGpr++;
2629       MI.setDesc(get(PPC::STD));
2630     }
2631     return true;
2632   }
2633   case PPC::SPILLTOVSR_LDX: {
2634     Register TargetReg = MI.getOperand(0).getReg();
2635     if (PPC::VSFRCRegClass.contains(TargetReg))
2636       MI.setDesc(get(PPC::LXSDX));
2637     else
2638       MI.setDesc(get(PPC::LDX));
2639     return true;
2640   }
2641   case PPC::SPILLTOVSR_STX: {
2642     Register SrcReg = MI.getOperand(0).getReg();
2643     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2644       NumStoreSPILLVSRRCAsVec++;
2645       MI.setDesc(get(PPC::STXSDX));
2646     } else {
2647       NumStoreSPILLVSRRCAsGpr++;
2648       MI.setDesc(get(PPC::STDX));
2649     }
2650     return true;
2651   }
2652 
2653   case PPC::CFENCE8: {
2654     auto Val = MI.getOperand(0).getReg();
2655     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2656     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2657         .addImm(PPC::PRED_NE_MINUS)
2658         .addReg(PPC::CR7)
2659         .addImm(1);
2660     MI.setDesc(get(PPC::ISYNC));
2661     MI.RemoveOperand(0);
2662     return true;
2663   }
2664   }
2665   return false;
2666 }
2667 
2668 // Essentially a compile-time implementation of a compare->isel sequence.
2669 // It takes two constants to compare, along with the true/false registers
2670 // and the comparison type (as a subreg to a CR field) and returns one
2671 // of the true/false registers, depending on the comparison results.
2672 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2673                           unsigned TrueReg, unsigned FalseReg,
2674                           unsigned CRSubReg) {
2675   // Signed comparisons. The immediates are assumed to be sign-extended.
2676   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2677     switch (CRSubReg) {
2678     default: llvm_unreachable("Unknown integer comparison type.");
2679     case PPC::sub_lt:
2680       return Imm1 < Imm2 ? TrueReg : FalseReg;
2681     case PPC::sub_gt:
2682       return Imm1 > Imm2 ? TrueReg : FalseReg;
2683     case PPC::sub_eq:
2684       return Imm1 == Imm2 ? TrueReg : FalseReg;
2685     }
2686   }
2687   // Unsigned comparisons.
2688   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2689     switch (CRSubReg) {
2690     default: llvm_unreachable("Unknown integer comparison type.");
2691     case PPC::sub_lt:
2692       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2693     case PPC::sub_gt:
2694       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2695     case PPC::sub_eq:
2696       return Imm1 == Imm2 ? TrueReg : FalseReg;
2697     }
2698   }
2699   return PPC::NoRegister;
2700 }
2701 
2702 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2703                                               unsigned OpNo,
2704                                               int64_t Imm) const {
2705   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2706   // Replace the REG with the Immediate.
2707   Register InUseReg = MI.getOperand(OpNo).getReg();
2708   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2709 
2710   if (MI.implicit_operands().empty())
2711     return;
2712 
2713   // We need to make sure that the MI didn't have any implicit use
2714   // of this REG any more.
2715   const TargetRegisterInfo *TRI = &getRegisterInfo();
2716   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2717   if (UseOpIdx >= 0) {
2718     MachineOperand &MO = MI.getOperand(UseOpIdx);
2719     if (MO.isImplicit())
2720       // The operands must always be in the following order:
2721       // - explicit reg defs,
2722       // - other explicit operands (reg uses, immediates, etc.),
2723       // - implicit reg defs
2724       // - implicit reg uses
2725       // Therefore, removing the implicit operand won't change the explicit
2726       // operands layout.
2727       MI.RemoveOperand(UseOpIdx);
2728   }
2729 }
2730 
2731 // Replace an instruction with one that materializes a constant (and sets
2732 // CR0 if the original instruction was a record-form instruction).
2733 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2734                                       const LoadImmediateInfo &LII) const {
2735   // Remove existing operands.
2736   int OperandToKeep = LII.SetCR ? 1 : 0;
2737   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2738     MI.RemoveOperand(i);
2739 
2740   // Replace the instruction.
2741   if (LII.SetCR) {
2742     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
2743     // Set the immediate.
2744     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2745         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2746     return;
2747   }
2748   else
2749     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2750 
2751   // Set the immediate.
2752   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2753       .addImm(LII.Imm);
2754 }
2755 
2756 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2757                                            bool &SeenIntermediateUse) const {
2758   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2759          "Should be called after register allocation.");
2760   const TargetRegisterInfo *TRI = &getRegisterInfo();
2761   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2762   It++;
2763   SeenIntermediateUse = false;
2764   for (; It != E; ++It) {
2765     if (It->modifiesRegister(Reg, TRI))
2766       return &*It;
2767     if (It->readsRegister(Reg, TRI))
2768       SeenIntermediateUse = true;
2769   }
2770   return nullptr;
2771 }
2772 
2773 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2774   MachineInstr &MI,
2775   unsigned &OpNoForForwarding,
2776   bool &SeenIntermediateUse) const {
2777   OpNoForForwarding = ~0U;
2778   MachineInstr *DefMI = nullptr;
2779   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2780   const TargetRegisterInfo *TRI = &getRegisterInfo();
2781   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2782   // within the basic block to see if the register is defined using an
2783   // LI/LI8/ADDI/ADDI8.
2784   if (MRI->isSSA()) {
2785     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2786       if (!MI.getOperand(i).isReg())
2787         continue;
2788       Register Reg = MI.getOperand(i).getReg();
2789       if (!Register::isVirtualRegister(Reg))
2790         continue;
2791       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2792       if (Register::isVirtualRegister(TrueReg)) {
2793         DefMI = MRI->getVRegDef(TrueReg);
2794         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8 ||
2795             DefMI->getOpcode() == PPC::ADDI ||
2796             DefMI->getOpcode() == PPC::ADDI8) {
2797           OpNoForForwarding = i;
2798           // The ADDI and LI operand maybe exist in one instruction at same
2799           // time. we prefer to fold LI operand as LI only has one Imm operand
2800           // and is more possible to be converted. So if current DefMI is
2801           // ADDI/ADDI8, we continue to find possible LI/LI8.
2802           if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
2803             break;
2804         }
2805       }
2806     }
2807   } else {
2808     // Looking back through the definition for each operand could be expensive,
2809     // so exit early if this isn't an instruction that either has an immediate
2810     // form or is already an immediate form that we can handle.
2811     ImmInstrInfo III;
2812     unsigned Opc = MI.getOpcode();
2813     bool ConvertibleImmForm =
2814         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
2815         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2816         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
2817         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
2818         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2819         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
2820         Opc == PPC::RLWINM8_rec;
2821     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2822                        ? isVFRegister(MI.getOperand(0).getReg())
2823                        : false;
2824     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2825       return nullptr;
2826 
2827     // Don't convert or %X, %Y, %Y since that's just a register move.
2828     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2829         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2830       return nullptr;
2831     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2832       MachineOperand &MO = MI.getOperand(i);
2833       SeenIntermediateUse = false;
2834       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2835         Register Reg = MI.getOperand(i).getReg();
2836         // If we see another use of this reg between the def and the MI,
2837         // we want to flat it so the def isn't deleted.
2838         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2839         if (DefMI) {
2840           // Is this register defined by some form of add-immediate (including
2841           // load-immediate) within this basic block?
2842           switch (DefMI->getOpcode()) {
2843           default:
2844             break;
2845           case PPC::LI:
2846           case PPC::LI8:
2847           case PPC::ADDItocL:
2848           case PPC::ADDI:
2849           case PPC::ADDI8:
2850             OpNoForForwarding = i;
2851             return DefMI;
2852           }
2853         }
2854       }
2855     }
2856   }
2857   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2858 }
2859 
2860 unsigned PPCInstrInfo::getSpillTarget() const {
2861   // With P10, we may need to spill paired vector registers or accumulator
2862   // registers. MMA implies paired vectors, so we can just check that.
2863   bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
2864   return IsP10Variant ? 2 : Subtarget.hasP9Vector() ? 1 : 0;
2865 }
2866 
2867 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2868   return StoreSpillOpcodesArray[getSpillTarget()];
2869 }
2870 
2871 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2872   return LoadSpillOpcodesArray[getSpillTarget()];
2873 }
2874 
2875 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr *StartMI, MachineInstr *EndMI,
2876                                      unsigned RegNo) const {
2877   // Conservatively clear kill flag for the register if the instructions are in
2878   // different basic blocks and in SSA form, because the kill flag may no longer
2879   // be right. There is no need to bother with dead flags since defs with no
2880   // uses will be handled by DCE.
2881   MachineRegisterInfo &MRI = StartMI->getParent()->getParent()->getRegInfo();
2882   if (MRI.isSSA() && (StartMI->getParent() != EndMI->getParent())) {
2883     MRI.clearKillFlags(RegNo);
2884     return;
2885   }
2886 
2887   // Instructions between [StartMI, EndMI] should be in same basic block.
2888   assert((StartMI->getParent() == EndMI->getParent()) &&
2889          "Instructions are not in same basic block");
2890 
2891   // If before RA, StartMI may be def through COPY, we need to adjust it to the
2892   // real def. See function getForwardingDefMI.
2893   if (MRI.isSSA()) {
2894     bool Reads, Writes;
2895     std::tie(Reads, Writes) = StartMI->readsWritesVirtualRegister(RegNo);
2896     if (!Reads && !Writes) {
2897       assert(Register::isVirtualRegister(RegNo) &&
2898              "Must be a virtual register");
2899       // Get real def and ignore copies.
2900       StartMI = MRI.getVRegDef(RegNo);
2901     }
2902   }
2903 
2904   bool IsKillSet = false;
2905 
2906   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2907     MachineOperand &MO = MI.getOperand(Index);
2908     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2909         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2910       MO.setIsKill(false);
2911   };
2912 
2913   // Set killed flag for EndMI.
2914   // No need to do anything if EndMI defines RegNo.
2915   int UseIndex =
2916       EndMI->findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2917   if (UseIndex != -1) {
2918     EndMI->getOperand(UseIndex).setIsKill(true);
2919     IsKillSet = true;
2920     // Clear killed flag for other EndMI operands related to RegNo. In some
2921     // upexpected cases, killed may be set multiple times for same register
2922     // operand in same MI.
2923     for (int i = 0, e = EndMI->getNumOperands(); i != e; ++i)
2924       if (i != UseIndex)
2925         clearOperandKillInfo(*EndMI, i);
2926   }
2927 
2928   // Walking the inst in reverse order (EndMI -> StartMI].
2929   MachineBasicBlock::reverse_iterator It = *EndMI;
2930   MachineBasicBlock::reverse_iterator E = EndMI->getParent()->rend();
2931   // EndMI has been handled above, skip it here.
2932   It++;
2933   MachineOperand *MO = nullptr;
2934   for (; It != E; ++It) {
2935     // Skip insturctions which could not be a def/use of RegNo.
2936     if (It->isDebugInstr() || It->isPosition())
2937       continue;
2938 
2939     // Clear killed flag for all It operands related to RegNo. In some
2940     // upexpected cases, killed may be set multiple times for same register
2941     // operand in same MI.
2942     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2943         clearOperandKillInfo(*It, i);
2944 
2945     // If killed is not set, set killed for its last use or set dead for its def
2946     // if no use found.
2947     if (!IsKillSet) {
2948       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2949         // Use found, set it killed.
2950         IsKillSet = true;
2951         MO->setIsKill(true);
2952         continue;
2953       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2954                                                   &getRegisterInfo()))) {
2955         // No use found, set dead for its def.
2956         assert(&*It == StartMI && "No new def between StartMI and EndMI.");
2957         MO->setIsDead(true);
2958         break;
2959       }
2960     }
2961 
2962     if ((&*It) == StartMI)
2963       break;
2964   }
2965   // Ensure RegMo liveness is killed after EndMI.
2966   assert((IsKillSet || (MO && MO->isDead())) &&
2967          "RegNo should be killed or dead");
2968 }
2969 
2970 // This opt tries to convert the following imm form to an index form to save an
2971 // add for stack variables.
2972 // Return false if no such pattern found.
2973 //
2974 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
2975 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
2976 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
2977 //
2978 // can be converted to:
2979 //
2980 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
2981 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
2982 //
2983 // In order to eliminate ADD instr, make sure that:
2984 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
2985 //    new ADDI instr and ADDI can only take int16 Imm.
2986 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
2987 //    between ADDI and ADD instr since its original def in ADDI will be changed
2988 //    in new ADDI instr. And also there should be no new def for it between
2989 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
2990 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
2991 //    between ADD and Imm instr since ADD instr will be eliminated.
2992 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
2993 //    moved to Index instr.
2994 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
2995   MachineFunction *MF = MI.getParent()->getParent();
2996   MachineRegisterInfo *MRI = &MF->getRegInfo();
2997   bool PostRA = !MRI->isSSA();
2998   // Do this opt after PEI which is after RA. The reason is stack slot expansion
2999   // in PEI may expose such opportunities since in PEI, stack slot offsets to
3000   // frame base(OffsetAddi) are determined.
3001   if (!PostRA)
3002     return false;
3003   unsigned ToBeDeletedReg = 0;
3004   int64_t OffsetImm = 0;
3005   unsigned XFormOpcode = 0;
3006   ImmInstrInfo III;
3007 
3008   // Check if Imm instr meets requirement.
3009   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
3010                                     III))
3011     return false;
3012 
3013   bool OtherIntermediateUse = false;
3014   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
3015 
3016   // Exit if there is other use between ADD and Imm instr or no def found.
3017   if (OtherIntermediateUse || !ADDMI)
3018     return false;
3019 
3020   // Check if ADD instr meets requirement.
3021   if (!isADDInstrEligibleForFolding(*ADDMI))
3022     return false;
3023 
3024   unsigned ScaleRegIdx = 0;
3025   int64_t OffsetAddi = 0;
3026   MachineInstr *ADDIMI = nullptr;
3027 
3028   // Check if there is a valid ToBeChangedReg in ADDMI.
3029   // 1: It must be killed.
3030   // 2: Its definition must be a valid ADDIMI.
3031   // 3: It must satify int16 offset requirement.
3032   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
3033     ScaleRegIdx = 2;
3034   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
3035     ScaleRegIdx = 1;
3036   else
3037     return false;
3038 
3039   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3040   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
3041   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
3042   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3043                        MachineBasicBlock::iterator End) {
3044     for (auto It = ++Start; It != End; It++)
3045       if (It->modifiesRegister(Reg, &getRegisterInfo()))
3046         return true;
3047     return false;
3048   };
3049 
3050   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3051   // treated as special zero when ScaleReg is R0/X0 register.
3052   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3053       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3054     return false;
3055 
3056   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3057   // and Imm Instr.
3058   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3059     return false;
3060 
3061   // Now start to do the transformation.
3062   LLVM_DEBUG(dbgs() << "Replace instruction: "
3063                     << "\n");
3064   LLVM_DEBUG(ADDIMI->dump());
3065   LLVM_DEBUG(ADDMI->dump());
3066   LLVM_DEBUG(MI.dump());
3067   LLVM_DEBUG(dbgs() << "with: "
3068                     << "\n");
3069 
3070   // Update ADDI instr.
3071   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
3072 
3073   // Update Imm instr.
3074   MI.setDesc(get(XFormOpcode));
3075   MI.getOperand(III.ImmOpNo)
3076       .ChangeToRegister(ScaleReg, false, false,
3077                         ADDMI->getOperand(ScaleRegIdx).isKill());
3078 
3079   MI.getOperand(III.OpNoForForwarding)
3080       .ChangeToRegister(ToBeChangedReg, false, false, true);
3081 
3082   // Eliminate ADD instr.
3083   ADDMI->eraseFromParent();
3084 
3085   LLVM_DEBUG(ADDIMI->dump());
3086   LLVM_DEBUG(MI.dump());
3087 
3088   return true;
3089 }
3090 
3091 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
3092                                                  int64_t &Imm) const {
3093   unsigned Opc = ADDIMI.getOpcode();
3094 
3095   // Exit if the instruction is not ADDI.
3096   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3097     return false;
3098 
3099   // The operand may not necessarily be an immediate - it could be a relocation.
3100   if (!ADDIMI.getOperand(2).isImm())
3101     return false;
3102 
3103   Imm = ADDIMI.getOperand(2).getImm();
3104 
3105   return true;
3106 }
3107 
3108 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
3109   unsigned Opc = ADDMI.getOpcode();
3110 
3111   // Exit if the instruction is not ADD.
3112   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3113 }
3114 
3115 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
3116                                                 unsigned &ToBeDeletedReg,
3117                                                 unsigned &XFormOpcode,
3118                                                 int64_t &OffsetImm,
3119                                                 ImmInstrInfo &III) const {
3120   // Only handle load/store.
3121   if (!MI.mayLoadOrStore())
3122     return false;
3123 
3124   unsigned Opc = MI.getOpcode();
3125 
3126   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
3127 
3128   // Exit if instruction has no index form.
3129   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3130     return false;
3131 
3132   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3133   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
3134                        III, true))
3135     return false;
3136 
3137   if (!III.IsSummingOperands)
3138     return false;
3139 
3140   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
3141   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
3142   // Only support imm operands, not relocation slots or others.
3143   if (!ImmOperand.isImm())
3144     return false;
3145 
3146   assert(RegOperand.isReg() && "Instruction format is not right");
3147 
3148   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3149   if (!RegOperand.isKill())
3150     return false;
3151 
3152   ToBeDeletedReg = RegOperand.getReg();
3153   OffsetImm = ImmOperand.getImm();
3154 
3155   return true;
3156 }
3157 
3158 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
3159                                          MachineInstr *&ADDIMI,
3160                                          int64_t &OffsetAddi,
3161                                          int64_t OffsetImm) const {
3162   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3163   MachineOperand &MO = ADDMI->getOperand(Index);
3164 
3165   if (!MO.isKill())
3166     return false;
3167 
3168   bool OtherIntermediateUse = false;
3169 
3170   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
3171   // Currently handle only one "add + Imminstr" pair case, exit if other
3172   // intermediate use for ToBeChangedReg found.
3173   // TODO: handle the cases where there are other "add + Imminstr" pairs
3174   // with same offset in Imminstr which is like:
3175   //
3176   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
3177   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3178   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
3179   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3180   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
3181   //
3182   // can be converted to:
3183   //
3184   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3185   //                                       (OffsetAddi + OffsetImm)
3186   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
3187   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
3188 
3189   if (OtherIntermediateUse || !ADDIMI)
3190     return false;
3191   // Check if ADDI instr meets requirement.
3192   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
3193     return false;
3194 
3195   if (isInt<16>(OffsetAddi + OffsetImm))
3196     return true;
3197   return false;
3198 }
3199 
3200 // If this instruction has an immediate form and one of its operands is a
3201 // result of a load-immediate or an add-immediate, convert it to
3202 // the immediate form if the constant is in range.
3203 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
3204                                           MachineInstr **KilledDef) const {
3205   MachineFunction *MF = MI.getParent()->getParent();
3206   MachineRegisterInfo *MRI = &MF->getRegInfo();
3207   bool PostRA = !MRI->isSSA();
3208   bool SeenIntermediateUse = true;
3209   unsigned ForwardingOperand = ~0U;
3210   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
3211                                            SeenIntermediateUse);
3212   if (!DefMI)
3213     return false;
3214   assert(ForwardingOperand < MI.getNumOperands() &&
3215          "The forwarding operand needs to be valid at this point");
3216   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
3217   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3218   if (KilledDef && KillFwdDefMI)
3219     *KilledDef = DefMI;
3220 
3221   // If this is a imm instruction and its register operands is produced by ADDI,
3222   // put the imm into imm inst directly.
3223   if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
3224           PPC::INSTRUCTION_LIST_END &&
3225       transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
3226     return true;
3227 
3228   ImmInstrInfo III;
3229   bool IsVFReg = MI.getOperand(0).isReg()
3230                      ? isVFRegister(MI.getOperand(0).getReg())
3231                      : false;
3232   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
3233   // If this is a reg+reg instruction that has a reg+imm form,
3234   // and one of the operands is produced by an add-immediate,
3235   // try to convert it.
3236   if (HasImmForm &&
3237       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
3238                                  KillFwdDefMI))
3239     return true;
3240 
3241   // If this is a reg+reg instruction that has a reg+imm form,
3242   // and one of the operands is produced by LI, convert it now.
3243   if (HasImmForm &&
3244       transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
3245     return true;
3246 
3247   // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3248   // can be simpified to LI.
3249   if (!HasImmForm && simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef))
3250     return true;
3251 
3252   return false;
3253 }
3254 
3255 bool PPCInstrInfo::combineRLWINM(MachineInstr &MI,
3256                                  MachineInstr **ToErase) const {
3257   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3258   unsigned FoldingReg = MI.getOperand(1).getReg();
3259   if (!Register::isVirtualRegister(FoldingReg))
3260     return false;
3261   MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg);
3262   if (SrcMI->getOpcode() != PPC::RLWINM &&
3263       SrcMI->getOpcode() != PPC::RLWINM_rec &&
3264       SrcMI->getOpcode() != PPC::RLWINM8 &&
3265       SrcMI->getOpcode() != PPC::RLWINM8_rec)
3266     return false;
3267   assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3268           MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3269           SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3270          "Invalid PPC::RLWINM Instruction!");
3271   uint64_t SHSrc = SrcMI->getOperand(2).getImm();
3272   uint64_t SHMI = MI.getOperand(2).getImm();
3273   uint64_t MBSrc = SrcMI->getOperand(3).getImm();
3274   uint64_t MBMI = MI.getOperand(3).getImm();
3275   uint64_t MESrc = SrcMI->getOperand(4).getImm();
3276   uint64_t MEMI = MI.getOperand(4).getImm();
3277 
3278   assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3279          "Invalid PPC::RLWINM Instruction!");
3280   // If MBMI is bigger than MEMI, we always can not get run of ones.
3281   // RotatedSrcMask non-wrap:
3282   //                 0........31|32........63
3283   // RotatedSrcMask:   B---E        B---E
3284   // MaskMI:         -----------|--E  B------
3285   // Result:           -----          ---      (Bad candidate)
3286   //
3287   // RotatedSrcMask wrap:
3288   //                 0........31|32........63
3289   // RotatedSrcMask: --E   B----|--E    B----
3290   // MaskMI:         -----------|--E  B------
3291   // Result:         ---   -----|---    -----  (Bad candidate)
3292   //
3293   // One special case is RotatedSrcMask is a full set mask.
3294   // RotatedSrcMask full:
3295   //                 0........31|32........63
3296   // RotatedSrcMask: ------EB---|-------EB---
3297   // MaskMI:         -----------|--E  B------
3298   // Result:         -----------|---  -------  (Good candidate)
3299 
3300   // Mark special case.
3301   bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3302 
3303   // For other MBMI > MEMI cases, just return.
3304   if ((MBMI > MEMI) && !SrcMaskFull)
3305     return false;
3306 
3307   // Handle MBMI <= MEMI cases.
3308   APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
3309   // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3310   // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3311   // while in PowerPC ISA, lowerest bit is at index 63.
3312   APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
3313 
3314   APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
3315   APInt FinalMask = RotatedSrcMask & MaskMI;
3316   uint32_t NewMB, NewME;
3317   bool Simplified = false;
3318 
3319   // If final mask is 0, MI result should be 0 too.
3320   if (FinalMask.isNullValue()) {
3321     bool Is64Bit =
3322         (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
3323     Simplified = true;
3324     LLVM_DEBUG(dbgs() << "Replace Instr: ");
3325     LLVM_DEBUG(MI.dump());
3326 
3327     if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3328       // Replace MI with "LI 0"
3329       MI.RemoveOperand(4);
3330       MI.RemoveOperand(3);
3331       MI.RemoveOperand(2);
3332       MI.getOperand(1).ChangeToImmediate(0);
3333       MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
3334     } else {
3335       // Replace MI with "ANDI_rec reg, 0"
3336       MI.RemoveOperand(4);
3337       MI.RemoveOperand(3);
3338       MI.getOperand(2).setImm(0);
3339       MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3340       MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3341       if (SrcMI->getOperand(1).isKill()) {
3342         MI.getOperand(1).setIsKill(true);
3343         SrcMI->getOperand(1).setIsKill(false);
3344       } else
3345         // About to replace MI.getOperand(1), clear its kill flag.
3346         MI.getOperand(1).setIsKill(false);
3347     }
3348 
3349     LLVM_DEBUG(dbgs() << "With: ");
3350     LLVM_DEBUG(MI.dump());
3351 
3352   } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
3353               NewMB <= NewME) ||
3354              SrcMaskFull) {
3355     // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3356     // than NewME. Otherwise we get a 64 bit value after folding, but MI
3357     // return a 32 bit value.
3358     Simplified = true;
3359     LLVM_DEBUG(dbgs() << "Converting Instr: ");
3360     LLVM_DEBUG(MI.dump());
3361 
3362     uint16_t NewSH = (SHSrc + SHMI) % 32;
3363     MI.getOperand(2).setImm(NewSH);
3364     // If SrcMI mask is full, no need to update MBMI and MEMI.
3365     if (!SrcMaskFull) {
3366       MI.getOperand(3).setImm(NewMB);
3367       MI.getOperand(4).setImm(NewME);
3368     }
3369     MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3370     if (SrcMI->getOperand(1).isKill()) {
3371       MI.getOperand(1).setIsKill(true);
3372       SrcMI->getOperand(1).setIsKill(false);
3373     } else
3374       // About to replace MI.getOperand(1), clear its kill flag.
3375       MI.getOperand(1).setIsKill(false);
3376 
3377     LLVM_DEBUG(dbgs() << "To: ");
3378     LLVM_DEBUG(MI.dump());
3379   }
3380   if (Simplified & MRI->use_nodbg_empty(FoldingReg) &&
3381       !SrcMI->hasImplicitDef()) {
3382     // If FoldingReg has no non-debug use and it has no implicit def (it
3383     // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
3384     // Otherwise keep it.
3385     *ToErase = SrcMI;
3386     LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
3387     LLVM_DEBUG(SrcMI->dump());
3388   }
3389   return Simplified;
3390 }
3391 
3392 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3393                                    ImmInstrInfo &III, bool PostRA) const {
3394   // The vast majority of the instructions would need their operand 2 replaced
3395   // with an immediate when switching to the reg+imm form. A marked exception
3396   // are the update form loads/stores for which a constant operand 2 would need
3397   // to turn into a displacement and move operand 1 to the operand 2 position.
3398   III.ImmOpNo = 2;
3399   III.OpNoForForwarding = 2;
3400   III.ImmWidth = 16;
3401   III.ImmMustBeMultipleOf = 1;
3402   III.TruncateImmTo = 0;
3403   III.IsSummingOperands = false;
3404   switch (Opc) {
3405   default: return false;
3406   case PPC::ADD4:
3407   case PPC::ADD8:
3408     III.SignedImm = true;
3409     III.ZeroIsSpecialOrig = 0;
3410     III.ZeroIsSpecialNew = 1;
3411     III.IsCommutative = true;
3412     III.IsSummingOperands = true;
3413     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3414     break;
3415   case PPC::ADDC:
3416   case PPC::ADDC8:
3417     III.SignedImm = true;
3418     III.ZeroIsSpecialOrig = 0;
3419     III.ZeroIsSpecialNew = 0;
3420     III.IsCommutative = true;
3421     III.IsSummingOperands = true;
3422     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3423     break;
3424   case PPC::ADDC_rec:
3425     III.SignedImm = true;
3426     III.ZeroIsSpecialOrig = 0;
3427     III.ZeroIsSpecialNew = 0;
3428     III.IsCommutative = true;
3429     III.IsSummingOperands = true;
3430     III.ImmOpcode = PPC::ADDIC_rec;
3431     break;
3432   case PPC::SUBFC:
3433   case PPC::SUBFC8:
3434     III.SignedImm = true;
3435     III.ZeroIsSpecialOrig = 0;
3436     III.ZeroIsSpecialNew = 0;
3437     III.IsCommutative = false;
3438     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3439     break;
3440   case PPC::CMPW:
3441   case PPC::CMPD:
3442     III.SignedImm = true;
3443     III.ZeroIsSpecialOrig = 0;
3444     III.ZeroIsSpecialNew = 0;
3445     III.IsCommutative = false;
3446     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3447     break;
3448   case PPC::CMPLW:
3449   case PPC::CMPLD:
3450     III.SignedImm = false;
3451     III.ZeroIsSpecialOrig = 0;
3452     III.ZeroIsSpecialNew = 0;
3453     III.IsCommutative = false;
3454     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3455     break;
3456   case PPC::AND_rec:
3457   case PPC::AND8_rec:
3458   case PPC::OR:
3459   case PPC::OR8:
3460   case PPC::XOR:
3461   case PPC::XOR8:
3462     III.SignedImm = false;
3463     III.ZeroIsSpecialOrig = 0;
3464     III.ZeroIsSpecialNew = 0;
3465     III.IsCommutative = true;
3466     switch(Opc) {
3467     default: llvm_unreachable("Unknown opcode");
3468     case PPC::AND_rec:
3469       III.ImmOpcode = PPC::ANDI_rec;
3470       break;
3471     case PPC::AND8_rec:
3472       III.ImmOpcode = PPC::ANDI8_rec;
3473       break;
3474     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3475     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3476     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3477     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3478     }
3479     break;
3480   case PPC::RLWNM:
3481   case PPC::RLWNM8:
3482   case PPC::RLWNM_rec:
3483   case PPC::RLWNM8_rec:
3484   case PPC::SLW:
3485   case PPC::SLW8:
3486   case PPC::SLW_rec:
3487   case PPC::SLW8_rec:
3488   case PPC::SRW:
3489   case PPC::SRW8:
3490   case PPC::SRW_rec:
3491   case PPC::SRW8_rec:
3492   case PPC::SRAW:
3493   case PPC::SRAW_rec:
3494     III.SignedImm = false;
3495     III.ZeroIsSpecialOrig = 0;
3496     III.ZeroIsSpecialNew = 0;
3497     III.IsCommutative = false;
3498     // This isn't actually true, but the instructions ignore any of the
3499     // upper bits, so any immediate loaded with an LI is acceptable.
3500     // This does not apply to shift right algebraic because a value
3501     // out of range will produce a -1/0.
3502     III.ImmWidth = 16;
3503     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3504         Opc == PPC::RLWNM8_rec)
3505       III.TruncateImmTo = 5;
3506     else
3507       III.TruncateImmTo = 6;
3508     switch(Opc) {
3509     default: llvm_unreachable("Unknown opcode");
3510     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3511     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3512     case PPC::RLWNM_rec:
3513       III.ImmOpcode = PPC::RLWINM_rec;
3514       break;
3515     case PPC::RLWNM8_rec:
3516       III.ImmOpcode = PPC::RLWINM8_rec;
3517       break;
3518     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3519     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3520     case PPC::SLW_rec:
3521       III.ImmOpcode = PPC::RLWINM_rec;
3522       break;
3523     case PPC::SLW8_rec:
3524       III.ImmOpcode = PPC::RLWINM8_rec;
3525       break;
3526     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3527     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3528     case PPC::SRW_rec:
3529       III.ImmOpcode = PPC::RLWINM_rec;
3530       break;
3531     case PPC::SRW8_rec:
3532       III.ImmOpcode = PPC::RLWINM8_rec;
3533       break;
3534     case PPC::SRAW:
3535       III.ImmWidth = 5;
3536       III.TruncateImmTo = 0;
3537       III.ImmOpcode = PPC::SRAWI;
3538       break;
3539     case PPC::SRAW_rec:
3540       III.ImmWidth = 5;
3541       III.TruncateImmTo = 0;
3542       III.ImmOpcode = PPC::SRAWI_rec;
3543       break;
3544     }
3545     break;
3546   case PPC::RLDCL:
3547   case PPC::RLDCL_rec:
3548   case PPC::RLDCR:
3549   case PPC::RLDCR_rec:
3550   case PPC::SLD:
3551   case PPC::SLD_rec:
3552   case PPC::SRD:
3553   case PPC::SRD_rec:
3554   case PPC::SRAD:
3555   case PPC::SRAD_rec:
3556     III.SignedImm = false;
3557     III.ZeroIsSpecialOrig = 0;
3558     III.ZeroIsSpecialNew = 0;
3559     III.IsCommutative = false;
3560     // This isn't actually true, but the instructions ignore any of the
3561     // upper bits, so any immediate loaded with an LI is acceptable.
3562     // This does not apply to shift right algebraic because a value
3563     // out of range will produce a -1/0.
3564     III.ImmWidth = 16;
3565     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3566         Opc == PPC::RLDCR_rec)
3567       III.TruncateImmTo = 6;
3568     else
3569       III.TruncateImmTo = 7;
3570     switch(Opc) {
3571     default: llvm_unreachable("Unknown opcode");
3572     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
3573     case PPC::RLDCL_rec:
3574       III.ImmOpcode = PPC::RLDICL_rec;
3575       break;
3576     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
3577     case PPC::RLDCR_rec:
3578       III.ImmOpcode = PPC::RLDICR_rec;
3579       break;
3580     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
3581     case PPC::SLD_rec:
3582       III.ImmOpcode = PPC::RLDICR_rec;
3583       break;
3584     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
3585     case PPC::SRD_rec:
3586       III.ImmOpcode = PPC::RLDICL_rec;
3587       break;
3588     case PPC::SRAD:
3589       III.ImmWidth = 6;
3590       III.TruncateImmTo = 0;
3591       III.ImmOpcode = PPC::SRADI;
3592        break;
3593     case PPC::SRAD_rec:
3594       III.ImmWidth = 6;
3595       III.TruncateImmTo = 0;
3596       III.ImmOpcode = PPC::SRADI_rec;
3597       break;
3598     }
3599     break;
3600   // Loads and stores:
3601   case PPC::LBZX:
3602   case PPC::LBZX8:
3603   case PPC::LHZX:
3604   case PPC::LHZX8:
3605   case PPC::LHAX:
3606   case PPC::LHAX8:
3607   case PPC::LWZX:
3608   case PPC::LWZX8:
3609   case PPC::LWAX:
3610   case PPC::LDX:
3611   case PPC::LFSX:
3612   case PPC::LFDX:
3613   case PPC::STBX:
3614   case PPC::STBX8:
3615   case PPC::STHX:
3616   case PPC::STHX8:
3617   case PPC::STWX:
3618   case PPC::STWX8:
3619   case PPC::STDX:
3620   case PPC::STFSX:
3621   case PPC::STFDX:
3622     III.SignedImm = true;
3623     III.ZeroIsSpecialOrig = 1;
3624     III.ZeroIsSpecialNew = 2;
3625     III.IsCommutative = true;
3626     III.IsSummingOperands = true;
3627     III.ImmOpNo = 1;
3628     III.OpNoForForwarding = 2;
3629     switch(Opc) {
3630     default: llvm_unreachable("Unknown opcode");
3631     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3632     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3633     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3634     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3635     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3636     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3637     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3638     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3639     case PPC::LWAX:
3640       III.ImmOpcode = PPC::LWA;
3641       III.ImmMustBeMultipleOf = 4;
3642       break;
3643     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3644     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3645     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3646     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3647     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3648     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3649     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3650     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3651     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3652     case PPC::STDX:
3653       III.ImmOpcode = PPC::STD;
3654       III.ImmMustBeMultipleOf = 4;
3655       break;
3656     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3657     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3658     }
3659     break;
3660   case PPC::LBZUX:
3661   case PPC::LBZUX8:
3662   case PPC::LHZUX:
3663   case PPC::LHZUX8:
3664   case PPC::LHAUX:
3665   case PPC::LHAUX8:
3666   case PPC::LWZUX:
3667   case PPC::LWZUX8:
3668   case PPC::LDUX:
3669   case PPC::LFSUX:
3670   case PPC::LFDUX:
3671   case PPC::STBUX:
3672   case PPC::STBUX8:
3673   case PPC::STHUX:
3674   case PPC::STHUX8:
3675   case PPC::STWUX:
3676   case PPC::STWUX8:
3677   case PPC::STDUX:
3678   case PPC::STFSUX:
3679   case PPC::STFDUX:
3680     III.SignedImm = true;
3681     III.ZeroIsSpecialOrig = 2;
3682     III.ZeroIsSpecialNew = 3;
3683     III.IsCommutative = false;
3684     III.IsSummingOperands = true;
3685     III.ImmOpNo = 2;
3686     III.OpNoForForwarding = 3;
3687     switch(Opc) {
3688     default: llvm_unreachable("Unknown opcode");
3689     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3690     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3691     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3692     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3693     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3694     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3695     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3696     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3697     case PPC::LDUX:
3698       III.ImmOpcode = PPC::LDU;
3699       III.ImmMustBeMultipleOf = 4;
3700       break;
3701     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3702     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3703     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3704     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3705     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3706     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3707     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3708     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3709     case PPC::STDUX:
3710       III.ImmOpcode = PPC::STDU;
3711       III.ImmMustBeMultipleOf = 4;
3712       break;
3713     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3714     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3715     }
3716     break;
3717   // Power9 and up only. For some of these, the X-Form version has access to all
3718   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3719   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3720   // into or stored from is one of the VR registers.
3721   case PPC::LXVX:
3722   case PPC::LXSSPX:
3723   case PPC::LXSDX:
3724   case PPC::STXVX:
3725   case PPC::STXSSPX:
3726   case PPC::STXSDX:
3727   case PPC::XFLOADf32:
3728   case PPC::XFLOADf64:
3729   case PPC::XFSTOREf32:
3730   case PPC::XFSTOREf64:
3731     if (!Subtarget.hasP9Vector())
3732       return false;
3733     III.SignedImm = true;
3734     III.ZeroIsSpecialOrig = 1;
3735     III.ZeroIsSpecialNew = 2;
3736     III.IsCommutative = true;
3737     III.IsSummingOperands = true;
3738     III.ImmOpNo = 1;
3739     III.OpNoForForwarding = 2;
3740     III.ImmMustBeMultipleOf = 4;
3741     switch(Opc) {
3742     default: llvm_unreachable("Unknown opcode");
3743     case PPC::LXVX:
3744       III.ImmOpcode = PPC::LXV;
3745       III.ImmMustBeMultipleOf = 16;
3746       break;
3747     case PPC::LXSSPX:
3748       if (PostRA) {
3749         if (IsVFReg)
3750           III.ImmOpcode = PPC::LXSSP;
3751         else {
3752           III.ImmOpcode = PPC::LFS;
3753           III.ImmMustBeMultipleOf = 1;
3754         }
3755         break;
3756       }
3757       LLVM_FALLTHROUGH;
3758     case PPC::XFLOADf32:
3759       III.ImmOpcode = PPC::DFLOADf32;
3760       break;
3761     case PPC::LXSDX:
3762       if (PostRA) {
3763         if (IsVFReg)
3764           III.ImmOpcode = PPC::LXSD;
3765         else {
3766           III.ImmOpcode = PPC::LFD;
3767           III.ImmMustBeMultipleOf = 1;
3768         }
3769         break;
3770       }
3771       LLVM_FALLTHROUGH;
3772     case PPC::XFLOADf64:
3773       III.ImmOpcode = PPC::DFLOADf64;
3774       break;
3775     case PPC::STXVX:
3776       III.ImmOpcode = PPC::STXV;
3777       III.ImmMustBeMultipleOf = 16;
3778       break;
3779     case PPC::STXSSPX:
3780       if (PostRA) {
3781         if (IsVFReg)
3782           III.ImmOpcode = PPC::STXSSP;
3783         else {
3784           III.ImmOpcode = PPC::STFS;
3785           III.ImmMustBeMultipleOf = 1;
3786         }
3787         break;
3788       }
3789       LLVM_FALLTHROUGH;
3790     case PPC::XFSTOREf32:
3791       III.ImmOpcode = PPC::DFSTOREf32;
3792       break;
3793     case PPC::STXSDX:
3794       if (PostRA) {
3795         if (IsVFReg)
3796           III.ImmOpcode = PPC::STXSD;
3797         else {
3798           III.ImmOpcode = PPC::STFD;
3799           III.ImmMustBeMultipleOf = 1;
3800         }
3801         break;
3802       }
3803       LLVM_FALLTHROUGH;
3804     case PPC::XFSTOREf64:
3805       III.ImmOpcode = PPC::DFSTOREf64;
3806       break;
3807     }
3808     break;
3809   }
3810   return true;
3811 }
3812 
3813 // Utility function for swaping two arbitrary operands of an instruction.
3814 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3815   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3816 
3817   unsigned MaxOp = std::max(Op1, Op2);
3818   unsigned MinOp = std::min(Op1, Op2);
3819   MachineOperand MOp1 = MI.getOperand(MinOp);
3820   MachineOperand MOp2 = MI.getOperand(MaxOp);
3821   MI.RemoveOperand(std::max(Op1, Op2));
3822   MI.RemoveOperand(std::min(Op1, Op2));
3823 
3824   // If the operands we are swapping are the two at the end (the common case)
3825   // we can just remove both and add them in the opposite order.
3826   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3827     MI.addOperand(MOp2);
3828     MI.addOperand(MOp1);
3829   } else {
3830     // Store all operands in a temporary vector, remove them and re-add in the
3831     // right order.
3832     SmallVector<MachineOperand, 2> MOps;
3833     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3834     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3835       MOps.push_back(MI.getOperand(i));
3836       MI.RemoveOperand(i);
3837     }
3838     // MOp2 needs to be added next.
3839     MI.addOperand(MOp2);
3840     // Now add the rest.
3841     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3842       if (i == MaxOp)
3843         MI.addOperand(MOp1);
3844       else {
3845         MI.addOperand(MOps.back());
3846         MOps.pop_back();
3847       }
3848     }
3849   }
3850 }
3851 
3852 // Check if the 'MI' that has the index OpNoForForwarding
3853 // meets the requirement described in the ImmInstrInfo.
3854 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3855                                                const ImmInstrInfo &III,
3856                                                unsigned OpNoForForwarding
3857                                                ) const {
3858   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3859   // would not work pre-RA, we can only do the check post RA.
3860   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3861   if (MRI.isSSA())
3862     return false;
3863 
3864   // Cannot do the transform if MI isn't summing the operands.
3865   if (!III.IsSummingOperands)
3866     return false;
3867 
3868   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3869   if (!III.ZeroIsSpecialOrig)
3870     return false;
3871 
3872   // We cannot do the transform if the operand we are trying to replace
3873   // isn't the same as the operand the instruction allows.
3874   if (OpNoForForwarding != III.OpNoForForwarding)
3875     return false;
3876 
3877   // Check if the instruction we are trying to transform really has
3878   // the special zero register as its operand.
3879   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3880       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3881     return false;
3882 
3883   // This machine instruction is convertible if it is,
3884   // 1. summing the operands.
3885   // 2. one of the operands is special zero register.
3886   // 3. the operand we are trying to replace is allowed by the MI.
3887   return true;
3888 }
3889 
3890 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3891 // accordingly.
3892 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3893                                                const ImmInstrInfo &III,
3894                                                MachineOperand *&ImmMO,
3895                                                MachineOperand *&RegMO) const {
3896   unsigned Opc = DefMI.getOpcode();
3897   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3898     return false;
3899 
3900   assert(DefMI.getNumOperands() >= 3 &&
3901          "Add inst must have at least three operands");
3902   RegMO = &DefMI.getOperand(1);
3903   ImmMO = &DefMI.getOperand(2);
3904 
3905   // Before RA, ADDI first operand could be a frame index.
3906   if (!RegMO->isReg())
3907     return false;
3908 
3909   // This DefMI is elgible for forwarding if it is:
3910   // 1. add inst
3911   // 2. one of the operands is Imm/CPI/Global.
3912   return isAnImmediateOperand(*ImmMO);
3913 }
3914 
3915 bool PPCInstrInfo::isRegElgibleForForwarding(
3916     const MachineOperand &RegMO, const MachineInstr &DefMI,
3917     const MachineInstr &MI, bool KillDefMI,
3918     bool &IsFwdFeederRegKilled) const {
3919   // x = addi y, imm
3920   // ...
3921   // z = lfdx 0, x   -> z = lfd imm(y)
3922   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3923   // of "y" between the DEF of "x" and "z".
3924   // The query is only valid post RA.
3925   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3926   if (MRI.isSSA())
3927     return false;
3928 
3929   Register Reg = RegMO.getReg();
3930 
3931   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3932   MachineBasicBlock::const_reverse_iterator It = MI;
3933   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3934   It++;
3935   for (; It != E; ++It) {
3936     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3937       return false;
3938     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3939       IsFwdFeederRegKilled = true;
3940     // Made it to DefMI without encountering a clobber.
3941     if ((&*It) == &DefMI)
3942       break;
3943   }
3944   assert((&*It) == &DefMI && "DefMI is missing");
3945 
3946   // If DefMI also defines the register to be forwarded, we can only forward it
3947   // if DefMI is being erased.
3948   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3949     return KillDefMI;
3950 
3951   return true;
3952 }
3953 
3954 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3955                                              const MachineInstr &DefMI,
3956                                              const ImmInstrInfo &III,
3957                                              int64_t &Imm,
3958                                              int64_t BaseImm) const {
3959   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3960   if (DefMI.getOpcode() == PPC::ADDItocL) {
3961     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3962     // However, we know that, it is 16-bit width, and has the alignment of 4.
3963     // Check if the instruction met the requirement.
3964     if (III.ImmMustBeMultipleOf > 4 ||
3965        III.TruncateImmTo || III.ImmWidth != 16)
3966       return false;
3967 
3968     // Going from XForm to DForm loads means that the displacement needs to be
3969     // not just an immediate but also a multiple of 4, or 16 depending on the
3970     // load. A DForm load cannot be represented if it is a multiple of say 2.
3971     // XForm loads do not have this restriction.
3972     if (ImmMO.isGlobal()) {
3973       const DataLayout &DL = ImmMO.getGlobal()->getParent()->getDataLayout();
3974       if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf)
3975         return false;
3976     }
3977 
3978     return true;
3979   }
3980 
3981   if (ImmMO.isImm()) {
3982     // It is Imm, we need to check if the Imm fit the range.
3983     // Sign-extend to 64-bits.
3984     // DefMI may be folded with another imm form instruction, the result Imm is
3985     // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
3986     Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
3987 
3988     if (Imm % III.ImmMustBeMultipleOf)
3989       return false;
3990     if (III.TruncateImmTo)
3991       Imm &= ((1 << III.TruncateImmTo) - 1);
3992     if (III.SignedImm) {
3993       APInt ActualValue(64, Imm, true);
3994       if (!ActualValue.isSignedIntN(III.ImmWidth))
3995         return false;
3996     } else {
3997       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3998       if ((uint64_t)Imm > UnsignedMax)
3999         return false;
4000     }
4001   }
4002   else
4003     return false;
4004 
4005   // This ImmMO is forwarded if it meets the requriement describle
4006   // in ImmInstrInfo
4007   return true;
4008 }
4009 
4010 bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4011                                 unsigned OpNoForForwarding,
4012                                 MachineInstr **KilledDef) const {
4013   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4014       !DefMI.getOperand(1).isImm())
4015     return false;
4016 
4017   MachineFunction *MF = MI.getParent()->getParent();
4018   MachineRegisterInfo *MRI = &MF->getRegInfo();
4019   bool PostRA = !MRI->isSSA();
4020 
4021   int64_t Immediate = DefMI.getOperand(1).getImm();
4022   // Sign-extend to 64-bits.
4023   int64_t SExtImm = SignExtend64<16>(Immediate);
4024 
4025   bool IsForwardingOperandKilled = MI.getOperand(OpNoForForwarding).isKill();
4026   Register ForwardingOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4027 
4028   bool ReplaceWithLI = false;
4029   bool Is64BitLI = false;
4030   int64_t NewImm = 0;
4031   bool SetCR = false;
4032   unsigned Opc = MI.getOpcode();
4033   switch (Opc) {
4034   default:
4035     return false;
4036 
4037   // FIXME: Any branches conditional on such a comparison can be made
4038   // unconditional. At this time, this happens too infrequently to be worth
4039   // the implementation effort, but if that ever changes, we could convert
4040   // such a pattern here.
4041   case PPC::CMPWI:
4042   case PPC::CMPLWI:
4043   case PPC::CMPDI:
4044   case PPC::CMPLDI: {
4045     // Doing this post-RA would require dataflow analysis to reliably find uses
4046     // of the CR register set by the compare.
4047     // No need to fixup killed/dead flag since this transformation is only valid
4048     // before RA.
4049     if (PostRA)
4050       return false;
4051     // If a compare-immediate is fed by an immediate and is itself an input of
4052     // an ISEL (the most common case) into a COPY of the correct register.
4053     bool Changed = false;
4054     Register DefReg = MI.getOperand(0).getReg();
4055     int64_t Comparand = MI.getOperand(2).getImm();
4056     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4057                                 ? (Comparand | 0xFFFFFFFFFFFF0000)
4058                                 : Comparand;
4059 
4060     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
4061       unsigned UseOpc = CompareUseMI.getOpcode();
4062       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4063         continue;
4064       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
4065       Register TrueReg = CompareUseMI.getOperand(1).getReg();
4066       Register FalseReg = CompareUseMI.getOperand(2).getReg();
4067       unsigned RegToCopy =
4068           selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
4069       if (RegToCopy == PPC::NoRegister)
4070         continue;
4071       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4072       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4073         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4074         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
4075         CompareUseMI.RemoveOperand(3);
4076         CompareUseMI.RemoveOperand(2);
4077         continue;
4078       }
4079       LLVM_DEBUG(
4080           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4081       LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4082       LLVM_DEBUG(dbgs() << "Is converted to:\n");
4083       // Convert to copy and remove unneeded operands.
4084       CompareUseMI.setDesc(get(PPC::COPY));
4085       CompareUseMI.RemoveOperand(3);
4086       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
4087       CmpIselsConverted++;
4088       Changed = true;
4089       LLVM_DEBUG(CompareUseMI.dump());
4090     }
4091     if (Changed)
4092       return true;
4093     // This may end up incremented multiple times since this function is called
4094     // during a fixed-point transformation, but it is only meant to indicate the
4095     // presence of this opportunity.
4096     MissedConvertibleImmediateInstrs++;
4097     return false;
4098   }
4099 
4100   // Immediate forms - may simply be convertable to an LI.
4101   case PPC::ADDI:
4102   case PPC::ADDI8: {
4103     // Does the sum fit in a 16-bit signed field?
4104     int64_t Addend = MI.getOperand(2).getImm();
4105     if (isInt<16>(Addend + SExtImm)) {
4106       ReplaceWithLI = true;
4107       Is64BitLI = Opc == PPC::ADDI8;
4108       NewImm = Addend + SExtImm;
4109       break;
4110     }
4111     return false;
4112   }
4113   case PPC::SUBFIC:
4114   case PPC::SUBFIC8: {
4115     // Only transform this if the CARRY implicit operand is dead.
4116     if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
4117       return false;
4118     int64_t Minuend = MI.getOperand(2).getImm();
4119     if (isInt<16>(Minuend - SExtImm)) {
4120       ReplaceWithLI = true;
4121       Is64BitLI = Opc == PPC::SUBFIC8;
4122       NewImm = Minuend - SExtImm;
4123       break;
4124     }
4125     return false;
4126   }
4127   case PPC::RLDICL:
4128   case PPC::RLDICL_rec:
4129   case PPC::RLDICL_32:
4130   case PPC::RLDICL_32_64: {
4131     // Use APInt's rotate function.
4132     int64_t SH = MI.getOperand(2).getImm();
4133     int64_t MB = MI.getOperand(3).getImm();
4134     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4135                 SExtImm, true);
4136     InVal = InVal.rotl(SH);
4137     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4138     InVal &= Mask;
4139     // Can't replace negative values with an LI as that will sign-extend
4140     // and not clear the left bits. If we're setting the CR bit, we will use
4141     // ANDI_rec which won't sign extend, so that's safe.
4142     if (isUInt<15>(InVal.getSExtValue()) ||
4143         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
4144       ReplaceWithLI = true;
4145       Is64BitLI = Opc != PPC::RLDICL_32;
4146       NewImm = InVal.getSExtValue();
4147       SetCR = Opc == PPC::RLDICL_rec;
4148       break;
4149     }
4150     return false;
4151   }
4152   case PPC::RLWINM:
4153   case PPC::RLWINM8:
4154   case PPC::RLWINM_rec:
4155   case PPC::RLWINM8_rec: {
4156     int64_t SH = MI.getOperand(2).getImm();
4157     int64_t MB = MI.getOperand(3).getImm();
4158     int64_t ME = MI.getOperand(4).getImm();
4159     APInt InVal(32, SExtImm, true);
4160     InVal = InVal.rotl(SH);
4161     APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
4162     InVal &= Mask;
4163     // Can't replace negative values with an LI as that will sign-extend
4164     // and not clear the left bits. If we're setting the CR bit, we will use
4165     // ANDI_rec which won't sign extend, so that's safe.
4166     bool ValueFits = isUInt<15>(InVal.getSExtValue());
4167     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4168                   isUInt<16>(InVal.getSExtValue()));
4169     if (ValueFits) {
4170       ReplaceWithLI = true;
4171       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4172       NewImm = InVal.getSExtValue();
4173       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4174       break;
4175     }
4176     return false;
4177   }
4178   case PPC::ORI:
4179   case PPC::ORI8:
4180   case PPC::XORI:
4181   case PPC::XORI8: {
4182     int64_t LogicalImm = MI.getOperand(2).getImm();
4183     int64_t Result = 0;
4184     if (Opc == PPC::ORI || Opc == PPC::ORI8)
4185       Result = LogicalImm | SExtImm;
4186     else
4187       Result = LogicalImm ^ SExtImm;
4188     if (isInt<16>(Result)) {
4189       ReplaceWithLI = true;
4190       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4191       NewImm = Result;
4192       break;
4193     }
4194     return false;
4195   }
4196   }
4197 
4198   if (ReplaceWithLI) {
4199     // We need to be careful with CR-setting instructions we're replacing.
4200     if (SetCR) {
4201       // We don't know anything about uses when we're out of SSA, so only
4202       // replace if the new immediate will be reproduced.
4203       bool ImmChanged = (SExtImm & NewImm) != NewImm;
4204       if (PostRA && ImmChanged)
4205         return false;
4206 
4207       if (!PostRA) {
4208         // If the defining load-immediate has no other uses, we can just replace
4209         // the immediate with the new immediate.
4210         if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
4211           DefMI.getOperand(1).setImm(NewImm);
4212 
4213         // If we're not using the GPR result of the CR-setting instruction, we
4214         // just need to and with zero/non-zero depending on the new immediate.
4215         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
4216           if (NewImm) {
4217             assert(Immediate && "Transformation converted zero to non-zero?");
4218             NewImm = Immediate;
4219           }
4220         } else if (ImmChanged)
4221           return false;
4222       }
4223     }
4224 
4225     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4226     LLVM_DEBUG(MI.dump());
4227     LLVM_DEBUG(dbgs() << "Fed by:\n");
4228     LLVM_DEBUG(DefMI.dump());
4229     LoadImmediateInfo LII;
4230     LII.Imm = NewImm;
4231     LII.Is64Bit = Is64BitLI;
4232     LII.SetCR = SetCR;
4233     // If we're setting the CR, the original load-immediate must be kept (as an
4234     // operand to ANDI_rec/ANDI8_rec).
4235     if (KilledDef && SetCR)
4236       *KilledDef = nullptr;
4237     replaceInstrWithLI(MI, LII);
4238 
4239     // Fixup killed/dead flag after transformation.
4240     // Pattern:
4241     // ForwardingOperandReg = LI imm1
4242     // y = op2 imm2, ForwardingOperandReg(killed)
4243     if (IsForwardingOperandKilled)
4244       fixupIsDeadOrKill(&DefMI, &MI, ForwardingOperandReg);
4245 
4246     LLVM_DEBUG(dbgs() << "With:\n");
4247     LLVM_DEBUG(MI.dump());
4248     return true;
4249   }
4250   return false;
4251 }
4252 
4253 bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4254     MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4255   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4256   bool PostRA = !MRI->isSSA();
4257   // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4258   // for post-ra.
4259   if (PostRA)
4260     return false;
4261 
4262   // Only handle load/store.
4263   if (!MI.mayLoadOrStore())
4264     return false;
4265 
4266   unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
4267 
4268   assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4269          "MI must have x-form opcode");
4270 
4271   // get Imm Form info.
4272   ImmInstrInfo III;
4273   bool IsVFReg = MI.getOperand(0).isReg()
4274                      ? isVFRegister(MI.getOperand(0).getReg())
4275                      : false;
4276 
4277   if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
4278     return false;
4279 
4280   if (!III.IsSummingOperands)
4281     return false;
4282 
4283   if (OpNoForForwarding != III.OpNoForForwarding)
4284     return false;
4285 
4286   MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
4287   if (!ImmOperandMI.isImm())
4288     return false;
4289 
4290   // Check DefMI.
4291   MachineOperand *ImmMO = nullptr;
4292   MachineOperand *RegMO = nullptr;
4293   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4294     return false;
4295   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4296 
4297   // Check Imm.
4298   // Set ImmBase from imm instruction as base and get new Imm inside
4299   // isImmElgibleForForwarding.
4300   int64_t ImmBase = ImmOperandMI.getImm();
4301   int64_t Imm = 0;
4302   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
4303     return false;
4304 
4305   // Get killed info in case fixup needed after transformation.
4306   unsigned ForwardKilledOperandReg = ~0U;
4307   if (MI.getOperand(III.OpNoForForwarding).isKill())
4308     ForwardKilledOperandReg = MI.getOperand(III.OpNoForForwarding).getReg();
4309 
4310   // Do the transform
4311   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4312   LLVM_DEBUG(MI.dump());
4313   LLVM_DEBUG(dbgs() << "Fed by:\n");
4314   LLVM_DEBUG(DefMI.dump());
4315 
4316   MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
4317   MI.getOperand(III.OpNoForForwarding).setIsKill(RegMO->isKill());
4318   MI.getOperand(III.ImmOpNo).setImm(Imm);
4319 
4320   // FIXME: fix kill/dead flag if MI and DefMI are not in same basic block.
4321   if (DefMI.getParent() == MI.getParent()) {
4322     // Check if reg is killed between MI and DefMI.
4323     auto IsKilledFor = [&](unsigned Reg) {
4324       MachineBasicBlock::const_reverse_iterator It = MI;
4325       MachineBasicBlock::const_reverse_iterator E = DefMI;
4326       It++;
4327       for (; It != E; ++It) {
4328         if (It->killsRegister(Reg))
4329           return true;
4330       }
4331       return false;
4332     };
4333 
4334     // Update kill flag
4335     if (RegMO->isKill() || IsKilledFor(RegMO->getReg()))
4336       fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4337     if (ForwardKilledOperandReg != ~0U)
4338       fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4339   }
4340 
4341   LLVM_DEBUG(dbgs() << "With:\n");
4342   LLVM_DEBUG(MI.dump());
4343   return true;
4344 }
4345 
4346 // If an X-Form instruction is fed by an add-immediate and one of its operands
4347 // is the literal zero, attempt to forward the source of the add-immediate to
4348 // the corresponding D-Form instruction with the displacement coming from
4349 // the immediate being added.
4350 bool PPCInstrInfo::transformToImmFormFedByAdd(
4351     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4352     MachineInstr &DefMI, bool KillDefMI) const {
4353   //         RegMO ImmMO
4354   //           |    |
4355   // x = addi reg, imm  <----- DefMI
4356   // y = op    0 ,  x   <----- MI
4357   //                |
4358   //         OpNoForForwarding
4359   // Check if the MI meet the requirement described in the III.
4360   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4361     return false;
4362 
4363   // Check if the DefMI meet the requirement
4364   // described in the III. If yes, set the ImmMO and RegMO accordingly.
4365   MachineOperand *ImmMO = nullptr;
4366   MachineOperand *RegMO = nullptr;
4367   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4368     return false;
4369   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4370 
4371   // As we get the Imm operand now, we need to check if the ImmMO meet
4372   // the requirement described in the III. If yes set the Imm.
4373   int64_t Imm = 0;
4374   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
4375     return false;
4376 
4377   bool IsFwdFeederRegKilled = false;
4378   // Check if the RegMO can be forwarded to MI.
4379   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
4380                                  IsFwdFeederRegKilled))
4381     return false;
4382 
4383   // Get killed info in case fixup needed after transformation.
4384   unsigned ForwardKilledOperandReg = ~0U;
4385   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4386   bool PostRA = !MRI.isSSA();
4387   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
4388     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4389 
4390   // We know that, the MI and DefMI both meet the pattern, and
4391   // the Imm also meet the requirement with the new Imm-form.
4392   // It is safe to do the transformation now.
4393   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4394   LLVM_DEBUG(MI.dump());
4395   LLVM_DEBUG(dbgs() << "Fed by:\n");
4396   LLVM_DEBUG(DefMI.dump());
4397 
4398   // Update the base reg first.
4399   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
4400                                                         false, false,
4401                                                         RegMO->isKill());
4402 
4403   // Then, update the imm.
4404   if (ImmMO->isImm()) {
4405     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
4406     // directly.
4407     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
4408   }
4409   else {
4410     // Otherwise, it is Constant Pool Index(CPI) or Global,
4411     // which is relocation in fact. We need to replace the special zero
4412     // register with ImmMO.
4413     // Before that, we need to fixup the target flags for imm.
4414     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
4415     if (DefMI.getOpcode() == PPC::ADDItocL)
4416       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
4417 
4418     // MI didn't have the interface such as MI.setOperand(i) though
4419     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
4420     // ImmMO, we need to remove ZERO operand and all the operands behind it,
4421     // and, add the ImmMO, then, move back all the operands behind ZERO.
4422     SmallVector<MachineOperand, 2> MOps;
4423     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
4424       MOps.push_back(MI.getOperand(i));
4425       MI.RemoveOperand(i);
4426     }
4427 
4428     // Remove the last MO in the list, which is ZERO operand in fact.
4429     MOps.pop_back();
4430     // Add the imm operand.
4431     MI.addOperand(*ImmMO);
4432     // Now add the rest back.
4433     for (auto &MO : MOps)
4434       MI.addOperand(MO);
4435   }
4436 
4437   // Update the opcode.
4438   MI.setDesc(get(III.ImmOpcode));
4439 
4440   // Fix up killed/dead flag after transformation.
4441   // Pattern 1:
4442   // x = ADD KilledFwdFeederReg, imm
4443   // n = opn KilledFwdFeederReg(killed), regn
4444   // y = XOP 0, x
4445   // Pattern 2:
4446   // x = ADD reg(killed), imm
4447   // y = XOP 0, x
4448   if (IsFwdFeederRegKilled || RegMO->isKill())
4449     fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4450   // Pattern 3:
4451   // ForwardKilledOperandReg = ADD reg, imm
4452   // y = XOP 0, ForwardKilledOperandReg(killed)
4453   if (ForwardKilledOperandReg != ~0U)
4454     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4455 
4456   LLVM_DEBUG(dbgs() << "With:\n");
4457   LLVM_DEBUG(MI.dump());
4458 
4459   return true;
4460 }
4461 
4462 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
4463                                              const ImmInstrInfo &III,
4464                                              unsigned ConstantOpNo,
4465                                              MachineInstr &DefMI) const {
4466   // DefMI must be LI or LI8.
4467   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4468       !DefMI.getOperand(1).isImm())
4469     return false;
4470 
4471   // Get Imm operand and Sign-extend to 64-bits.
4472   int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
4473 
4474   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4475   bool PostRA = !MRI.isSSA();
4476   // Exit early if we can't convert this.
4477   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
4478     return false;
4479   if (Imm % III.ImmMustBeMultipleOf)
4480     return false;
4481   if (III.TruncateImmTo)
4482     Imm &= ((1 << III.TruncateImmTo) - 1);
4483   if (III.SignedImm) {
4484     APInt ActualValue(64, Imm, true);
4485     if (!ActualValue.isSignedIntN(III.ImmWidth))
4486       return false;
4487   } else {
4488     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
4489     if ((uint64_t)Imm > UnsignedMax)
4490       return false;
4491   }
4492 
4493   // If we're post-RA, the instructions don't agree on whether register zero is
4494   // special, we can transform this as long as the register operand that will
4495   // end up in the location where zero is special isn't R0.
4496   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
4497     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
4498       III.ZeroIsSpecialNew + 1;
4499     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
4500     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
4501     // If R0 is in the operand where zero is special for the new instruction,
4502     // it is unsafe to transform if the constant operand isn't that operand.
4503     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
4504         ConstantOpNo != III.ZeroIsSpecialNew)
4505       return false;
4506     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
4507         ConstantOpNo != PosForOrigZero)
4508       return false;
4509   }
4510 
4511   // Get killed info in case fixup needed after transformation.
4512   unsigned ForwardKilledOperandReg = ~0U;
4513   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
4514     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
4515 
4516   unsigned Opc = MI.getOpcode();
4517   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
4518                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
4519                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
4520                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
4521   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
4522                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
4523   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
4524                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
4525   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
4526                     Opc == PPC::SRD_rec;
4527 
4528   MI.setDesc(get(III.ImmOpcode));
4529   if (ConstantOpNo == III.OpNoForForwarding) {
4530     // Converting shifts to immediate form is a bit tricky since they may do
4531     // one of three things:
4532     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
4533     // 2. If the shift amount is zero, the result is unchanged (save for maybe
4534     //    setting CR0)
4535     // 3. If the shift amount is in [1, OpSize), it's just a shift
4536     if (SpecialShift32 || SpecialShift64) {
4537       LoadImmediateInfo LII;
4538       LII.Imm = 0;
4539       LII.SetCR = SetCR;
4540       LII.Is64Bit = SpecialShift64;
4541       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
4542       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
4543         replaceInstrWithLI(MI, LII);
4544       // Shifts by zero don't change the value. If we don't need to set CR0,
4545       // just convert this to a COPY. Can't do this post-RA since we've already
4546       // cleaned up the copies.
4547       else if (!SetCR && ShAmt == 0 && !PostRA) {
4548         MI.RemoveOperand(2);
4549         MI.setDesc(get(PPC::COPY));
4550       } else {
4551         // The 32 bit and 64 bit instructions are quite different.
4552         if (SpecialShift32) {
4553           // Left shifts use (N, 0, 31-N).
4554           // Right shifts use (32-N, N, 31) if 0 < N < 32.
4555           //              use (0, 0, 31)    if N == 0.
4556           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
4557           uint64_t MB = RightShift ? ShAmt : 0;
4558           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
4559           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4560           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
4561             .addImm(ME);
4562         } else {
4563           // Left shifts use (N, 63-N).
4564           // Right shifts use (64-N, N) if 0 < N < 64.
4565           //              use (0, 0)    if N == 0.
4566           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
4567           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
4568           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4569           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
4570         }
4571       }
4572     } else
4573       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
4574   }
4575   // Convert commutative instructions (switch the operands and convert the
4576   // desired one to an immediate.
4577   else if (III.IsCommutative) {
4578     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
4579     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
4580   } else
4581     llvm_unreachable("Should have exited early!");
4582 
4583   // For instructions for which the constant register replaces a different
4584   // operand than where the immediate goes, we need to swap them.
4585   if (III.OpNoForForwarding != III.ImmOpNo)
4586     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
4587 
4588   // If the special R0/X0 register index are different for original instruction
4589   // and new instruction, we need to fix up the register class in new
4590   // instruction.
4591   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
4592     if (III.ZeroIsSpecialNew) {
4593       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
4594       // need to fix up register class.
4595       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
4596       if (Register::isVirtualRegister(RegToModify)) {
4597         const TargetRegisterClass *NewRC =
4598           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
4599           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
4600         MRI.setRegClass(RegToModify, NewRC);
4601       }
4602     }
4603   }
4604 
4605   // Fix up killed/dead flag after transformation.
4606   // Pattern:
4607   // ForwardKilledOperandReg = LI imm
4608   // y = XOP reg, ForwardKilledOperandReg(killed)
4609   if (ForwardKilledOperandReg != ~0U)
4610     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4611   return true;
4612 }
4613 
4614 const TargetRegisterClass *
4615 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
4616   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
4617     return &PPC::VSRCRegClass;
4618   return RC;
4619 }
4620 
4621 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
4622   return PPC::getRecordFormOpcode(Opcode);
4623 }
4624 
4625 // This function returns true if the machine instruction
4626 // always outputs a value by sign-extending a 32 bit value,
4627 // i.e. 0 to 31-th bits are same as 32-th bit.
4628 static bool isSignExtendingOp(const MachineInstr &MI) {
4629   int Opcode = MI.getOpcode();
4630   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
4631       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
4632       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
4633       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
4634       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
4635       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
4636       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
4637       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
4638       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
4639       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
4640       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
4641       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
4642       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
4643       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
4644       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
4645       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
4646       Opcode == PPC::EXTSB8_32_64)
4647     return true;
4648 
4649   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
4650     return true;
4651 
4652   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
4653        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
4654       MI.getOperand(3).getImm() > 0 &&
4655       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
4656     return true;
4657 
4658   return false;
4659 }
4660 
4661 // This function returns true if the machine instruction
4662 // always outputs zeros in higher 32 bits.
4663 static bool isZeroExtendingOp(const MachineInstr &MI) {
4664   int Opcode = MI.getOpcode();
4665   // The 16-bit immediate is sign-extended in li/lis.
4666   // If the most significant bit is zero, all higher bits are zero.
4667   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
4668       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
4669     int64_t Imm = MI.getOperand(1).getImm();
4670     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
4671       return true;
4672   }
4673 
4674   // We have some variations of rotate-and-mask instructions
4675   // that clear higher 32-bits.
4676   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
4677        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
4678        Opcode == PPC::RLDICL_32_64) &&
4679       MI.getOperand(3).getImm() >= 32)
4680     return true;
4681 
4682   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
4683       MI.getOperand(3).getImm() >= 32 &&
4684       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
4685     return true;
4686 
4687   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
4688        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
4689        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
4690       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
4691     return true;
4692 
4693   // There are other instructions that clear higher 32-bits.
4694   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
4695       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
4696       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
4697       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
4698       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
4699       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
4700       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
4701       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
4702       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
4703       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
4704       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
4705       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
4706       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
4707       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
4708       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
4709       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
4710       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
4711       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
4712       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
4713       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
4714       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
4715       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
4716       Opcode == PPC::MFVSRWZ)
4717     return true;
4718 
4719   return false;
4720 }
4721 
4722 // This function returns true if the input MachineInstr is a TOC save
4723 // instruction.
4724 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
4725   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
4726     return false;
4727   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4728   unsigned StackOffset = MI.getOperand(1).getImm();
4729   Register StackReg = MI.getOperand(2).getReg();
4730   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
4731     return true;
4732 
4733   return false;
4734 }
4735 
4736 // We limit the max depth to track incoming values of PHIs or binary ops
4737 // (e.g. AND) to avoid excessive cost.
4738 const unsigned MAX_DEPTH = 1;
4739 
4740 bool
4741 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
4742                                    const unsigned Depth) const {
4743   const MachineFunction *MF = MI.getParent()->getParent();
4744   const MachineRegisterInfo *MRI = &MF->getRegInfo();
4745 
4746   // If we know this instruction returns sign- or zero-extended result,
4747   // return true.
4748   if (SignExt ? isSignExtendingOp(MI):
4749                 isZeroExtendingOp(MI))
4750     return true;
4751 
4752   switch (MI.getOpcode()) {
4753   case PPC::COPY: {
4754     Register SrcReg = MI.getOperand(1).getReg();
4755 
4756     // In both ELFv1 and v2 ABI, method parameters and the return value
4757     // are sign- or zero-extended.
4758     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
4759       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
4760       // We check the ZExt/SExt flags for a method parameter.
4761       if (MI.getParent()->getBasicBlock() ==
4762           &MF->getFunction().getEntryBlock()) {
4763         Register VReg = MI.getOperand(0).getReg();
4764         if (MF->getRegInfo().isLiveIn(VReg))
4765           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
4766                            FuncInfo->isLiveInZExt(VReg);
4767       }
4768 
4769       // For a method return value, we check the ZExt/SExt flags in attribute.
4770       // We assume the following code sequence for method call.
4771       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
4772       //   BL8_NOP @func,...
4773       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
4774       //   %5 = COPY %x3; G8RC:%5
4775       if (SrcReg == PPC::X3) {
4776         const MachineBasicBlock *MBB = MI.getParent();
4777         MachineBasicBlock::const_instr_iterator II =
4778           MachineBasicBlock::const_instr_iterator(&MI);
4779         if (II != MBB->instr_begin() &&
4780             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
4781           const MachineInstr &CallMI = *(--II);
4782           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
4783             const Function *CalleeFn =
4784               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
4785             if (!CalleeFn)
4786               return false;
4787             const IntegerType *IntTy =
4788               dyn_cast<IntegerType>(CalleeFn->getReturnType());
4789             const AttributeSet &Attrs =
4790               CalleeFn->getAttributes().getRetAttributes();
4791             if (IntTy && IntTy->getBitWidth() <= 32)
4792               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
4793                                                   Attribute::ZExt);
4794           }
4795         }
4796       }
4797     }
4798 
4799     // If this is a copy from another register, we recursively check source.
4800     if (!Register::isVirtualRegister(SrcReg))
4801       return false;
4802     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4803     if (SrcMI != NULL)
4804       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4805 
4806     return false;
4807   }
4808 
4809   case PPC::ANDI_rec:
4810   case PPC::ANDIS_rec:
4811   case PPC::ORI:
4812   case PPC::ORIS:
4813   case PPC::XORI:
4814   case PPC::XORIS:
4815   case PPC::ANDI8_rec:
4816   case PPC::ANDIS8_rec:
4817   case PPC::ORI8:
4818   case PPC::ORIS8:
4819   case PPC::XORI8:
4820   case PPC::XORIS8: {
4821     // logical operation with 16-bit immediate does not change the upper bits.
4822     // So, we track the operand register as we do for register copy.
4823     Register SrcReg = MI.getOperand(1).getReg();
4824     if (!Register::isVirtualRegister(SrcReg))
4825       return false;
4826     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4827     if (SrcMI != NULL)
4828       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4829 
4830     return false;
4831   }
4832 
4833   // If all incoming values are sign-/zero-extended,
4834   // the output of OR, ISEL or PHI is also sign-/zero-extended.
4835   case PPC::OR:
4836   case PPC::OR8:
4837   case PPC::ISEL:
4838   case PPC::PHI: {
4839     if (Depth >= MAX_DEPTH)
4840       return false;
4841 
4842     // The input registers for PHI are operand 1, 3, ...
4843     // The input registers for others are operand 1 and 2.
4844     unsigned E = 3, D = 1;
4845     if (MI.getOpcode() == PPC::PHI) {
4846       E = MI.getNumOperands();
4847       D = 2;
4848     }
4849 
4850     for (unsigned I = 1; I != E; I += D) {
4851       if (MI.getOperand(I).isReg()) {
4852         Register SrcReg = MI.getOperand(I).getReg();
4853         if (!Register::isVirtualRegister(SrcReg))
4854           return false;
4855         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4856         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
4857           return false;
4858       }
4859       else
4860         return false;
4861     }
4862     return true;
4863   }
4864 
4865   // If at least one of the incoming values of an AND is zero extended
4866   // then the output is also zero-extended. If both of the incoming values
4867   // are sign-extended then the output is also sign extended.
4868   case PPC::AND:
4869   case PPC::AND8: {
4870     if (Depth >= MAX_DEPTH)
4871        return false;
4872 
4873     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
4874 
4875     Register SrcReg1 = MI.getOperand(1).getReg();
4876     Register SrcReg2 = MI.getOperand(2).getReg();
4877 
4878     if (!Register::isVirtualRegister(SrcReg1) ||
4879         !Register::isVirtualRegister(SrcReg2))
4880       return false;
4881 
4882     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
4883     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
4884     if (!MISrc1 || !MISrc2)
4885         return false;
4886 
4887     if(SignExt)
4888         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
4889                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4890     else
4891         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
4892                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4893   }
4894 
4895   default:
4896     break;
4897   }
4898   return false;
4899 }
4900 
4901 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
4902   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
4903 }
4904 
4905 namespace {
4906 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
4907   MachineInstr *Loop, *EndLoop, *LoopCount;
4908   MachineFunction *MF;
4909   const TargetInstrInfo *TII;
4910   int64_t TripCount;
4911 
4912 public:
4913   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
4914                        MachineInstr *LoopCount)
4915       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
4916         MF(Loop->getParent()->getParent()),
4917         TII(MF->getSubtarget().getInstrInfo()) {
4918     // Inspect the Loop instruction up-front, as it may be deleted when we call
4919     // createTripCountGreaterCondition.
4920     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
4921       TripCount = LoopCount->getOperand(1).getImm();
4922     else
4923       TripCount = -1;
4924   }
4925 
4926   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
4927     // Only ignore the terminator.
4928     return MI == EndLoop;
4929   }
4930 
4931   Optional<bool>
4932   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
4933                                   SmallVectorImpl<MachineOperand> &Cond) override {
4934     if (TripCount == -1) {
4935       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4936       // so we don't need to generate any thing here.
4937       Cond.push_back(MachineOperand::CreateImm(0));
4938       Cond.push_back(MachineOperand::CreateReg(
4939           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
4940           true));
4941       return {};
4942     }
4943 
4944     return TripCount > TC;
4945   }
4946 
4947   void setPreheader(MachineBasicBlock *NewPreheader) override {
4948     // Do nothing. We want the LOOP setup instruction to stay in the *old*
4949     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
4950   }
4951 
4952   void adjustTripCount(int TripCountAdjust) override {
4953     // If the loop trip count is a compile-time value, then just change the
4954     // value.
4955     if (LoopCount->getOpcode() == PPC::LI8 ||
4956         LoopCount->getOpcode() == PPC::LI) {
4957       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
4958       LoopCount->getOperand(1).setImm(TripCount);
4959       return;
4960     }
4961 
4962     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4963     // so we don't need to generate any thing here.
4964   }
4965 
4966   void disposed() override {
4967     Loop->eraseFromParent();
4968     // Ensure the loop setup instruction is deleted too.
4969     LoopCount->eraseFromParent();
4970   }
4971 };
4972 } // namespace
4973 
4974 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4975 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4976   // We really "analyze" only hardware loops right now.
4977   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4978   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4979   if (Preheader == LoopBB)
4980     Preheader = *std::next(LoopBB->pred_begin());
4981   MachineFunction *MF = Preheader->getParent();
4982 
4983   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
4984     SmallPtrSet<MachineBasicBlock *, 8> Visited;
4985     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
4986       Register LoopCountReg = LoopInst->getOperand(0).getReg();
4987       MachineRegisterInfo &MRI = MF->getRegInfo();
4988       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
4989       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
4990     }
4991   }
4992   return nullptr;
4993 }
4994 
4995 MachineInstr *PPCInstrInfo::findLoopInstr(
4996     MachineBasicBlock &PreHeader,
4997     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
4998 
4999   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5000 
5001   // The loop set-up instruction should be in preheader
5002   for (auto &I : PreHeader.instrs())
5003     if (I.getOpcode() == LOOPi)
5004       return &I;
5005   return nullptr;
5006 }
5007 
5008 // Return true if get the base operand, byte offset of an instruction and the
5009 // memory width. Width is the size of memory that is being loaded/stored.
5010 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
5011     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
5012     unsigned &Width, const TargetRegisterInfo *TRI) const {
5013   if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5014     return false;
5015 
5016   // Handle only loads/stores with base register followed by immediate offset.
5017   if (!LdSt.getOperand(1).isImm() ||
5018       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5019     return false;
5020   if (!LdSt.getOperand(1).isImm() ||
5021       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5022     return false;
5023 
5024   if (!LdSt.hasOneMemOperand())
5025     return false;
5026 
5027   Width = (*LdSt.memoperands_begin())->getSize();
5028   Offset = LdSt.getOperand(1).getImm();
5029   BaseReg = &LdSt.getOperand(2);
5030   return true;
5031 }
5032 
5033 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
5034     const MachineInstr &MIa, const MachineInstr &MIb) const {
5035   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5036   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5037 
5038   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
5039       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
5040     return false;
5041 
5042   // Retrieve the base register, offset from the base register and width. Width
5043   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
5044   // base registers are identical, and the offset of a lower memory access +
5045   // the width doesn't overlap the offset of a higher memory access,
5046   // then the memory accesses are different.
5047   const TargetRegisterInfo *TRI = &getRegisterInfo();
5048   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5049   int64_t OffsetA = 0, OffsetB = 0;
5050   unsigned int WidthA = 0, WidthB = 0;
5051   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
5052       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
5053     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
5054       int LowOffset = std::min(OffsetA, OffsetB);
5055       int HighOffset = std::max(OffsetA, OffsetB);
5056       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5057       if (LowOffset + LowWidth <= HighOffset)
5058         return true;
5059     }
5060   }
5061   return false;
5062 }
5063