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