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