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