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 MCInst PPCInstrInfo::getNop() const {
1262   MCInst Nop;
1263   Nop.setOpcode(PPC::NOP);
1264   return Nop;
1265 }
1266 
1267 // Branch analysis.
1268 // Note: If the condition register is set to CTR or CTR8 then this is a
1269 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
1270 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
1271                                  MachineBasicBlock *&TBB,
1272                                  MachineBasicBlock *&FBB,
1273                                  SmallVectorImpl<MachineOperand> &Cond,
1274                                  bool AllowModify) const {
1275   bool isPPC64 = Subtarget.isPPC64();
1276 
1277   // If the block has no terminators, it just falls into the block after it.
1278   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1279   if (I == MBB.end())
1280     return false;
1281 
1282   if (!isUnpredicatedTerminator(*I))
1283     return false;
1284 
1285   if (AllowModify) {
1286     // If the BB ends with an unconditional branch to the fallthrough BB,
1287     // we eliminate the branch instruction.
1288     if (I->getOpcode() == PPC::B &&
1289         MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
1290       I->eraseFromParent();
1291 
1292       // We update iterator after deleting the last branch.
1293       I = MBB.getLastNonDebugInstr();
1294       if (I == MBB.end() || !isUnpredicatedTerminator(*I))
1295         return false;
1296     }
1297   }
1298 
1299   // Get the last instruction in the block.
1300   MachineInstr &LastInst = *I;
1301 
1302   // If there is only one terminator instruction, process it.
1303   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
1304     if (LastInst.getOpcode() == PPC::B) {
1305       if (!LastInst.getOperand(0).isMBB())
1306         return true;
1307       TBB = LastInst.getOperand(0).getMBB();
1308       return false;
1309     } else if (LastInst.getOpcode() == PPC::BCC) {
1310       if (!LastInst.getOperand(2).isMBB())
1311         return true;
1312       // Block ends with fall-through condbranch.
1313       TBB = LastInst.getOperand(2).getMBB();
1314       Cond.push_back(LastInst.getOperand(0));
1315       Cond.push_back(LastInst.getOperand(1));
1316       return false;
1317     } else if (LastInst.getOpcode() == PPC::BC) {
1318       if (!LastInst.getOperand(1).isMBB())
1319         return true;
1320       // Block ends with fall-through condbranch.
1321       TBB = LastInst.getOperand(1).getMBB();
1322       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
1323       Cond.push_back(LastInst.getOperand(0));
1324       return false;
1325     } else if (LastInst.getOpcode() == PPC::BCn) {
1326       if (!LastInst.getOperand(1).isMBB())
1327         return true;
1328       // Block ends with fall-through condbranch.
1329       TBB = LastInst.getOperand(1).getMBB();
1330       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
1331       Cond.push_back(LastInst.getOperand(0));
1332       return false;
1333     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
1334                LastInst.getOpcode() == PPC::BDNZ) {
1335       if (!LastInst.getOperand(0).isMBB())
1336         return true;
1337       if (DisableCTRLoopAnal)
1338         return true;
1339       TBB = LastInst.getOperand(0).getMBB();
1340       Cond.push_back(MachineOperand::CreateImm(1));
1341       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1342                                                true));
1343       return false;
1344     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
1345                LastInst.getOpcode() == PPC::BDZ) {
1346       if (!LastInst.getOperand(0).isMBB())
1347         return true;
1348       if (DisableCTRLoopAnal)
1349         return true;
1350       TBB = LastInst.getOperand(0).getMBB();
1351       Cond.push_back(MachineOperand::CreateImm(0));
1352       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1353                                                true));
1354       return false;
1355     }
1356 
1357     // Otherwise, don't know what this is.
1358     return true;
1359   }
1360 
1361   // Get the instruction before it if it's a terminator.
1362   MachineInstr &SecondLastInst = *I;
1363 
1364   // If there are three terminators, we don't know what sort of block this is.
1365   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
1366     return true;
1367 
1368   // If the block ends with PPC::B and PPC:BCC, handle it.
1369   if (SecondLastInst.getOpcode() == PPC::BCC &&
1370       LastInst.getOpcode() == PPC::B) {
1371     if (!SecondLastInst.getOperand(2).isMBB() ||
1372         !LastInst.getOperand(0).isMBB())
1373       return true;
1374     TBB = SecondLastInst.getOperand(2).getMBB();
1375     Cond.push_back(SecondLastInst.getOperand(0));
1376     Cond.push_back(SecondLastInst.getOperand(1));
1377     FBB = LastInst.getOperand(0).getMBB();
1378     return false;
1379   } else if (SecondLastInst.getOpcode() == PPC::BC &&
1380              LastInst.getOpcode() == PPC::B) {
1381     if (!SecondLastInst.getOperand(1).isMBB() ||
1382         !LastInst.getOperand(0).isMBB())
1383       return true;
1384     TBB = SecondLastInst.getOperand(1).getMBB();
1385     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
1386     Cond.push_back(SecondLastInst.getOperand(0));
1387     FBB = LastInst.getOperand(0).getMBB();
1388     return false;
1389   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
1390              LastInst.getOpcode() == PPC::B) {
1391     if (!SecondLastInst.getOperand(1).isMBB() ||
1392         !LastInst.getOperand(0).isMBB())
1393       return true;
1394     TBB = SecondLastInst.getOperand(1).getMBB();
1395     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
1396     Cond.push_back(SecondLastInst.getOperand(0));
1397     FBB = LastInst.getOperand(0).getMBB();
1398     return false;
1399   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
1400               SecondLastInst.getOpcode() == PPC::BDNZ) &&
1401              LastInst.getOpcode() == PPC::B) {
1402     if (!SecondLastInst.getOperand(0).isMBB() ||
1403         !LastInst.getOperand(0).isMBB())
1404       return true;
1405     if (DisableCTRLoopAnal)
1406       return true;
1407     TBB = SecondLastInst.getOperand(0).getMBB();
1408     Cond.push_back(MachineOperand::CreateImm(1));
1409     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1410                                              true));
1411     FBB = LastInst.getOperand(0).getMBB();
1412     return false;
1413   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
1414               SecondLastInst.getOpcode() == PPC::BDZ) &&
1415              LastInst.getOpcode() == PPC::B) {
1416     if (!SecondLastInst.getOperand(0).isMBB() ||
1417         !LastInst.getOperand(0).isMBB())
1418       return true;
1419     if (DisableCTRLoopAnal)
1420       return true;
1421     TBB = SecondLastInst.getOperand(0).getMBB();
1422     Cond.push_back(MachineOperand::CreateImm(0));
1423     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1424                                              true));
1425     FBB = LastInst.getOperand(0).getMBB();
1426     return false;
1427   }
1428 
1429   // If the block ends with two PPC:Bs, handle it.  The second one is not
1430   // executed, so remove it.
1431   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
1432     if (!SecondLastInst.getOperand(0).isMBB())
1433       return true;
1434     TBB = SecondLastInst.getOperand(0).getMBB();
1435     I = LastInst;
1436     if (AllowModify)
1437       I->eraseFromParent();
1438     return false;
1439   }
1440 
1441   // Otherwise, can't handle this.
1442   return true;
1443 }
1444 
1445 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
1446                                     int *BytesRemoved) const {
1447   assert(!BytesRemoved && "code size not handled");
1448 
1449   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1450   if (I == MBB.end())
1451     return 0;
1452 
1453   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
1454       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1455       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1456       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
1457     return 0;
1458 
1459   // Remove the branch.
1460   I->eraseFromParent();
1461 
1462   I = MBB.end();
1463 
1464   if (I == MBB.begin()) return 1;
1465   --I;
1466   if (I->getOpcode() != PPC::BCC &&
1467       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1468       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1469       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
1470     return 1;
1471 
1472   // Remove the branch.
1473   I->eraseFromParent();
1474   return 2;
1475 }
1476 
1477 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
1478                                     MachineBasicBlock *TBB,
1479                                     MachineBasicBlock *FBB,
1480                                     ArrayRef<MachineOperand> Cond,
1481                                     const DebugLoc &DL,
1482                                     int *BytesAdded) const {
1483   // Shouldn't be a fall through.
1484   assert(TBB && "insertBranch must not be told to insert a fallthrough");
1485   assert((Cond.size() == 2 || Cond.size() == 0) &&
1486          "PPC branch conditions have two components!");
1487   assert(!BytesAdded && "code size not handled");
1488 
1489   bool isPPC64 = Subtarget.isPPC64();
1490 
1491   // One-way branch.
1492   if (!FBB) {
1493     if (Cond.empty())   // Unconditional branch
1494       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
1495     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1496       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1497                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1498                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
1499     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1500       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1501     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1502       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1503     else                // Conditional branch
1504       BuildMI(&MBB, DL, get(PPC::BCC))
1505           .addImm(Cond[0].getImm())
1506           .add(Cond[1])
1507           .addMBB(TBB);
1508     return 1;
1509   }
1510 
1511   // Two-way Conditional Branch.
1512   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1513     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1514                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1515                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
1516   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1517     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1518   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1519     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1520   else
1521     BuildMI(&MBB, DL, get(PPC::BCC))
1522         .addImm(Cond[0].getImm())
1523         .add(Cond[1])
1524         .addMBB(TBB);
1525   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
1526   return 2;
1527 }
1528 
1529 // Select analysis.
1530 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1531                                    ArrayRef<MachineOperand> Cond,
1532                                    Register DstReg, Register TrueReg,
1533                                    Register FalseReg, int &CondCycles,
1534                                    int &TrueCycles, int &FalseCycles) const {
1535   if (Cond.size() != 2)
1536     return false;
1537 
1538   // If this is really a bdnz-like condition, then it cannot be turned into a
1539   // select.
1540   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1541     return false;
1542 
1543   // Check register classes.
1544   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1545   const TargetRegisterClass *RC =
1546     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1547   if (!RC)
1548     return false;
1549 
1550   // isel is for regular integer GPRs only.
1551   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
1552       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
1553       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
1554       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
1555     return false;
1556 
1557   // FIXME: These numbers are for the A2, how well they work for other cores is
1558   // an open question. On the A2, the isel instruction has a 2-cycle latency
1559   // but single-cycle throughput. These numbers are used in combination with
1560   // the MispredictPenalty setting from the active SchedMachineModel.
1561   CondCycles = 1;
1562   TrueCycles = 1;
1563   FalseCycles = 1;
1564 
1565   return true;
1566 }
1567 
1568 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
1569                                 MachineBasicBlock::iterator MI,
1570                                 const DebugLoc &dl, Register DestReg,
1571                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
1572                                 Register FalseReg) const {
1573   assert(Cond.size() == 2 &&
1574          "PPC branch conditions have two components!");
1575 
1576   // Get the register classes.
1577   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1578   const TargetRegisterClass *RC =
1579     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1580   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
1581 
1582   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
1583                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
1584   assert((Is64Bit ||
1585           PPC::GPRCRegClass.hasSubClassEq(RC) ||
1586           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
1587          "isel is for regular integer GPRs only");
1588 
1589   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
1590   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
1591 
1592   unsigned SubIdx = 0;
1593   bool SwapOps = false;
1594   switch (SelectPred) {
1595   case PPC::PRED_EQ:
1596   case PPC::PRED_EQ_MINUS:
1597   case PPC::PRED_EQ_PLUS:
1598       SubIdx = PPC::sub_eq; SwapOps = false; break;
1599   case PPC::PRED_NE:
1600   case PPC::PRED_NE_MINUS:
1601   case PPC::PRED_NE_PLUS:
1602       SubIdx = PPC::sub_eq; SwapOps = true; break;
1603   case PPC::PRED_LT:
1604   case PPC::PRED_LT_MINUS:
1605   case PPC::PRED_LT_PLUS:
1606       SubIdx = PPC::sub_lt; SwapOps = false; break;
1607   case PPC::PRED_GE:
1608   case PPC::PRED_GE_MINUS:
1609   case PPC::PRED_GE_PLUS:
1610       SubIdx = PPC::sub_lt; SwapOps = true; break;
1611   case PPC::PRED_GT:
1612   case PPC::PRED_GT_MINUS:
1613   case PPC::PRED_GT_PLUS:
1614       SubIdx = PPC::sub_gt; SwapOps = false; break;
1615   case PPC::PRED_LE:
1616   case PPC::PRED_LE_MINUS:
1617   case PPC::PRED_LE_PLUS:
1618       SubIdx = PPC::sub_gt; SwapOps = true; break;
1619   case PPC::PRED_UN:
1620   case PPC::PRED_UN_MINUS:
1621   case PPC::PRED_UN_PLUS:
1622       SubIdx = PPC::sub_un; SwapOps = false; break;
1623   case PPC::PRED_NU:
1624   case PPC::PRED_NU_MINUS:
1625   case PPC::PRED_NU_PLUS:
1626       SubIdx = PPC::sub_un; SwapOps = true; break;
1627   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
1628   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
1629   }
1630 
1631   Register FirstReg =  SwapOps ? FalseReg : TrueReg,
1632            SecondReg = SwapOps ? TrueReg  : FalseReg;
1633 
1634   // The first input register of isel cannot be r0. If it is a member
1635   // of a register class that can be r0, then copy it first (the
1636   // register allocator should eliminate the copy).
1637   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
1638       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
1639     const TargetRegisterClass *FirstRC =
1640       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
1641         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
1642     Register OldFirstReg = FirstReg;
1643     FirstReg = MRI.createVirtualRegister(FirstRC);
1644     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
1645       .addReg(OldFirstReg);
1646   }
1647 
1648   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
1649     .addReg(FirstReg).addReg(SecondReg)
1650     .addReg(Cond[1].getReg(), 0, SubIdx);
1651 }
1652 
1653 static unsigned getCRBitValue(unsigned CRBit) {
1654   unsigned Ret = 4;
1655   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
1656       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
1657       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
1658       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
1659     Ret = 3;
1660   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
1661       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
1662       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
1663       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
1664     Ret = 2;
1665   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
1666       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
1667       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
1668       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
1669     Ret = 1;
1670   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
1671       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
1672       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
1673       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
1674     Ret = 0;
1675 
1676   assert(Ret != 4 && "Invalid CR bit register");
1677   return Ret;
1678 }
1679 
1680 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
1681                                MachineBasicBlock::iterator I,
1682                                const DebugLoc &DL, MCRegister DestReg,
1683                                MCRegister SrcReg, bool KillSrc) const {
1684   // We can end up with self copies and similar things as a result of VSX copy
1685   // legalization. Promote them here.
1686   const TargetRegisterInfo *TRI = &getRegisterInfo();
1687   if (PPC::F8RCRegClass.contains(DestReg) &&
1688       PPC::VSRCRegClass.contains(SrcReg)) {
1689     MCRegister SuperReg =
1690         TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
1691 
1692     if (VSXSelfCopyCrash && SrcReg == SuperReg)
1693       llvm_unreachable("nop VSX copy");
1694 
1695     DestReg = SuperReg;
1696   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
1697              PPC::VSRCRegClass.contains(DestReg)) {
1698     MCRegister SuperReg =
1699         TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
1700 
1701     if (VSXSelfCopyCrash && DestReg == SuperReg)
1702       llvm_unreachable("nop VSX copy");
1703 
1704     SrcReg = SuperReg;
1705   }
1706 
1707   // Different class register copy
1708   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
1709       PPC::GPRCRegClass.contains(DestReg)) {
1710     MCRegister CRReg = getCRFromCRBit(SrcReg);
1711     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
1712     getKillRegState(KillSrc);
1713     // Rotate the CR bit in the CR fields to be the least significant bit and
1714     // then mask with 0x1 (MB = ME = 31).
1715     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
1716        .addReg(DestReg, RegState::Kill)
1717        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
1718        .addImm(31)
1719        .addImm(31);
1720     return;
1721   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
1722              (PPC::G8RCRegClass.contains(DestReg) ||
1723               PPC::GPRCRegClass.contains(DestReg))) {
1724     bool Is64Bit = PPC::G8RCRegClass.contains(DestReg);
1725     unsigned MvCode = Is64Bit ? PPC::MFOCRF8 : PPC::MFOCRF;
1726     unsigned ShCode = Is64Bit ? PPC::RLWINM8 : PPC::RLWINM;
1727     unsigned CRNum = TRI->getEncodingValue(SrcReg);
1728     BuildMI(MBB, I, DL, get(MvCode), DestReg).addReg(SrcReg);
1729     getKillRegState(KillSrc);
1730     if (CRNum == 7)
1731       return;
1732     // Shift the CR bits to make the CR field in the lowest 4 bits of GRC.
1733     BuildMI(MBB, I, DL, get(ShCode), DestReg)
1734         .addReg(DestReg, RegState::Kill)
1735         .addImm(CRNum * 4 + 4)
1736         .addImm(28)
1737         .addImm(31);
1738     return;
1739   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
1740              PPC::VSFRCRegClass.contains(DestReg)) {
1741     assert(Subtarget.hasDirectMove() &&
1742            "Subtarget doesn't support directmove, don't know how to copy.");
1743     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
1744     NumGPRtoVSRSpill++;
1745     getKillRegState(KillSrc);
1746     return;
1747   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
1748              PPC::G8RCRegClass.contains(DestReg)) {
1749     assert(Subtarget.hasDirectMove() &&
1750            "Subtarget doesn't support directmove, don't know how to copy.");
1751     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
1752     getKillRegState(KillSrc);
1753     return;
1754   } else if (PPC::SPERCRegClass.contains(SrcReg) &&
1755              PPC::GPRCRegClass.contains(DestReg)) {
1756     BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
1757     getKillRegState(KillSrc);
1758     return;
1759   } else if (PPC::GPRCRegClass.contains(SrcReg) &&
1760              PPC::SPERCRegClass.contains(DestReg)) {
1761     BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
1762     getKillRegState(KillSrc);
1763     return;
1764   }
1765 
1766   unsigned Opc;
1767   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
1768     Opc = PPC::OR;
1769   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
1770     Opc = PPC::OR8;
1771   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
1772     Opc = PPC::FMR;
1773   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
1774     Opc = PPC::MCRF;
1775   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
1776     Opc = PPC::VOR;
1777   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
1778     // There are two different ways this can be done:
1779     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1780     //      issue in VSU pipeline 0.
1781     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1782     //      can go to either pipeline.
1783     // We'll always use xxlor here, because in practically all cases where
1784     // copies are generated, they are close enough to some use that the
1785     // lower-latency form is preferable.
1786     Opc = PPC::XXLOR;
1787   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1788            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1789     Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1790   else if (Subtarget.pairedVectorMemops() &&
1791            PPC::VSRpRCRegClass.contains(DestReg, SrcReg)) {
1792     if (SrcReg > PPC::VSRp15)
1793       SrcReg = PPC::V0 + (SrcReg - PPC::VSRp16) * 2;
1794     else
1795       SrcReg = PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1796     if (DestReg > PPC::VSRp15)
1797       DestReg = PPC::V0 + (DestReg - PPC::VSRp16) * 2;
1798     else
1799       DestReg = PPC::VSL0 + (DestReg - PPC::VSRp0) * 2;
1800     BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg).
1801       addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1802     BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg + 1).
1803       addReg(SrcReg + 1).addReg(SrcReg + 1, getKillRegState(KillSrc));
1804     return;
1805   }
1806   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1807     Opc = PPC::CROR;
1808   else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1809     Opc = PPC::EVOR;
1810   else if ((PPC::ACCRCRegClass.contains(DestReg) ||
1811             PPC::UACCRCRegClass.contains(DestReg)) &&
1812            (PPC::ACCRCRegClass.contains(SrcReg) ||
1813             PPC::UACCRCRegClass.contains(SrcReg))) {
1814     // If primed, de-prime the source register, copy the individual registers
1815     // and prime the destination if needed. The vector subregisters are
1816     // vs[(u)acc * 4] - vs[(u)acc * 4 + 3]. If the copy is not a kill and the
1817     // source is primed, we need to re-prime it after the copy as well.
1818     PPCRegisterInfo::emitAccCopyInfo(MBB, DestReg, SrcReg);
1819     bool DestPrimed = PPC::ACCRCRegClass.contains(DestReg);
1820     bool SrcPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1821     MCRegister VSLSrcReg =
1822         PPC::VSL0 + (SrcReg - (SrcPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1823     MCRegister VSLDestReg =
1824         PPC::VSL0 + (DestReg - (DestPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1825     if (SrcPrimed)
1826       BuildMI(MBB, I, DL, get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1827     for (unsigned Idx = 0; Idx < 4; Idx++)
1828       BuildMI(MBB, I, DL, get(PPC::XXLOR), VSLDestReg + Idx)
1829           .addReg(VSLSrcReg + Idx)
1830           .addReg(VSLSrcReg + Idx, getKillRegState(KillSrc));
1831     if (DestPrimed)
1832       BuildMI(MBB, I, DL, get(PPC::XXMTACC), DestReg).addReg(DestReg);
1833     if (SrcPrimed && !KillSrc)
1834       BuildMI(MBB, I, DL, get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1835     return;
1836   } else
1837     llvm_unreachable("Impossible reg-to-reg copy");
1838 
1839   const MCInstrDesc &MCID = get(Opc);
1840   if (MCID.getNumOperands() == 3)
1841     BuildMI(MBB, I, DL, MCID, DestReg)
1842       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1843   else
1844     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1845 }
1846 
1847 unsigned PPCInstrInfo::getSpillIndex(const TargetRegisterClass *RC) const {
1848   int OpcodeIndex = 0;
1849 
1850   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1851       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1852     OpcodeIndex = SOK_Int4Spill;
1853   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1854              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1855     OpcodeIndex = SOK_Int8Spill;
1856   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1857     OpcodeIndex = SOK_Float8Spill;
1858   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1859     OpcodeIndex = SOK_Float4Spill;
1860   } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1861     OpcodeIndex = SOK_SPESpill;
1862   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1863     OpcodeIndex = SOK_CRSpill;
1864   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1865     OpcodeIndex = SOK_CRBitSpill;
1866   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1867     OpcodeIndex = SOK_VRVectorSpill;
1868   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1869     OpcodeIndex = SOK_VSXVectorSpill;
1870   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1871     OpcodeIndex = SOK_VectorFloat8Spill;
1872   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1873     OpcodeIndex = SOK_VectorFloat4Spill;
1874   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1875     OpcodeIndex = SOK_SpillToVSR;
1876   } else if (PPC::ACCRCRegClass.hasSubClassEq(RC)) {
1877     assert(Subtarget.pairedVectorMemops() &&
1878            "Register unexpected when paired memops are disabled.");
1879     OpcodeIndex = SOK_AccumulatorSpill;
1880   } else if (PPC::UACCRCRegClass.hasSubClassEq(RC)) {
1881     assert(Subtarget.pairedVectorMemops() &&
1882            "Register unexpected when paired memops are disabled.");
1883     OpcodeIndex = SOK_UAccumulatorSpill;
1884   } else if (PPC::VSRpRCRegClass.hasSubClassEq(RC)) {
1885     assert(Subtarget.pairedVectorMemops() &&
1886            "Register unexpected when paired memops are disabled.");
1887     OpcodeIndex = SOK_PairedVecSpill;
1888   } else {
1889     llvm_unreachable("Unknown regclass!");
1890   }
1891   return OpcodeIndex;
1892 }
1893 
1894 unsigned
1895 PPCInstrInfo::getStoreOpcodeForSpill(const TargetRegisterClass *RC) const {
1896   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1897   return OpcodesForSpill[getSpillIndex(RC)];
1898 }
1899 
1900 unsigned
1901 PPCInstrInfo::getLoadOpcodeForSpill(const TargetRegisterClass *RC) const {
1902   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1903   return OpcodesForSpill[getSpillIndex(RC)];
1904 }
1905 
1906 void PPCInstrInfo::StoreRegToStackSlot(
1907     MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1908     const TargetRegisterClass *RC,
1909     SmallVectorImpl<MachineInstr *> &NewMIs) const {
1910   unsigned Opcode = getStoreOpcodeForSpill(RC);
1911   DebugLoc DL;
1912 
1913   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1914   FuncInfo->setHasSpills();
1915 
1916   NewMIs.push_back(addFrameReference(
1917       BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1918       FrameIdx));
1919 
1920   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1921       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1922     FuncInfo->setSpillsCR();
1923 
1924   if (isXFormMemOp(Opcode))
1925     FuncInfo->setHasNonRISpills();
1926 }
1927 
1928 void PPCInstrInfo::storeRegToStackSlotNoUpd(
1929     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
1930     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
1931     const TargetRegisterInfo *TRI) const {
1932   MachineFunction &MF = *MBB.getParent();
1933   SmallVector<MachineInstr *, 4> NewMIs;
1934 
1935   StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1936 
1937   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1938     MBB.insert(MI, NewMIs[i]);
1939 
1940   const MachineFrameInfo &MFI = MF.getFrameInfo();
1941   MachineMemOperand *MMO = MF.getMachineMemOperand(
1942       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1943       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1944       MFI.getObjectAlign(FrameIdx));
1945   NewMIs.back()->addMemOperand(MF, MMO);
1946 }
1947 
1948 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1949                                        MachineBasicBlock::iterator MI,
1950                                        Register SrcReg, bool isKill,
1951                                        int FrameIdx,
1952                                        const TargetRegisterClass *RC,
1953                                        const TargetRegisterInfo *TRI) const {
1954   // We need to avoid a situation in which the value from a VRRC register is
1955   // spilled using an Altivec instruction and reloaded into a VSRC register
1956   // using a VSX instruction. The issue with this is that the VSX
1957   // load/store instructions swap the doublewords in the vector and the Altivec
1958   // ones don't. The register classes on the spill/reload may be different if
1959   // the register is defined using an Altivec instruction and is then used by a
1960   // VSX instruction.
1961   RC = updatedRC(RC);
1962   storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI);
1963 }
1964 
1965 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1966                                         unsigned DestReg, int FrameIdx,
1967                                         const TargetRegisterClass *RC,
1968                                         SmallVectorImpl<MachineInstr *> &NewMIs)
1969                                         const {
1970   unsigned Opcode = getLoadOpcodeForSpill(RC);
1971   NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1972                                      FrameIdx));
1973   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1974 
1975   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1976       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1977     FuncInfo->setSpillsCR();
1978 
1979   if (isXFormMemOp(Opcode))
1980     FuncInfo->setHasNonRISpills();
1981 }
1982 
1983 void PPCInstrInfo::loadRegFromStackSlotNoUpd(
1984     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
1985     int FrameIdx, const TargetRegisterClass *RC,
1986     const TargetRegisterInfo *TRI) const {
1987   MachineFunction &MF = *MBB.getParent();
1988   SmallVector<MachineInstr*, 4> NewMIs;
1989   DebugLoc DL;
1990   if (MI != MBB.end()) DL = MI->getDebugLoc();
1991 
1992   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1993   FuncInfo->setHasSpills();
1994 
1995   LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1996 
1997   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1998     MBB.insert(MI, NewMIs[i]);
1999 
2000   const MachineFrameInfo &MFI = MF.getFrameInfo();
2001   MachineMemOperand *MMO = MF.getMachineMemOperand(
2002       MachinePointerInfo::getFixedStack(MF, FrameIdx),
2003       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
2004       MFI.getObjectAlign(FrameIdx));
2005   NewMIs.back()->addMemOperand(MF, MMO);
2006 }
2007 
2008 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
2009                                         MachineBasicBlock::iterator MI,
2010                                         Register DestReg, int FrameIdx,
2011                                         const TargetRegisterClass *RC,
2012                                         const TargetRegisterInfo *TRI) const {
2013   // We need to avoid a situation in which the value from a VRRC register is
2014   // spilled using an Altivec instruction and reloaded into a VSRC register
2015   // using a VSX instruction. The issue with this is that the VSX
2016   // load/store instructions swap the doublewords in the vector and the Altivec
2017   // ones don't. The register classes on the spill/reload may be different if
2018   // the register is defined using an Altivec instruction and is then used by a
2019   // VSX instruction.
2020   RC = updatedRC(RC);
2021 
2022   loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI);
2023 }
2024 
2025 bool PPCInstrInfo::
2026 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
2027   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
2028   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
2029     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
2030   else
2031     // Leave the CR# the same, but invert the condition.
2032     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
2033   return false;
2034 }
2035 
2036 // For some instructions, it is legal to fold ZERO into the RA register field.
2037 // This function performs that fold by replacing the operand with PPC::ZERO,
2038 // it does not consider whether the load immediate zero is no longer in use.
2039 bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2040                                      Register Reg) const {
2041   // A zero immediate should always be loaded with a single li.
2042   unsigned DefOpc = DefMI.getOpcode();
2043   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
2044     return false;
2045   if (!DefMI.getOperand(1).isImm())
2046     return false;
2047   if (DefMI.getOperand(1).getImm() != 0)
2048     return false;
2049 
2050   // Note that we cannot here invert the arguments of an isel in order to fold
2051   // a ZERO into what is presented as the second argument. All we have here
2052   // is the condition bit, and that might come from a CR-logical bit operation.
2053 
2054   const MCInstrDesc &UseMCID = UseMI.getDesc();
2055 
2056   // Only fold into real machine instructions.
2057   if (UseMCID.isPseudo())
2058     return false;
2059 
2060   // We need to find which of the User's operands is to be folded, that will be
2061   // the operand that matches the given register ID.
2062   unsigned UseIdx;
2063   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
2064     if (UseMI.getOperand(UseIdx).isReg() &&
2065         UseMI.getOperand(UseIdx).getReg() == Reg)
2066       break;
2067 
2068   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
2069   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
2070 
2071   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
2072 
2073   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
2074   // register (which might also be specified as a pointer class kind).
2075   if (UseInfo->isLookupPtrRegClass()) {
2076     if (UseInfo->RegClass /* Kind */ != 1)
2077       return false;
2078   } else {
2079     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
2080         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
2081       return false;
2082   }
2083 
2084   // Make sure this is not tied to an output register (or otherwise
2085   // constrained). This is true for ST?UX registers, for example, which
2086   // are tied to their output registers.
2087   if (UseInfo->Constraints != 0)
2088     return false;
2089 
2090   MCRegister ZeroReg;
2091   if (UseInfo->isLookupPtrRegClass()) {
2092     bool isPPC64 = Subtarget.isPPC64();
2093     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
2094   } else {
2095     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
2096               PPC::ZERO8 : PPC::ZERO;
2097   }
2098 
2099   UseMI.getOperand(UseIdx).setReg(ZeroReg);
2100   return true;
2101 }
2102 
2103 // Folds zero into instructions which have a load immediate zero as an operand
2104 // but also recognize zero as immediate zero. If the definition of the load
2105 // has no more users it is deleted.
2106 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2107                                  Register Reg, MachineRegisterInfo *MRI) const {
2108   bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
2109   if (MRI->use_nodbg_empty(Reg))
2110     DefMI.eraseFromParent();
2111   return Changed;
2112 }
2113 
2114 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
2115   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2116        I != IE; ++I)
2117     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
2118       return true;
2119   return false;
2120 }
2121 
2122 // We should make sure that, if we're going to predicate both sides of a
2123 // condition (a diamond), that both sides don't define the counter register. We
2124 // can predicate counter-decrement-based branches, but while that predicates
2125 // the branching, it does not predicate the counter decrement. If we tried to
2126 // merge the triangle into one predicated block, we'd decrement the counter
2127 // twice.
2128 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
2129                      unsigned NumT, unsigned ExtraT,
2130                      MachineBasicBlock &FMBB,
2131                      unsigned NumF, unsigned ExtraF,
2132                      BranchProbability Probability) const {
2133   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
2134 }
2135 
2136 
2137 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
2138   // The predicated branches are identified by their type, not really by the
2139   // explicit presence of a predicate. Furthermore, some of them can be
2140   // predicated more than once. Because if conversion won't try to predicate
2141   // any instruction which already claims to be predicated (by returning true
2142   // here), always return false. In doing so, we let isPredicable() be the
2143   // final word on whether not the instruction can be (further) predicated.
2144 
2145   return false;
2146 }
2147 
2148 bool PPCInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2149                                         const MachineBasicBlock *MBB,
2150                                         const MachineFunction &MF) const {
2151   // Set MFFS and MTFSF as scheduling boundary to avoid unexpected code motion
2152   // across them, since some FP operations may change content of FPSCR.
2153   // TODO: Model FPSCR in PPC instruction definitions and remove the workaround
2154   if (MI.getOpcode() == PPC::MFFS || MI.getOpcode() == PPC::MTFSF)
2155     return true;
2156   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF);
2157 }
2158 
2159 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
2160                                         ArrayRef<MachineOperand> Pred) const {
2161   unsigned OpC = MI.getOpcode();
2162   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
2163     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2164       bool isPPC64 = Subtarget.isPPC64();
2165       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
2166                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
2167       // Need add Def and Use for CTR implicit operand.
2168       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2169           .addReg(Pred[1].getReg(), RegState::Implicit)
2170           .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
2171     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2172       MI.setDesc(get(PPC::BCLR));
2173       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2174     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2175       MI.setDesc(get(PPC::BCLRn));
2176       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2177     } else {
2178       MI.setDesc(get(PPC::BCCLR));
2179       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2180           .addImm(Pred[0].getImm())
2181           .add(Pred[1]);
2182     }
2183 
2184     return true;
2185   } else if (OpC == PPC::B) {
2186     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2187       bool isPPC64 = Subtarget.isPPC64();
2188       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
2189                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
2190       // Need add Def and Use for CTR implicit operand.
2191       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2192           .addReg(Pred[1].getReg(), RegState::Implicit)
2193           .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
2194     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2195       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2196       MI.RemoveOperand(0);
2197 
2198       MI.setDesc(get(PPC::BC));
2199       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2200           .add(Pred[1])
2201           .addMBB(MBB);
2202     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2203       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2204       MI.RemoveOperand(0);
2205 
2206       MI.setDesc(get(PPC::BCn));
2207       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2208           .add(Pred[1])
2209           .addMBB(MBB);
2210     } else {
2211       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2212       MI.RemoveOperand(0);
2213 
2214       MI.setDesc(get(PPC::BCC));
2215       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2216           .addImm(Pred[0].getImm())
2217           .add(Pred[1])
2218           .addMBB(MBB);
2219     }
2220 
2221     return true;
2222   } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
2223              OpC == PPC::BCTRL8) {
2224     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
2225       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
2226 
2227     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
2228     bool isPPC64 = Subtarget.isPPC64();
2229 
2230     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2231       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
2232                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
2233       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2234     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2235       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
2236                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
2237       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2238     } else {
2239       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
2240                              : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
2241       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2242           .addImm(Pred[0].getImm())
2243           .add(Pred[1]);
2244     }
2245 
2246     // Need add Def and Use for LR implicit operand.
2247     if (setLR)
2248       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2249           .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::Implicit)
2250           .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::ImplicitDefine);
2251 
2252     return true;
2253   }
2254 
2255   return false;
2256 }
2257 
2258 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
2259                                      ArrayRef<MachineOperand> Pred2) const {
2260   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
2261   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
2262 
2263   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
2264     return false;
2265   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
2266     return false;
2267 
2268   // P1 can only subsume P2 if they test the same condition register.
2269   if (Pred1[1].getReg() != Pred2[1].getReg())
2270     return false;
2271 
2272   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
2273   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
2274 
2275   if (P1 == P2)
2276     return true;
2277 
2278   // Does P1 subsume P2, e.g. GE subsumes GT.
2279   if (P1 == PPC::PRED_LE &&
2280       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
2281     return true;
2282   if (P1 == PPC::PRED_GE &&
2283       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
2284     return true;
2285 
2286   return false;
2287 }
2288 
2289 bool PPCInstrInfo::ClobbersPredicate(MachineInstr &MI,
2290                                      std::vector<MachineOperand> &Pred,
2291                                      bool SkipDead) const {
2292   // Note: At the present time, the contents of Pred from this function is
2293   // unused by IfConversion. This implementation follows ARM by pushing the
2294   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
2295   // predicate, instructions defining CTR or CTR8 are also included as
2296   // predicate-defining instructions.
2297 
2298   const TargetRegisterClass *RCs[] =
2299     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
2300       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
2301 
2302   bool Found = false;
2303   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2304     const MachineOperand &MO = MI.getOperand(i);
2305     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
2306       const TargetRegisterClass *RC = RCs[c];
2307       if (MO.isReg()) {
2308         if (MO.isDef() && RC->contains(MO.getReg())) {
2309           Pred.push_back(MO);
2310           Found = true;
2311         }
2312       } else if (MO.isRegMask()) {
2313         for (TargetRegisterClass::iterator I = RC->begin(),
2314              IE = RC->end(); I != IE; ++I)
2315           if (MO.clobbersPhysReg(*I)) {
2316             Pred.push_back(MO);
2317             Found = true;
2318           }
2319       }
2320     }
2321   }
2322 
2323   return Found;
2324 }
2325 
2326 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
2327                                   Register &SrcReg2, int &Mask,
2328                                   int &Value) const {
2329   unsigned Opc = MI.getOpcode();
2330 
2331   switch (Opc) {
2332   default: return false;
2333   case PPC::CMPWI:
2334   case PPC::CMPLWI:
2335   case PPC::CMPDI:
2336   case PPC::CMPLDI:
2337     SrcReg = MI.getOperand(1).getReg();
2338     SrcReg2 = 0;
2339     Value = MI.getOperand(2).getImm();
2340     Mask = 0xFFFF;
2341     return true;
2342   case PPC::CMPW:
2343   case PPC::CMPLW:
2344   case PPC::CMPD:
2345   case PPC::CMPLD:
2346   case PPC::FCMPUS:
2347   case PPC::FCMPUD:
2348     SrcReg = MI.getOperand(1).getReg();
2349     SrcReg2 = MI.getOperand(2).getReg();
2350     Value = 0;
2351     Mask = 0;
2352     return true;
2353   }
2354 }
2355 
2356 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
2357                                         Register SrcReg2, int Mask, int Value,
2358                                         const MachineRegisterInfo *MRI) const {
2359   if (DisableCmpOpt)
2360     return false;
2361 
2362   int OpC = CmpInstr.getOpcode();
2363   Register CRReg = CmpInstr.getOperand(0).getReg();
2364 
2365   // FP record forms set CR1 based on the exception status bits, not a
2366   // comparison with zero.
2367   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
2368     return false;
2369 
2370   const TargetRegisterInfo *TRI = &getRegisterInfo();
2371   // The record forms set the condition register based on a signed comparison
2372   // with zero (so says the ISA manual). This is not as straightforward as it
2373   // seems, however, because this is always a 64-bit comparison on PPC64, even
2374   // for instructions that are 32-bit in nature (like slw for example).
2375   // So, on PPC32, for unsigned comparisons, we can use the record forms only
2376   // for equality checks (as those don't depend on the sign). On PPC64,
2377   // we are restricted to equality for unsigned 64-bit comparisons and for
2378   // signed 32-bit comparisons the applicability is more restricted.
2379   bool isPPC64 = Subtarget.isPPC64();
2380   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
2381   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
2382   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
2383 
2384   // Look through copies unless that gets us to a physical register.
2385   Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
2386   if (ActualSrc.isVirtual())
2387     SrcReg = ActualSrc;
2388 
2389   // Get the unique definition of SrcReg.
2390   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2391   if (!MI) return false;
2392 
2393   bool equalityOnly = false;
2394   bool noSub = false;
2395   if (isPPC64) {
2396     if (is32BitSignedCompare) {
2397       // We can perform this optimization only if MI is sign-extending.
2398       if (isSignExtended(*MI))
2399         noSub = true;
2400       else
2401         return false;
2402     } else if (is32BitUnsignedCompare) {
2403       // We can perform this optimization, equality only, if MI is
2404       // zero-extending.
2405       if (isZeroExtended(*MI)) {
2406         noSub = true;
2407         equalityOnly = true;
2408       } else
2409         return false;
2410     } else
2411       equalityOnly = is64BitUnsignedCompare;
2412   } else
2413     equalityOnly = is32BitUnsignedCompare;
2414 
2415   if (equalityOnly) {
2416     // We need to check the uses of the condition register in order to reject
2417     // non-equality comparisons.
2418     for (MachineRegisterInfo::use_instr_iterator
2419          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2420          I != IE; ++I) {
2421       MachineInstr *UseMI = &*I;
2422       if (UseMI->getOpcode() == PPC::BCC) {
2423         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
2424         unsigned PredCond = PPC::getPredicateCondition(Pred);
2425         // We ignore hint bits when checking for non-equality comparisons.
2426         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
2427           return false;
2428       } else if (UseMI->getOpcode() == PPC::ISEL ||
2429                  UseMI->getOpcode() == PPC::ISEL8) {
2430         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
2431         if (SubIdx != PPC::sub_eq)
2432           return false;
2433       } else
2434         return false;
2435     }
2436   }
2437 
2438   MachineBasicBlock::iterator I = CmpInstr;
2439 
2440   // Scan forward to find the first use of the compare.
2441   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
2442        ++I) {
2443     bool FoundUse = false;
2444     for (MachineRegisterInfo::use_instr_iterator
2445          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
2446          J != JE; ++J)
2447       if (&*J == &*I) {
2448         FoundUse = true;
2449         break;
2450       }
2451 
2452     if (FoundUse)
2453       break;
2454   }
2455 
2456   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
2457   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
2458 
2459   // There are two possible candidates which can be changed to set CR[01].
2460   // One is MI, the other is a SUB instruction.
2461   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2462   MachineInstr *Sub = nullptr;
2463   if (SrcReg2 != 0)
2464     // MI is not a candidate for CMPrr.
2465     MI = nullptr;
2466   // FIXME: Conservatively refuse to convert an instruction which isn't in the
2467   // same BB as the comparison. This is to allow the check below to avoid calls
2468   // (and other explicit clobbers); instead we should really check for these
2469   // more explicitly (in at least a few predecessors).
2470   else if (MI->getParent() != CmpInstr.getParent())
2471     return false;
2472   else if (Value != 0) {
2473     // The record-form instructions set CR bit based on signed comparison
2474     // against 0. We try to convert a compare against 1 or -1 into a compare
2475     // against 0 to exploit record-form instructions. For example, we change
2476     // the condition "greater than -1" into "greater than or equal to 0"
2477     // and "less than 1" into "less than or equal to 0".
2478 
2479     // Since we optimize comparison based on a specific branch condition,
2480     // we don't optimize if condition code is used by more than once.
2481     if (equalityOnly || !MRI->hasOneUse(CRReg))
2482       return false;
2483 
2484     MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
2485     if (UseMI->getOpcode() != PPC::BCC)
2486       return false;
2487 
2488     PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
2489     unsigned PredCond = PPC::getPredicateCondition(Pred);
2490     unsigned PredHint = PPC::getPredicateHint(Pred);
2491     int16_t Immed = (int16_t)Value;
2492 
2493     // When modifying the condition in the predicate, we propagate hint bits
2494     // from the original predicate to the new one.
2495     if (Immed == -1 && PredCond == PPC::PRED_GT)
2496       // We convert "greater than -1" into "greater than or equal to 0",
2497       // since we are assuming signed comparison by !equalityOnly
2498       Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
2499     else if (Immed == -1 && PredCond == PPC::PRED_LE)
2500       // We convert "less than or equal to -1" into "less than 0".
2501       Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
2502     else if (Immed == 1 && PredCond == PPC::PRED_LT)
2503       // We convert "less than 1" into "less than or equal to 0".
2504       Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
2505     else if (Immed == 1 && PredCond == PPC::PRED_GE)
2506       // We convert "greater than or equal to 1" into "greater than 0".
2507       Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
2508     else
2509       return false;
2510 
2511     PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
2512   }
2513 
2514   // Search for Sub.
2515   --I;
2516 
2517   // Get ready to iterate backward from CmpInstr.
2518   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
2519 
2520   for (; I != E && !noSub; --I) {
2521     const MachineInstr &Instr = *I;
2522     unsigned IOpC = Instr.getOpcode();
2523 
2524     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
2525                              Instr.readsRegister(PPC::CR0, TRI)))
2526       // This instruction modifies or uses the record condition register after
2527       // the one we want to change. While we could do this transformation, it
2528       // would likely not be profitable. This transformation removes one
2529       // instruction, and so even forcing RA to generate one move probably
2530       // makes it unprofitable.
2531       return false;
2532 
2533     // Check whether CmpInstr can be made redundant by the current instruction.
2534     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
2535          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
2536         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
2537         ((Instr.getOperand(1).getReg() == SrcReg &&
2538           Instr.getOperand(2).getReg() == SrcReg2) ||
2539         (Instr.getOperand(1).getReg() == SrcReg2 &&
2540          Instr.getOperand(2).getReg() == SrcReg))) {
2541       Sub = &*I;
2542       break;
2543     }
2544 
2545     if (I == B)
2546       // The 'and' is below the comparison instruction.
2547       return false;
2548   }
2549 
2550   // Return false if no candidates exist.
2551   if (!MI && !Sub)
2552     return false;
2553 
2554   // The single candidate is called MI.
2555   if (!MI) MI = Sub;
2556 
2557   int NewOpC = -1;
2558   int MIOpC = MI->getOpcode();
2559   if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
2560       MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
2561     NewOpC = MIOpC;
2562   else {
2563     NewOpC = PPC::getRecordFormOpcode(MIOpC);
2564     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
2565       NewOpC = MIOpC;
2566   }
2567 
2568   // FIXME: On the non-embedded POWER architectures, only some of the record
2569   // forms are fast, and we should use only the fast ones.
2570 
2571   // The defining instruction has a record form (or is already a record
2572   // form). It is possible, however, that we'll need to reverse the condition
2573   // code of the users.
2574   if (NewOpC == -1)
2575     return false;
2576 
2577   // This transformation should not be performed if `nsw` is missing and is not
2578   // `equalityOnly` comparison. Since if there is overflow, sub_lt, sub_gt in
2579   // CRReg do not reflect correct order. If `equalityOnly` is true, sub_eq in
2580   // CRReg can reflect if compared values are equal, this optz is still valid.
2581   if (!equalityOnly && (NewOpC == PPC::SUBF_rec || NewOpC == PPC::SUBF8_rec) &&
2582       Sub && !Sub->getFlag(MachineInstr::NoSWrap))
2583     return false;
2584 
2585   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
2586   // needs to be updated to be based on SUB.  Push the condition code
2587   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
2588   // condition code of these operands will be modified.
2589   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
2590   // comparison against 0, which may modify predicate.
2591   bool ShouldSwap = false;
2592   if (Sub && Value == 0) {
2593     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2594       Sub->getOperand(2).getReg() == SrcReg;
2595 
2596     // The operands to subf are the opposite of sub, so only in the fixed-point
2597     // case, invert the order.
2598     ShouldSwap = !ShouldSwap;
2599   }
2600 
2601   if (ShouldSwap)
2602     for (MachineRegisterInfo::use_instr_iterator
2603          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2604          I != IE; ++I) {
2605       MachineInstr *UseMI = &*I;
2606       if (UseMI->getOpcode() == PPC::BCC) {
2607         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
2608         unsigned PredCond = PPC::getPredicateCondition(Pred);
2609         assert((!equalityOnly ||
2610                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
2611                "Invalid predicate for equality-only optimization");
2612         (void)PredCond; // To suppress warning in release build.
2613         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
2614                                 PPC::getSwappedPredicate(Pred)));
2615       } else if (UseMI->getOpcode() == PPC::ISEL ||
2616                  UseMI->getOpcode() == PPC::ISEL8) {
2617         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
2618         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
2619                "Invalid CR bit for equality-only optimization");
2620 
2621         if (NewSubReg == PPC::sub_lt)
2622           NewSubReg = PPC::sub_gt;
2623         else if (NewSubReg == PPC::sub_gt)
2624           NewSubReg = PPC::sub_lt;
2625 
2626         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
2627                                                  NewSubReg));
2628       } else // We need to abort on a user we don't understand.
2629         return false;
2630     }
2631   assert(!(Value != 0 && ShouldSwap) &&
2632          "Non-zero immediate support and ShouldSwap"
2633          "may conflict in updating predicate");
2634 
2635   // Create a new virtual register to hold the value of the CR set by the
2636   // record-form instruction. If the instruction was not previously in
2637   // record form, then set the kill flag on the CR.
2638   CmpInstr.eraseFromParent();
2639 
2640   MachineBasicBlock::iterator MII = MI;
2641   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
2642           get(TargetOpcode::COPY), CRReg)
2643     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
2644 
2645   // Even if CR0 register were dead before, it is alive now since the
2646   // instruction we just built uses it.
2647   MI->clearRegisterDeads(PPC::CR0);
2648 
2649   if (MIOpC != NewOpC) {
2650     // We need to be careful here: we're replacing one instruction with
2651     // another, and we need to make sure that we get all of the right
2652     // implicit uses and defs. On the other hand, the caller may be holding
2653     // an iterator to this instruction, and so we can't delete it (this is
2654     // specifically the case if this is the instruction directly after the
2655     // compare).
2656 
2657     // Rotates are expensive instructions. If we're emitting a record-form
2658     // rotate that can just be an andi/andis, we should just emit that.
2659     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
2660       Register GPRRes = MI->getOperand(0).getReg();
2661       int64_t SH = MI->getOperand(2).getImm();
2662       int64_t MB = MI->getOperand(3).getImm();
2663       int64_t ME = MI->getOperand(4).getImm();
2664       // We can only do this if both the start and end of the mask are in the
2665       // same halfword.
2666       bool MBInLoHWord = MB >= 16;
2667       bool MEInLoHWord = ME >= 16;
2668       uint64_t Mask = ~0LLU;
2669 
2670       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
2671         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2672         // The mask value needs to shift right 16 if we're emitting andis.
2673         Mask >>= MBInLoHWord ? 0 : 16;
2674         NewOpC = MIOpC == PPC::RLWINM
2675                      ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
2676                      : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
2677       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
2678                  (ME - MB + 1 == SH) && (MB >= 16)) {
2679         // If we are rotating by the exact number of bits as are in the mask
2680         // and the mask is in the least significant bits of the register,
2681         // that's just an andis. (as long as the GPR result has no uses).
2682         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
2683         Mask >>= 16;
2684         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
2685       }
2686       // If we've set the mask, we can transform.
2687       if (Mask != ~0LLU) {
2688         MI->RemoveOperand(4);
2689         MI->RemoveOperand(3);
2690         MI->getOperand(2).setImm(Mask);
2691         NumRcRotatesConvertedToRcAnd++;
2692       }
2693     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
2694       int64_t MB = MI->getOperand(3).getImm();
2695       if (MB >= 48) {
2696         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2697         NewOpC = PPC::ANDI8_rec;
2698         MI->RemoveOperand(3);
2699         MI->getOperand(2).setImm(Mask);
2700         NumRcRotatesConvertedToRcAnd++;
2701       }
2702     }
2703 
2704     const MCInstrDesc &NewDesc = get(NewOpC);
2705     MI->setDesc(NewDesc);
2706 
2707     if (NewDesc.ImplicitDefs)
2708       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
2709            *ImpDefs; ++ImpDefs)
2710         if (!MI->definesRegister(*ImpDefs))
2711           MI->addOperand(*MI->getParent()->getParent(),
2712                          MachineOperand::CreateReg(*ImpDefs, true, true));
2713     if (NewDesc.ImplicitUses)
2714       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
2715            *ImpUses; ++ImpUses)
2716         if (!MI->readsRegister(*ImpUses))
2717           MI->addOperand(*MI->getParent()->getParent(),
2718                          MachineOperand::CreateReg(*ImpUses, false, true));
2719   }
2720   assert(MI->definesRegister(PPC::CR0) &&
2721          "Record-form instruction does not define cr0?");
2722 
2723   // Modify the condition code of operands in OperandsToUpdate.
2724   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2725   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2726   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2727     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2728 
2729   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2730     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2731 
2732   return true;
2733 }
2734 
2735 bool PPCInstrInfo::getMemOperandsWithOffsetWidth(
2736     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2737     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
2738     const TargetRegisterInfo *TRI) const {
2739   const MachineOperand *BaseOp;
2740   OffsetIsScalable = false;
2741   if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))
2742     return false;
2743   BaseOps.push_back(BaseOp);
2744   return true;
2745 }
2746 
2747 static bool isLdStSafeToCluster(const MachineInstr &LdSt,
2748                                 const TargetRegisterInfo *TRI) {
2749   // If this is a volatile load/store, don't mess with it.
2750   if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
2751     return false;
2752 
2753   if (LdSt.getOperand(2).isFI())
2754     return true;
2755 
2756   assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
2757   // Can't cluster if the instruction modifies the base register
2758   // or it is update form. e.g. ld r2,3(r2)
2759   if (LdSt.modifiesRegister(LdSt.getOperand(2).getReg(), TRI))
2760     return false;
2761 
2762   return true;
2763 }
2764 
2765 // Only cluster instruction pair that have the same opcode, and they are
2766 // clusterable according to PowerPC specification.
2767 static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
2768                                      const PPCSubtarget &Subtarget) {
2769   switch (FirstOpc) {
2770   default:
2771     return false;
2772   case PPC::STD:
2773   case PPC::STFD:
2774   case PPC::STXSD:
2775   case PPC::DFSTOREf64:
2776     return FirstOpc == SecondOpc;
2777   // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
2778   // 32bit and 64bit instruction selection. They are clusterable pair though
2779   // they are different opcode.
2780   case PPC::STW:
2781   case PPC::STW8:
2782     return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
2783   }
2784 }
2785 
2786 bool PPCInstrInfo::shouldClusterMemOps(
2787     ArrayRef<const MachineOperand *> BaseOps1,
2788     ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
2789     unsigned NumBytes) const {
2790 
2791   assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
2792   const MachineOperand &BaseOp1 = *BaseOps1.front();
2793   const MachineOperand &BaseOp2 = *BaseOps2.front();
2794   assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
2795          "Only base registers and frame indices are supported.");
2796 
2797   // The NumLoads means the number of loads that has been clustered.
2798   // Don't cluster memory op if there are already two ops clustered at least.
2799   if (NumLoads > 2)
2800     return false;
2801 
2802   // Cluster the load/store only when they have the same base
2803   // register or FI.
2804   if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
2805       (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
2806       (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
2807     return false;
2808 
2809   // Check if the load/store are clusterable according to the PowerPC
2810   // specification.
2811   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
2812   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
2813   unsigned FirstOpc = FirstLdSt.getOpcode();
2814   unsigned SecondOpc = SecondLdSt.getOpcode();
2815   const TargetRegisterInfo *TRI = &getRegisterInfo();
2816   // Cluster the load/store only when they have the same opcode, and they are
2817   // clusterable opcode according to PowerPC specification.
2818   if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
2819     return false;
2820 
2821   // Can't cluster load/store that have ordered or volatile memory reference.
2822   if (!isLdStSafeToCluster(FirstLdSt, TRI) ||
2823       !isLdStSafeToCluster(SecondLdSt, TRI))
2824     return false;
2825 
2826   int64_t Offset1 = 0, Offset2 = 0;
2827   unsigned Width1 = 0, Width2 = 0;
2828   const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
2829   if (!getMemOperandWithOffsetWidth(FirstLdSt, Base1, Offset1, Width1, TRI) ||
2830       !getMemOperandWithOffsetWidth(SecondLdSt, Base2, Offset2, Width2, TRI) ||
2831       Width1 != Width2)
2832     return false;
2833 
2834   assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
2835          "getMemOperandWithOffsetWidth return incorrect base op");
2836   // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
2837   assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
2838   return Offset1 + Width1 == Offset2;
2839 }
2840 
2841 /// GetInstSize - Return the number of bytes of code the specified
2842 /// instruction may be.  This returns the maximum number of bytes.
2843 ///
2844 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2845   unsigned Opcode = MI.getOpcode();
2846 
2847   if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2848     const MachineFunction *MF = MI.getParent()->getParent();
2849     const char *AsmStr = MI.getOperand(0).getSymbolName();
2850     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2851   } else if (Opcode == TargetOpcode::STACKMAP) {
2852     StackMapOpers Opers(&MI);
2853     return Opers.getNumPatchBytes();
2854   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2855     PatchPointOpers Opers(&MI);
2856     return Opers.getNumPatchBytes();
2857   } else {
2858     return get(Opcode).getSize();
2859   }
2860 }
2861 
2862 std::pair<unsigned, unsigned>
2863 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2864   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2865   return std::make_pair(TF & Mask, TF & ~Mask);
2866 }
2867 
2868 ArrayRef<std::pair<unsigned, const char *>>
2869 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2870   using namespace PPCII;
2871   static const std::pair<unsigned, const char *> TargetFlags[] = {
2872       {MO_LO, "ppc-lo"},
2873       {MO_HA, "ppc-ha"},
2874       {MO_TPREL_LO, "ppc-tprel-lo"},
2875       {MO_TPREL_HA, "ppc-tprel-ha"},
2876       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2877       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2878       {MO_TOC_LO, "ppc-toc-lo"},
2879       {MO_TLS, "ppc-tls"}};
2880   return makeArrayRef(TargetFlags);
2881 }
2882 
2883 ArrayRef<std::pair<unsigned, const char *>>
2884 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2885   using namespace PPCII;
2886   static const std::pair<unsigned, const char *> TargetFlags[] = {
2887       {MO_PLT, "ppc-plt"},
2888       {MO_PIC_FLAG, "ppc-pic"},
2889       {MO_PCREL_FLAG, "ppc-pcrel"},
2890       {MO_GOT_FLAG, "ppc-got"},
2891       {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
2892       {MO_TLSGD_FLAG, "ppc-tlsgd"},
2893       {MO_TLSLD_FLAG, "ppc-tlsld"},
2894       {MO_TPREL_FLAG, "ppc-tprel"},
2895       {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
2896       {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
2897       {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"}};
2898   return makeArrayRef(TargetFlags);
2899 }
2900 
2901 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2902 // The VSX versions have the advantage of a full 64-register target whereas
2903 // the FP ones have the advantage of lower latency and higher throughput. So
2904 // what we are after is using the faster instructions in low register pressure
2905 // situations and using the larger register file in high register pressure
2906 // situations.
2907 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2908     unsigned UpperOpcode, LowerOpcode;
2909     switch (MI.getOpcode()) {
2910     case PPC::DFLOADf32:
2911       UpperOpcode = PPC::LXSSP;
2912       LowerOpcode = PPC::LFS;
2913       break;
2914     case PPC::DFLOADf64:
2915       UpperOpcode = PPC::LXSD;
2916       LowerOpcode = PPC::LFD;
2917       break;
2918     case PPC::DFSTOREf32:
2919       UpperOpcode = PPC::STXSSP;
2920       LowerOpcode = PPC::STFS;
2921       break;
2922     case PPC::DFSTOREf64:
2923       UpperOpcode = PPC::STXSD;
2924       LowerOpcode = PPC::STFD;
2925       break;
2926     case PPC::XFLOADf32:
2927       UpperOpcode = PPC::LXSSPX;
2928       LowerOpcode = PPC::LFSX;
2929       break;
2930     case PPC::XFLOADf64:
2931       UpperOpcode = PPC::LXSDX;
2932       LowerOpcode = PPC::LFDX;
2933       break;
2934     case PPC::XFSTOREf32:
2935       UpperOpcode = PPC::STXSSPX;
2936       LowerOpcode = PPC::STFSX;
2937       break;
2938     case PPC::XFSTOREf64:
2939       UpperOpcode = PPC::STXSDX;
2940       LowerOpcode = PPC::STFDX;
2941       break;
2942     case PPC::LIWAX:
2943       UpperOpcode = PPC::LXSIWAX;
2944       LowerOpcode = PPC::LFIWAX;
2945       break;
2946     case PPC::LIWZX:
2947       UpperOpcode = PPC::LXSIWZX;
2948       LowerOpcode = PPC::LFIWZX;
2949       break;
2950     case PPC::STIWX:
2951       UpperOpcode = PPC::STXSIWX;
2952       LowerOpcode = PPC::STFIWX;
2953       break;
2954     default:
2955       llvm_unreachable("Unknown Operation!");
2956     }
2957 
2958     Register TargetReg = MI.getOperand(0).getReg();
2959     unsigned Opcode;
2960     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2961         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2962       Opcode = LowerOpcode;
2963     else
2964       Opcode = UpperOpcode;
2965     MI.setDesc(get(Opcode));
2966     return true;
2967 }
2968 
2969 static bool isAnImmediateOperand(const MachineOperand &MO) {
2970   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2971 }
2972 
2973 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2974   auto &MBB = *MI.getParent();
2975   auto DL = MI.getDebugLoc();
2976 
2977   switch (MI.getOpcode()) {
2978   case PPC::BUILD_UACC: {
2979     MCRegister ACC = MI.getOperand(0).getReg();
2980     MCRegister UACC = MI.getOperand(1).getReg();
2981     if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
2982       MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
2983       MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
2984       // FIXME: This can easily be improved to look up to the top of the MBB
2985       // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
2986       // we can just re-target any such XXLOR's to DstVSR + offset.
2987       for (int VecNo = 0; VecNo < 4; VecNo++)
2988         BuildMI(MBB, MI, DL, get(PPC::XXLOR), DstVSR + VecNo)
2989             .addReg(SrcVSR + VecNo)
2990             .addReg(SrcVSR + VecNo);
2991     }
2992     // BUILD_UACC is expanded to 4 copies of the underlying vsx regisers.
2993     // So after building the 4 copies, we can replace the BUILD_UACC instruction
2994     // with a NOP.
2995     LLVM_FALLTHROUGH;
2996   }
2997   case PPC::KILL_PAIR: {
2998     MI.setDesc(get(PPC::UNENCODED_NOP));
2999     MI.RemoveOperand(1);
3000     MI.RemoveOperand(0);
3001     return true;
3002   }
3003   case TargetOpcode::LOAD_STACK_GUARD: {
3004     assert(Subtarget.isTargetLinux() &&
3005            "Only Linux target is expected to contain LOAD_STACK_GUARD");
3006     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
3007     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
3008     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
3009     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3010         .addImm(Offset)
3011         .addReg(Reg);
3012     return true;
3013   }
3014   case PPC::DFLOADf32:
3015   case PPC::DFLOADf64:
3016   case PPC::DFSTOREf32:
3017   case PPC::DFSTOREf64: {
3018     assert(Subtarget.hasP9Vector() &&
3019            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
3020     assert(MI.getOperand(2).isReg() &&
3021            isAnImmediateOperand(MI.getOperand(1)) &&
3022            "D-form op must have register and immediate operands");
3023     return expandVSXMemPseudo(MI);
3024   }
3025   case PPC::XFLOADf32:
3026   case PPC::XFSTOREf32:
3027   case PPC::LIWAX:
3028   case PPC::LIWZX:
3029   case PPC::STIWX: {
3030     assert(Subtarget.hasP8Vector() &&
3031            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
3032     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3033            "X-form op must have register and register operands");
3034     return expandVSXMemPseudo(MI);
3035   }
3036   case PPC::XFLOADf64:
3037   case PPC::XFSTOREf64: {
3038     assert(Subtarget.hasVSX() &&
3039            "Invalid X-Form Pseudo-ops on target that has no VSX.");
3040     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3041            "X-form op must have register and register operands");
3042     return expandVSXMemPseudo(MI);
3043   }
3044   case PPC::SPILLTOVSR_LD: {
3045     Register TargetReg = MI.getOperand(0).getReg();
3046     if (PPC::VSFRCRegClass.contains(TargetReg)) {
3047       MI.setDesc(get(PPC::DFLOADf64));
3048       return expandPostRAPseudo(MI);
3049     }
3050     else
3051       MI.setDesc(get(PPC::LD));
3052     return true;
3053   }
3054   case PPC::SPILLTOVSR_ST: {
3055     Register SrcReg = MI.getOperand(0).getReg();
3056     if (PPC::VSFRCRegClass.contains(SrcReg)) {
3057       NumStoreSPILLVSRRCAsVec++;
3058       MI.setDesc(get(PPC::DFSTOREf64));
3059       return expandPostRAPseudo(MI);
3060     } else {
3061       NumStoreSPILLVSRRCAsGpr++;
3062       MI.setDesc(get(PPC::STD));
3063     }
3064     return true;
3065   }
3066   case PPC::SPILLTOVSR_LDX: {
3067     Register TargetReg = MI.getOperand(0).getReg();
3068     if (PPC::VSFRCRegClass.contains(TargetReg))
3069       MI.setDesc(get(PPC::LXSDX));
3070     else
3071       MI.setDesc(get(PPC::LDX));
3072     return true;
3073   }
3074   case PPC::SPILLTOVSR_STX: {
3075     Register SrcReg = MI.getOperand(0).getReg();
3076     if (PPC::VSFRCRegClass.contains(SrcReg)) {
3077       NumStoreSPILLVSRRCAsVec++;
3078       MI.setDesc(get(PPC::STXSDX));
3079     } else {
3080       NumStoreSPILLVSRRCAsGpr++;
3081       MI.setDesc(get(PPC::STDX));
3082     }
3083     return true;
3084   }
3085 
3086   case PPC::CFENCE8: {
3087     auto Val = MI.getOperand(0).getReg();
3088     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
3089     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
3090         .addImm(PPC::PRED_NE_MINUS)
3091         .addReg(PPC::CR7)
3092         .addImm(1);
3093     MI.setDesc(get(PPC::ISYNC));
3094     MI.RemoveOperand(0);
3095     return true;
3096   }
3097   }
3098   return false;
3099 }
3100 
3101 // Essentially a compile-time implementation of a compare->isel sequence.
3102 // It takes two constants to compare, along with the true/false registers
3103 // and the comparison type (as a subreg to a CR field) and returns one
3104 // of the true/false registers, depending on the comparison results.
3105 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
3106                           unsigned TrueReg, unsigned FalseReg,
3107                           unsigned CRSubReg) {
3108   // Signed comparisons. The immediates are assumed to be sign-extended.
3109   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
3110     switch (CRSubReg) {
3111     default: llvm_unreachable("Unknown integer comparison type.");
3112     case PPC::sub_lt:
3113       return Imm1 < Imm2 ? TrueReg : FalseReg;
3114     case PPC::sub_gt:
3115       return Imm1 > Imm2 ? TrueReg : FalseReg;
3116     case PPC::sub_eq:
3117       return Imm1 == Imm2 ? TrueReg : FalseReg;
3118     }
3119   }
3120   // Unsigned comparisons.
3121   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
3122     switch (CRSubReg) {
3123     default: llvm_unreachable("Unknown integer comparison type.");
3124     case PPC::sub_lt:
3125       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
3126     case PPC::sub_gt:
3127       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
3128     case PPC::sub_eq:
3129       return Imm1 == Imm2 ? TrueReg : FalseReg;
3130     }
3131   }
3132   return PPC::NoRegister;
3133 }
3134 
3135 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
3136                                               unsigned OpNo,
3137                                               int64_t Imm) const {
3138   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
3139   // Replace the REG with the Immediate.
3140   Register InUseReg = MI.getOperand(OpNo).getReg();
3141   MI.getOperand(OpNo).ChangeToImmediate(Imm);
3142 
3143   if (MI.implicit_operands().empty())
3144     return;
3145 
3146   // We need to make sure that the MI didn't have any implicit use
3147   // of this REG any more.
3148   const TargetRegisterInfo *TRI = &getRegisterInfo();
3149   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
3150   if (UseOpIdx >= 0) {
3151     MachineOperand &MO = MI.getOperand(UseOpIdx);
3152     if (MO.isImplicit())
3153       // The operands must always be in the following order:
3154       // - explicit reg defs,
3155       // - other explicit operands (reg uses, immediates, etc.),
3156       // - implicit reg defs
3157       // - implicit reg uses
3158       // Therefore, removing the implicit operand won't change the explicit
3159       // operands layout.
3160       MI.RemoveOperand(UseOpIdx);
3161   }
3162 }
3163 
3164 // Replace an instruction with one that materializes a constant (and sets
3165 // CR0 if the original instruction was a record-form instruction).
3166 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
3167                                       const LoadImmediateInfo &LII) const {
3168   // Remove existing operands.
3169   int OperandToKeep = LII.SetCR ? 1 : 0;
3170   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
3171     MI.RemoveOperand(i);
3172 
3173   // Replace the instruction.
3174   if (LII.SetCR) {
3175     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3176     // Set the immediate.
3177     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3178         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
3179     return;
3180   }
3181   else
3182     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
3183 
3184   // Set the immediate.
3185   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3186       .addImm(LII.Imm);
3187 }
3188 
3189 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
3190                                            bool &SeenIntermediateUse) const {
3191   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
3192          "Should be called after register allocation.");
3193   const TargetRegisterInfo *TRI = &getRegisterInfo();
3194   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
3195   It++;
3196   SeenIntermediateUse = false;
3197   for (; It != E; ++It) {
3198     if (It->modifiesRegister(Reg, TRI))
3199       return &*It;
3200     if (It->readsRegister(Reg, TRI))
3201       SeenIntermediateUse = true;
3202   }
3203   return nullptr;
3204 }
3205 
3206 MachineInstr *PPCInstrInfo::getForwardingDefMI(
3207   MachineInstr &MI,
3208   unsigned &OpNoForForwarding,
3209   bool &SeenIntermediateUse) const {
3210   OpNoForForwarding = ~0U;
3211   MachineInstr *DefMI = nullptr;
3212   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3213   const TargetRegisterInfo *TRI = &getRegisterInfo();
3214   // If we're in SSA, get the defs through the MRI. Otherwise, only look
3215   // within the basic block to see if the register is defined using an
3216   // LI/LI8/ADDI/ADDI8.
3217   if (MRI->isSSA()) {
3218     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3219       if (!MI.getOperand(i).isReg())
3220         continue;
3221       Register Reg = MI.getOperand(i).getReg();
3222       if (!Register::isVirtualRegister(Reg))
3223         continue;
3224       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
3225       if (Register::isVirtualRegister(TrueReg)) {
3226         DefMI = MRI->getVRegDef(TrueReg);
3227         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8 ||
3228             DefMI->getOpcode() == PPC::ADDI ||
3229             DefMI->getOpcode() == PPC::ADDI8) {
3230           OpNoForForwarding = i;
3231           // The ADDI and LI operand maybe exist in one instruction at same
3232           // time. we prefer to fold LI operand as LI only has one Imm operand
3233           // and is more possible to be converted. So if current DefMI is
3234           // ADDI/ADDI8, we continue to find possible LI/LI8.
3235           if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
3236             break;
3237         }
3238       }
3239     }
3240   } else {
3241     // Looking back through the definition for each operand could be expensive,
3242     // so exit early if this isn't an instruction that either has an immediate
3243     // form or is already an immediate form that we can handle.
3244     ImmInstrInfo III;
3245     unsigned Opc = MI.getOpcode();
3246     bool ConvertibleImmForm =
3247         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
3248         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
3249         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
3250         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
3251         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
3252         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
3253         Opc == PPC::RLWINM8_rec;
3254     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
3255                        ? isVFRegister(MI.getOperand(0).getReg())
3256                        : false;
3257     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
3258       return nullptr;
3259 
3260     // Don't convert or %X, %Y, %Y since that's just a register move.
3261     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
3262         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
3263       return nullptr;
3264     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3265       MachineOperand &MO = MI.getOperand(i);
3266       SeenIntermediateUse = false;
3267       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
3268         Register Reg = MI.getOperand(i).getReg();
3269         // If we see another use of this reg between the def and the MI,
3270         // we want to flat it so the def isn't deleted.
3271         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
3272         if (DefMI) {
3273           // Is this register defined by some form of add-immediate (including
3274           // load-immediate) within this basic block?
3275           switch (DefMI->getOpcode()) {
3276           default:
3277             break;
3278           case PPC::LI:
3279           case PPC::LI8:
3280           case PPC::ADDItocL:
3281           case PPC::ADDI:
3282           case PPC::ADDI8:
3283             OpNoForForwarding = i;
3284             return DefMI;
3285           }
3286         }
3287       }
3288     }
3289   }
3290   return OpNoForForwarding == ~0U ? nullptr : DefMI;
3291 }
3292 
3293 unsigned PPCInstrInfo::getSpillTarget() const {
3294   // With P10, we may need to spill paired vector registers or accumulator
3295   // registers. MMA implies paired vectors, so we can just check that.
3296   bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
3297   return IsP10Variant ? 2 : Subtarget.hasP9Vector() ? 1 : 0;
3298 }
3299 
3300 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
3301   return StoreSpillOpcodesArray[getSpillTarget()];
3302 }
3303 
3304 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
3305   return LoadSpillOpcodesArray[getSpillTarget()];
3306 }
3307 
3308 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr *StartMI, MachineInstr *EndMI,
3309                                      unsigned RegNo) const {
3310   // Conservatively clear kill flag for the register if the instructions are in
3311   // different basic blocks and in SSA form, because the kill flag may no longer
3312   // be right. There is no need to bother with dead flags since defs with no
3313   // uses will be handled by DCE.
3314   MachineRegisterInfo &MRI = StartMI->getParent()->getParent()->getRegInfo();
3315   if (MRI.isSSA() && (StartMI->getParent() != EndMI->getParent())) {
3316     MRI.clearKillFlags(RegNo);
3317     return;
3318   }
3319 
3320   // Instructions between [StartMI, EndMI] should be in same basic block.
3321   assert((StartMI->getParent() == EndMI->getParent()) &&
3322          "Instructions are not in same basic block");
3323 
3324   // If before RA, StartMI may be def through COPY, we need to adjust it to the
3325   // real def. See function getForwardingDefMI.
3326   if (MRI.isSSA()) {
3327     bool Reads, Writes;
3328     std::tie(Reads, Writes) = StartMI->readsWritesVirtualRegister(RegNo);
3329     if (!Reads && !Writes) {
3330       assert(Register::isVirtualRegister(RegNo) &&
3331              "Must be a virtual register");
3332       // Get real def and ignore copies.
3333       StartMI = MRI.getVRegDef(RegNo);
3334     }
3335   }
3336 
3337   bool IsKillSet = false;
3338 
3339   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
3340     MachineOperand &MO = MI.getOperand(Index);
3341     if (MO.isReg() && MO.isUse() && MO.isKill() &&
3342         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
3343       MO.setIsKill(false);
3344   };
3345 
3346   // Set killed flag for EndMI.
3347   // No need to do anything if EndMI defines RegNo.
3348   int UseIndex =
3349       EndMI->findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
3350   if (UseIndex != -1) {
3351     EndMI->getOperand(UseIndex).setIsKill(true);
3352     IsKillSet = true;
3353     // Clear killed flag for other EndMI operands related to RegNo. In some
3354     // upexpected cases, killed may be set multiple times for same register
3355     // operand in same MI.
3356     for (int i = 0, e = EndMI->getNumOperands(); i != e; ++i)
3357       if (i != UseIndex)
3358         clearOperandKillInfo(*EndMI, i);
3359   }
3360 
3361   // Walking the inst in reverse order (EndMI -> StartMI].
3362   MachineBasicBlock::reverse_iterator It = *EndMI;
3363   MachineBasicBlock::reverse_iterator E = EndMI->getParent()->rend();
3364   // EndMI has been handled above, skip it here.
3365   It++;
3366   MachineOperand *MO = nullptr;
3367   for (; It != E; ++It) {
3368     // Skip insturctions which could not be a def/use of RegNo.
3369     if (It->isDebugInstr() || It->isPosition())
3370       continue;
3371 
3372     // Clear killed flag for all It operands related to RegNo. In some
3373     // upexpected cases, killed may be set multiple times for same register
3374     // operand in same MI.
3375     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
3376         clearOperandKillInfo(*It, i);
3377 
3378     // If killed is not set, set killed for its last use or set dead for its def
3379     // if no use found.
3380     if (!IsKillSet) {
3381       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
3382         // Use found, set it killed.
3383         IsKillSet = true;
3384         MO->setIsKill(true);
3385         continue;
3386       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
3387                                                   &getRegisterInfo()))) {
3388         // No use found, set dead for its def.
3389         assert(&*It == StartMI && "No new def between StartMI and EndMI.");
3390         MO->setIsDead(true);
3391         break;
3392       }
3393     }
3394 
3395     if ((&*It) == StartMI)
3396       break;
3397   }
3398   // Ensure RegMo liveness is killed after EndMI.
3399   assert((IsKillSet || (MO && MO->isDead())) &&
3400          "RegNo should be killed or dead");
3401 }
3402 
3403 // This opt tries to convert the following imm form to an index form to save an
3404 // add for stack variables.
3405 // Return false if no such pattern found.
3406 //
3407 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3408 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
3409 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
3410 //
3411 // can be converted to:
3412 //
3413 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
3414 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
3415 //
3416 // In order to eliminate ADD instr, make sure that:
3417 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
3418 //    new ADDI instr and ADDI can only take int16 Imm.
3419 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
3420 //    between ADDI and ADD instr since its original def in ADDI will be changed
3421 //    in new ADDI instr. And also there should be no new def for it between
3422 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
3423 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
3424 //    between ADD and Imm instr since ADD instr will be eliminated.
3425 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
3426 //    moved to Index instr.
3427 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
3428   MachineFunction *MF = MI.getParent()->getParent();
3429   MachineRegisterInfo *MRI = &MF->getRegInfo();
3430   bool PostRA = !MRI->isSSA();
3431   // Do this opt after PEI which is after RA. The reason is stack slot expansion
3432   // in PEI may expose such opportunities since in PEI, stack slot offsets to
3433   // frame base(OffsetAddi) are determined.
3434   if (!PostRA)
3435     return false;
3436   unsigned ToBeDeletedReg = 0;
3437   int64_t OffsetImm = 0;
3438   unsigned XFormOpcode = 0;
3439   ImmInstrInfo III;
3440 
3441   // Check if Imm instr meets requirement.
3442   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
3443                                     III))
3444     return false;
3445 
3446   bool OtherIntermediateUse = false;
3447   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
3448 
3449   // Exit if there is other use between ADD and Imm instr or no def found.
3450   if (OtherIntermediateUse || !ADDMI)
3451     return false;
3452 
3453   // Check if ADD instr meets requirement.
3454   if (!isADDInstrEligibleForFolding(*ADDMI))
3455     return false;
3456 
3457   unsigned ScaleRegIdx = 0;
3458   int64_t OffsetAddi = 0;
3459   MachineInstr *ADDIMI = nullptr;
3460 
3461   // Check if there is a valid ToBeChangedReg in ADDMI.
3462   // 1: It must be killed.
3463   // 2: Its definition must be a valid ADDIMI.
3464   // 3: It must satify int16 offset requirement.
3465   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
3466     ScaleRegIdx = 2;
3467   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
3468     ScaleRegIdx = 1;
3469   else
3470     return false;
3471 
3472   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3473   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
3474   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
3475   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3476                        MachineBasicBlock::iterator End) {
3477     for (auto It = ++Start; It != End; It++)
3478       if (It->modifiesRegister(Reg, &getRegisterInfo()))
3479         return true;
3480     return false;
3481   };
3482 
3483   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3484   // treated as special zero when ScaleReg is R0/X0 register.
3485   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3486       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3487     return false;
3488 
3489   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3490   // and Imm Instr.
3491   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3492     return false;
3493 
3494   // Now start to do the transformation.
3495   LLVM_DEBUG(dbgs() << "Replace instruction: "
3496                     << "\n");
3497   LLVM_DEBUG(ADDIMI->dump());
3498   LLVM_DEBUG(ADDMI->dump());
3499   LLVM_DEBUG(MI.dump());
3500   LLVM_DEBUG(dbgs() << "with: "
3501                     << "\n");
3502 
3503   // Update ADDI instr.
3504   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
3505 
3506   // Update Imm instr.
3507   MI.setDesc(get(XFormOpcode));
3508   MI.getOperand(III.ImmOpNo)
3509       .ChangeToRegister(ScaleReg, false, false,
3510                         ADDMI->getOperand(ScaleRegIdx).isKill());
3511 
3512   MI.getOperand(III.OpNoForForwarding)
3513       .ChangeToRegister(ToBeChangedReg, false, false, true);
3514 
3515   // Eliminate ADD instr.
3516   ADDMI->eraseFromParent();
3517 
3518   LLVM_DEBUG(ADDIMI->dump());
3519   LLVM_DEBUG(MI.dump());
3520 
3521   return true;
3522 }
3523 
3524 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
3525                                                  int64_t &Imm) const {
3526   unsigned Opc = ADDIMI.getOpcode();
3527 
3528   // Exit if the instruction is not ADDI.
3529   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3530     return false;
3531 
3532   // The operand may not necessarily be an immediate - it could be a relocation.
3533   if (!ADDIMI.getOperand(2).isImm())
3534     return false;
3535 
3536   Imm = ADDIMI.getOperand(2).getImm();
3537 
3538   return true;
3539 }
3540 
3541 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
3542   unsigned Opc = ADDMI.getOpcode();
3543 
3544   // Exit if the instruction is not ADD.
3545   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3546 }
3547 
3548 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
3549                                                 unsigned &ToBeDeletedReg,
3550                                                 unsigned &XFormOpcode,
3551                                                 int64_t &OffsetImm,
3552                                                 ImmInstrInfo &III) const {
3553   // Only handle load/store.
3554   if (!MI.mayLoadOrStore())
3555     return false;
3556 
3557   unsigned Opc = MI.getOpcode();
3558 
3559   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
3560 
3561   // Exit if instruction has no index form.
3562   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3563     return false;
3564 
3565   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3566   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
3567                        III, true))
3568     return false;
3569 
3570   if (!III.IsSummingOperands)
3571     return false;
3572 
3573   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
3574   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
3575   // Only support imm operands, not relocation slots or others.
3576   if (!ImmOperand.isImm())
3577     return false;
3578 
3579   assert(RegOperand.isReg() && "Instruction format is not right");
3580 
3581   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3582   if (!RegOperand.isKill())
3583     return false;
3584 
3585   ToBeDeletedReg = RegOperand.getReg();
3586   OffsetImm = ImmOperand.getImm();
3587 
3588   return true;
3589 }
3590 
3591 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
3592                                          MachineInstr *&ADDIMI,
3593                                          int64_t &OffsetAddi,
3594                                          int64_t OffsetImm) const {
3595   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3596   MachineOperand &MO = ADDMI->getOperand(Index);
3597 
3598   if (!MO.isKill())
3599     return false;
3600 
3601   bool OtherIntermediateUse = false;
3602 
3603   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
3604   // Currently handle only one "add + Imminstr" pair case, exit if other
3605   // intermediate use for ToBeChangedReg found.
3606   // TODO: handle the cases where there are other "add + Imminstr" pairs
3607   // with same offset in Imminstr which is like:
3608   //
3609   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
3610   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3611   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
3612   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3613   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
3614   //
3615   // can be converted to:
3616   //
3617   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3618   //                                       (OffsetAddi + OffsetImm)
3619   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
3620   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
3621 
3622   if (OtherIntermediateUse || !ADDIMI)
3623     return false;
3624   // Check if ADDI instr meets requirement.
3625   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
3626     return false;
3627 
3628   if (isInt<16>(OffsetAddi + OffsetImm))
3629     return true;
3630   return false;
3631 }
3632 
3633 // If this instruction has an immediate form and one of its operands is a
3634 // result of a load-immediate or an add-immediate, convert it to
3635 // the immediate form if the constant is in range.
3636 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
3637                                           MachineInstr **KilledDef) const {
3638   MachineFunction *MF = MI.getParent()->getParent();
3639   MachineRegisterInfo *MRI = &MF->getRegInfo();
3640   bool PostRA = !MRI->isSSA();
3641   bool SeenIntermediateUse = true;
3642   unsigned ForwardingOperand = ~0U;
3643   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
3644                                            SeenIntermediateUse);
3645   if (!DefMI)
3646     return false;
3647   assert(ForwardingOperand < MI.getNumOperands() &&
3648          "The forwarding operand needs to be valid at this point");
3649   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
3650   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3651   if (KilledDef && KillFwdDefMI)
3652     *KilledDef = DefMI;
3653 
3654   // If this is a imm instruction and its register operands is produced by ADDI,
3655   // put the imm into imm inst directly.
3656   if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
3657           PPC::INSTRUCTION_LIST_END &&
3658       transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
3659     return true;
3660 
3661   ImmInstrInfo III;
3662   bool IsVFReg = MI.getOperand(0).isReg()
3663                      ? isVFRegister(MI.getOperand(0).getReg())
3664                      : false;
3665   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
3666   // If this is a reg+reg instruction that has a reg+imm form,
3667   // and one of the operands is produced by an add-immediate,
3668   // try to convert it.
3669   if (HasImmForm &&
3670       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
3671                                  KillFwdDefMI))
3672     return true;
3673 
3674   // If this is a reg+reg instruction that has a reg+imm form,
3675   // and one of the operands is produced by LI, convert it now.
3676   if (HasImmForm &&
3677       transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
3678     return true;
3679 
3680   // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3681   // can be simpified to LI.
3682   if (!HasImmForm && simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef))
3683     return true;
3684 
3685   return false;
3686 }
3687 
3688 bool PPCInstrInfo::combineRLWINM(MachineInstr &MI,
3689                                  MachineInstr **ToErase) const {
3690   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3691   unsigned FoldingReg = MI.getOperand(1).getReg();
3692   if (!Register::isVirtualRegister(FoldingReg))
3693     return false;
3694   MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg);
3695   if (SrcMI->getOpcode() != PPC::RLWINM &&
3696       SrcMI->getOpcode() != PPC::RLWINM_rec &&
3697       SrcMI->getOpcode() != PPC::RLWINM8 &&
3698       SrcMI->getOpcode() != PPC::RLWINM8_rec)
3699     return false;
3700   assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3701           MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3702           SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3703          "Invalid PPC::RLWINM Instruction!");
3704   uint64_t SHSrc = SrcMI->getOperand(2).getImm();
3705   uint64_t SHMI = MI.getOperand(2).getImm();
3706   uint64_t MBSrc = SrcMI->getOperand(3).getImm();
3707   uint64_t MBMI = MI.getOperand(3).getImm();
3708   uint64_t MESrc = SrcMI->getOperand(4).getImm();
3709   uint64_t MEMI = MI.getOperand(4).getImm();
3710 
3711   assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3712          "Invalid PPC::RLWINM Instruction!");
3713   // If MBMI is bigger than MEMI, we always can not get run of ones.
3714   // RotatedSrcMask non-wrap:
3715   //                 0........31|32........63
3716   // RotatedSrcMask:   B---E        B---E
3717   // MaskMI:         -----------|--E  B------
3718   // Result:           -----          ---      (Bad candidate)
3719   //
3720   // RotatedSrcMask wrap:
3721   //                 0........31|32........63
3722   // RotatedSrcMask: --E   B----|--E    B----
3723   // MaskMI:         -----------|--E  B------
3724   // Result:         ---   -----|---    -----  (Bad candidate)
3725   //
3726   // One special case is RotatedSrcMask is a full set mask.
3727   // RotatedSrcMask full:
3728   //                 0........31|32........63
3729   // RotatedSrcMask: ------EB---|-------EB---
3730   // MaskMI:         -----------|--E  B------
3731   // Result:         -----------|---  -------  (Good candidate)
3732 
3733   // Mark special case.
3734   bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3735 
3736   // For other MBMI > MEMI cases, just return.
3737   if ((MBMI > MEMI) && !SrcMaskFull)
3738     return false;
3739 
3740   // Handle MBMI <= MEMI cases.
3741   APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
3742   // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3743   // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3744   // while in PowerPC ISA, lowerest bit is at index 63.
3745   APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
3746 
3747   APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
3748   APInt FinalMask = RotatedSrcMask & MaskMI;
3749   uint32_t NewMB, NewME;
3750   bool Simplified = false;
3751 
3752   // If final mask is 0, MI result should be 0 too.
3753   if (FinalMask.isNullValue()) {
3754     bool Is64Bit =
3755         (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
3756     Simplified = true;
3757     LLVM_DEBUG(dbgs() << "Replace Instr: ");
3758     LLVM_DEBUG(MI.dump());
3759 
3760     if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3761       // Replace MI with "LI 0"
3762       MI.RemoveOperand(4);
3763       MI.RemoveOperand(3);
3764       MI.RemoveOperand(2);
3765       MI.getOperand(1).ChangeToImmediate(0);
3766       MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
3767     } else {
3768       // Replace MI with "ANDI_rec reg, 0"
3769       MI.RemoveOperand(4);
3770       MI.RemoveOperand(3);
3771       MI.getOperand(2).setImm(0);
3772       MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3773       MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3774       if (SrcMI->getOperand(1).isKill()) {
3775         MI.getOperand(1).setIsKill(true);
3776         SrcMI->getOperand(1).setIsKill(false);
3777       } else
3778         // About to replace MI.getOperand(1), clear its kill flag.
3779         MI.getOperand(1).setIsKill(false);
3780     }
3781 
3782     LLVM_DEBUG(dbgs() << "With: ");
3783     LLVM_DEBUG(MI.dump());
3784 
3785   } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
3786               NewMB <= NewME) ||
3787              SrcMaskFull) {
3788     // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3789     // than NewME. Otherwise we get a 64 bit value after folding, but MI
3790     // return a 32 bit value.
3791     Simplified = true;
3792     LLVM_DEBUG(dbgs() << "Converting Instr: ");
3793     LLVM_DEBUG(MI.dump());
3794 
3795     uint16_t NewSH = (SHSrc + SHMI) % 32;
3796     MI.getOperand(2).setImm(NewSH);
3797     // If SrcMI mask is full, no need to update MBMI and MEMI.
3798     if (!SrcMaskFull) {
3799       MI.getOperand(3).setImm(NewMB);
3800       MI.getOperand(4).setImm(NewME);
3801     }
3802     MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3803     if (SrcMI->getOperand(1).isKill()) {
3804       MI.getOperand(1).setIsKill(true);
3805       SrcMI->getOperand(1).setIsKill(false);
3806     } else
3807       // About to replace MI.getOperand(1), clear its kill flag.
3808       MI.getOperand(1).setIsKill(false);
3809 
3810     LLVM_DEBUG(dbgs() << "To: ");
3811     LLVM_DEBUG(MI.dump());
3812   }
3813   if (Simplified & MRI->use_nodbg_empty(FoldingReg) &&
3814       !SrcMI->hasImplicitDef()) {
3815     // If FoldingReg has no non-debug use and it has no implicit def (it
3816     // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
3817     // Otherwise keep it.
3818     *ToErase = SrcMI;
3819     LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
3820     LLVM_DEBUG(SrcMI->dump());
3821   }
3822   return Simplified;
3823 }
3824 
3825 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3826                                    ImmInstrInfo &III, bool PostRA) const {
3827   // The vast majority of the instructions would need their operand 2 replaced
3828   // with an immediate when switching to the reg+imm form. A marked exception
3829   // are the update form loads/stores for which a constant operand 2 would need
3830   // to turn into a displacement and move operand 1 to the operand 2 position.
3831   III.ImmOpNo = 2;
3832   III.OpNoForForwarding = 2;
3833   III.ImmWidth = 16;
3834   III.ImmMustBeMultipleOf = 1;
3835   III.TruncateImmTo = 0;
3836   III.IsSummingOperands = false;
3837   switch (Opc) {
3838   default: return false;
3839   case PPC::ADD4:
3840   case PPC::ADD8:
3841     III.SignedImm = true;
3842     III.ZeroIsSpecialOrig = 0;
3843     III.ZeroIsSpecialNew = 1;
3844     III.IsCommutative = true;
3845     III.IsSummingOperands = true;
3846     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3847     break;
3848   case PPC::ADDC:
3849   case PPC::ADDC8:
3850     III.SignedImm = true;
3851     III.ZeroIsSpecialOrig = 0;
3852     III.ZeroIsSpecialNew = 0;
3853     III.IsCommutative = true;
3854     III.IsSummingOperands = true;
3855     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3856     break;
3857   case PPC::ADDC_rec:
3858     III.SignedImm = true;
3859     III.ZeroIsSpecialOrig = 0;
3860     III.ZeroIsSpecialNew = 0;
3861     III.IsCommutative = true;
3862     III.IsSummingOperands = true;
3863     III.ImmOpcode = PPC::ADDIC_rec;
3864     break;
3865   case PPC::SUBFC:
3866   case PPC::SUBFC8:
3867     III.SignedImm = true;
3868     III.ZeroIsSpecialOrig = 0;
3869     III.ZeroIsSpecialNew = 0;
3870     III.IsCommutative = false;
3871     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3872     break;
3873   case PPC::CMPW:
3874   case PPC::CMPD:
3875     III.SignedImm = true;
3876     III.ZeroIsSpecialOrig = 0;
3877     III.ZeroIsSpecialNew = 0;
3878     III.IsCommutative = false;
3879     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3880     break;
3881   case PPC::CMPLW:
3882   case PPC::CMPLD:
3883     III.SignedImm = false;
3884     III.ZeroIsSpecialOrig = 0;
3885     III.ZeroIsSpecialNew = 0;
3886     III.IsCommutative = false;
3887     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3888     break;
3889   case PPC::AND_rec:
3890   case PPC::AND8_rec:
3891   case PPC::OR:
3892   case PPC::OR8:
3893   case PPC::XOR:
3894   case PPC::XOR8:
3895     III.SignedImm = false;
3896     III.ZeroIsSpecialOrig = 0;
3897     III.ZeroIsSpecialNew = 0;
3898     III.IsCommutative = true;
3899     switch(Opc) {
3900     default: llvm_unreachable("Unknown opcode");
3901     case PPC::AND_rec:
3902       III.ImmOpcode = PPC::ANDI_rec;
3903       break;
3904     case PPC::AND8_rec:
3905       III.ImmOpcode = PPC::ANDI8_rec;
3906       break;
3907     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3908     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3909     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3910     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3911     }
3912     break;
3913   case PPC::RLWNM:
3914   case PPC::RLWNM8:
3915   case PPC::RLWNM_rec:
3916   case PPC::RLWNM8_rec:
3917   case PPC::SLW:
3918   case PPC::SLW8:
3919   case PPC::SLW_rec:
3920   case PPC::SLW8_rec:
3921   case PPC::SRW:
3922   case PPC::SRW8:
3923   case PPC::SRW_rec:
3924   case PPC::SRW8_rec:
3925   case PPC::SRAW:
3926   case PPC::SRAW_rec:
3927     III.SignedImm = false;
3928     III.ZeroIsSpecialOrig = 0;
3929     III.ZeroIsSpecialNew = 0;
3930     III.IsCommutative = false;
3931     // This isn't actually true, but the instructions ignore any of the
3932     // upper bits, so any immediate loaded with an LI is acceptable.
3933     // This does not apply to shift right algebraic because a value
3934     // out of range will produce a -1/0.
3935     III.ImmWidth = 16;
3936     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3937         Opc == PPC::RLWNM8_rec)
3938       III.TruncateImmTo = 5;
3939     else
3940       III.TruncateImmTo = 6;
3941     switch(Opc) {
3942     default: llvm_unreachable("Unknown opcode");
3943     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3944     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3945     case PPC::RLWNM_rec:
3946       III.ImmOpcode = PPC::RLWINM_rec;
3947       break;
3948     case PPC::RLWNM8_rec:
3949       III.ImmOpcode = PPC::RLWINM8_rec;
3950       break;
3951     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3952     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3953     case PPC::SLW_rec:
3954       III.ImmOpcode = PPC::RLWINM_rec;
3955       break;
3956     case PPC::SLW8_rec:
3957       III.ImmOpcode = PPC::RLWINM8_rec;
3958       break;
3959     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3960     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3961     case PPC::SRW_rec:
3962       III.ImmOpcode = PPC::RLWINM_rec;
3963       break;
3964     case PPC::SRW8_rec:
3965       III.ImmOpcode = PPC::RLWINM8_rec;
3966       break;
3967     case PPC::SRAW:
3968       III.ImmWidth = 5;
3969       III.TruncateImmTo = 0;
3970       III.ImmOpcode = PPC::SRAWI;
3971       break;
3972     case PPC::SRAW_rec:
3973       III.ImmWidth = 5;
3974       III.TruncateImmTo = 0;
3975       III.ImmOpcode = PPC::SRAWI_rec;
3976       break;
3977     }
3978     break;
3979   case PPC::RLDCL:
3980   case PPC::RLDCL_rec:
3981   case PPC::RLDCR:
3982   case PPC::RLDCR_rec:
3983   case PPC::SLD:
3984   case PPC::SLD_rec:
3985   case PPC::SRD:
3986   case PPC::SRD_rec:
3987   case PPC::SRAD:
3988   case PPC::SRAD_rec:
3989     III.SignedImm = false;
3990     III.ZeroIsSpecialOrig = 0;
3991     III.ZeroIsSpecialNew = 0;
3992     III.IsCommutative = false;
3993     // This isn't actually true, but the instructions ignore any of the
3994     // upper bits, so any immediate loaded with an LI is acceptable.
3995     // This does not apply to shift right algebraic because a value
3996     // out of range will produce a -1/0.
3997     III.ImmWidth = 16;
3998     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3999         Opc == PPC::RLDCR_rec)
4000       III.TruncateImmTo = 6;
4001     else
4002       III.TruncateImmTo = 7;
4003     switch(Opc) {
4004     default: llvm_unreachable("Unknown opcode");
4005     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
4006     case PPC::RLDCL_rec:
4007       III.ImmOpcode = PPC::RLDICL_rec;
4008       break;
4009     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
4010     case PPC::RLDCR_rec:
4011       III.ImmOpcode = PPC::RLDICR_rec;
4012       break;
4013     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
4014     case PPC::SLD_rec:
4015       III.ImmOpcode = PPC::RLDICR_rec;
4016       break;
4017     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
4018     case PPC::SRD_rec:
4019       III.ImmOpcode = PPC::RLDICL_rec;
4020       break;
4021     case PPC::SRAD:
4022       III.ImmWidth = 6;
4023       III.TruncateImmTo = 0;
4024       III.ImmOpcode = PPC::SRADI;
4025        break;
4026     case PPC::SRAD_rec:
4027       III.ImmWidth = 6;
4028       III.TruncateImmTo = 0;
4029       III.ImmOpcode = PPC::SRADI_rec;
4030       break;
4031     }
4032     break;
4033   // Loads and stores:
4034   case PPC::LBZX:
4035   case PPC::LBZX8:
4036   case PPC::LHZX:
4037   case PPC::LHZX8:
4038   case PPC::LHAX:
4039   case PPC::LHAX8:
4040   case PPC::LWZX:
4041   case PPC::LWZX8:
4042   case PPC::LWAX:
4043   case PPC::LDX:
4044   case PPC::LFSX:
4045   case PPC::LFDX:
4046   case PPC::STBX:
4047   case PPC::STBX8:
4048   case PPC::STHX:
4049   case PPC::STHX8:
4050   case PPC::STWX:
4051   case PPC::STWX8:
4052   case PPC::STDX:
4053   case PPC::STFSX:
4054   case PPC::STFDX:
4055     III.SignedImm = true;
4056     III.ZeroIsSpecialOrig = 1;
4057     III.ZeroIsSpecialNew = 2;
4058     III.IsCommutative = true;
4059     III.IsSummingOperands = true;
4060     III.ImmOpNo = 1;
4061     III.OpNoForForwarding = 2;
4062     switch(Opc) {
4063     default: llvm_unreachable("Unknown opcode");
4064     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
4065     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
4066     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
4067     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
4068     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
4069     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
4070     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
4071     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
4072     case PPC::LWAX:
4073       III.ImmOpcode = PPC::LWA;
4074       III.ImmMustBeMultipleOf = 4;
4075       break;
4076     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
4077     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
4078     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
4079     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
4080     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
4081     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
4082     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
4083     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
4084     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
4085     case PPC::STDX:
4086       III.ImmOpcode = PPC::STD;
4087       III.ImmMustBeMultipleOf = 4;
4088       break;
4089     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
4090     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
4091     }
4092     break;
4093   case PPC::LBZUX:
4094   case PPC::LBZUX8:
4095   case PPC::LHZUX:
4096   case PPC::LHZUX8:
4097   case PPC::LHAUX:
4098   case PPC::LHAUX8:
4099   case PPC::LWZUX:
4100   case PPC::LWZUX8:
4101   case PPC::LDUX:
4102   case PPC::LFSUX:
4103   case PPC::LFDUX:
4104   case PPC::STBUX:
4105   case PPC::STBUX8:
4106   case PPC::STHUX:
4107   case PPC::STHUX8:
4108   case PPC::STWUX:
4109   case PPC::STWUX8:
4110   case PPC::STDUX:
4111   case PPC::STFSUX:
4112   case PPC::STFDUX:
4113     III.SignedImm = true;
4114     III.ZeroIsSpecialOrig = 2;
4115     III.ZeroIsSpecialNew = 3;
4116     III.IsCommutative = false;
4117     III.IsSummingOperands = true;
4118     III.ImmOpNo = 2;
4119     III.OpNoForForwarding = 3;
4120     switch(Opc) {
4121     default: llvm_unreachable("Unknown opcode");
4122     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
4123     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
4124     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
4125     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
4126     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
4127     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
4128     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
4129     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
4130     case PPC::LDUX:
4131       III.ImmOpcode = PPC::LDU;
4132       III.ImmMustBeMultipleOf = 4;
4133       break;
4134     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
4135     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
4136     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
4137     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
4138     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
4139     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
4140     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
4141     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
4142     case PPC::STDUX:
4143       III.ImmOpcode = PPC::STDU;
4144       III.ImmMustBeMultipleOf = 4;
4145       break;
4146     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
4147     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
4148     }
4149     break;
4150   // Power9 and up only. For some of these, the X-Form version has access to all
4151   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
4152   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
4153   // into or stored from is one of the VR registers.
4154   case PPC::LXVX:
4155   case PPC::LXSSPX:
4156   case PPC::LXSDX:
4157   case PPC::STXVX:
4158   case PPC::STXSSPX:
4159   case PPC::STXSDX:
4160   case PPC::XFLOADf32:
4161   case PPC::XFLOADf64:
4162   case PPC::XFSTOREf32:
4163   case PPC::XFSTOREf64:
4164     if (!Subtarget.hasP9Vector())
4165       return false;
4166     III.SignedImm = true;
4167     III.ZeroIsSpecialOrig = 1;
4168     III.ZeroIsSpecialNew = 2;
4169     III.IsCommutative = true;
4170     III.IsSummingOperands = true;
4171     III.ImmOpNo = 1;
4172     III.OpNoForForwarding = 2;
4173     III.ImmMustBeMultipleOf = 4;
4174     switch(Opc) {
4175     default: llvm_unreachable("Unknown opcode");
4176     case PPC::LXVX:
4177       III.ImmOpcode = PPC::LXV;
4178       III.ImmMustBeMultipleOf = 16;
4179       break;
4180     case PPC::LXSSPX:
4181       if (PostRA) {
4182         if (IsVFReg)
4183           III.ImmOpcode = PPC::LXSSP;
4184         else {
4185           III.ImmOpcode = PPC::LFS;
4186           III.ImmMustBeMultipleOf = 1;
4187         }
4188         break;
4189       }
4190       LLVM_FALLTHROUGH;
4191     case PPC::XFLOADf32:
4192       III.ImmOpcode = PPC::DFLOADf32;
4193       break;
4194     case PPC::LXSDX:
4195       if (PostRA) {
4196         if (IsVFReg)
4197           III.ImmOpcode = PPC::LXSD;
4198         else {
4199           III.ImmOpcode = PPC::LFD;
4200           III.ImmMustBeMultipleOf = 1;
4201         }
4202         break;
4203       }
4204       LLVM_FALLTHROUGH;
4205     case PPC::XFLOADf64:
4206       III.ImmOpcode = PPC::DFLOADf64;
4207       break;
4208     case PPC::STXVX:
4209       III.ImmOpcode = PPC::STXV;
4210       III.ImmMustBeMultipleOf = 16;
4211       break;
4212     case PPC::STXSSPX:
4213       if (PostRA) {
4214         if (IsVFReg)
4215           III.ImmOpcode = PPC::STXSSP;
4216         else {
4217           III.ImmOpcode = PPC::STFS;
4218           III.ImmMustBeMultipleOf = 1;
4219         }
4220         break;
4221       }
4222       LLVM_FALLTHROUGH;
4223     case PPC::XFSTOREf32:
4224       III.ImmOpcode = PPC::DFSTOREf32;
4225       break;
4226     case PPC::STXSDX:
4227       if (PostRA) {
4228         if (IsVFReg)
4229           III.ImmOpcode = PPC::STXSD;
4230         else {
4231           III.ImmOpcode = PPC::STFD;
4232           III.ImmMustBeMultipleOf = 1;
4233         }
4234         break;
4235       }
4236       LLVM_FALLTHROUGH;
4237     case PPC::XFSTOREf64:
4238       III.ImmOpcode = PPC::DFSTOREf64;
4239       break;
4240     }
4241     break;
4242   }
4243   return true;
4244 }
4245 
4246 // Utility function for swaping two arbitrary operands of an instruction.
4247 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
4248   assert(Op1 != Op2 && "Cannot swap operand with itself.");
4249 
4250   unsigned MaxOp = std::max(Op1, Op2);
4251   unsigned MinOp = std::min(Op1, Op2);
4252   MachineOperand MOp1 = MI.getOperand(MinOp);
4253   MachineOperand MOp2 = MI.getOperand(MaxOp);
4254   MI.RemoveOperand(std::max(Op1, Op2));
4255   MI.RemoveOperand(std::min(Op1, Op2));
4256 
4257   // If the operands we are swapping are the two at the end (the common case)
4258   // we can just remove both and add them in the opposite order.
4259   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
4260     MI.addOperand(MOp2);
4261     MI.addOperand(MOp1);
4262   } else {
4263     // Store all operands in a temporary vector, remove them and re-add in the
4264     // right order.
4265     SmallVector<MachineOperand, 2> MOps;
4266     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
4267     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
4268       MOps.push_back(MI.getOperand(i));
4269       MI.RemoveOperand(i);
4270     }
4271     // MOp2 needs to be added next.
4272     MI.addOperand(MOp2);
4273     // Now add the rest.
4274     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
4275       if (i == MaxOp)
4276         MI.addOperand(MOp1);
4277       else {
4278         MI.addOperand(MOps.back());
4279         MOps.pop_back();
4280       }
4281     }
4282   }
4283 }
4284 
4285 // Check if the 'MI' that has the index OpNoForForwarding
4286 // meets the requirement described in the ImmInstrInfo.
4287 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
4288                                                const ImmInstrInfo &III,
4289                                                unsigned OpNoForForwarding
4290                                                ) const {
4291   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
4292   // would not work pre-RA, we can only do the check post RA.
4293   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4294   if (MRI.isSSA())
4295     return false;
4296 
4297   // Cannot do the transform if MI isn't summing the operands.
4298   if (!III.IsSummingOperands)
4299     return false;
4300 
4301   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
4302   if (!III.ZeroIsSpecialOrig)
4303     return false;
4304 
4305   // We cannot do the transform if the operand we are trying to replace
4306   // isn't the same as the operand the instruction allows.
4307   if (OpNoForForwarding != III.OpNoForForwarding)
4308     return false;
4309 
4310   // Check if the instruction we are trying to transform really has
4311   // the special zero register as its operand.
4312   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
4313       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
4314     return false;
4315 
4316   // This machine instruction is convertible if it is,
4317   // 1. summing the operands.
4318   // 2. one of the operands is special zero register.
4319   // 3. the operand we are trying to replace is allowed by the MI.
4320   return true;
4321 }
4322 
4323 // Check if the DefMI is the add inst and set the ImmMO and RegMO
4324 // accordingly.
4325 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
4326                                                const ImmInstrInfo &III,
4327                                                MachineOperand *&ImmMO,
4328                                                MachineOperand *&RegMO) const {
4329   unsigned Opc = DefMI.getOpcode();
4330   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
4331     return false;
4332 
4333   assert(DefMI.getNumOperands() >= 3 &&
4334          "Add inst must have at least three operands");
4335   RegMO = &DefMI.getOperand(1);
4336   ImmMO = &DefMI.getOperand(2);
4337 
4338   // Before RA, ADDI first operand could be a frame index.
4339   if (!RegMO->isReg())
4340     return false;
4341 
4342   // This DefMI is elgible for forwarding if it is:
4343   // 1. add inst
4344   // 2. one of the operands is Imm/CPI/Global.
4345   return isAnImmediateOperand(*ImmMO);
4346 }
4347 
4348 bool PPCInstrInfo::isRegElgibleForForwarding(
4349     const MachineOperand &RegMO, const MachineInstr &DefMI,
4350     const MachineInstr &MI, bool KillDefMI,
4351     bool &IsFwdFeederRegKilled) const {
4352   // x = addi y, imm
4353   // ...
4354   // z = lfdx 0, x   -> z = lfd imm(y)
4355   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
4356   // of "y" between the DEF of "x" and "z".
4357   // The query is only valid post RA.
4358   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4359   if (MRI.isSSA())
4360     return false;
4361 
4362   Register Reg = RegMO.getReg();
4363 
4364   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
4365   MachineBasicBlock::const_reverse_iterator It = MI;
4366   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
4367   It++;
4368   for (; It != E; ++It) {
4369     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4370       return false;
4371     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4372       IsFwdFeederRegKilled = true;
4373     // Made it to DefMI without encountering a clobber.
4374     if ((&*It) == &DefMI)
4375       break;
4376   }
4377   assert((&*It) == &DefMI && "DefMI is missing");
4378 
4379   // If DefMI also defines the register to be forwarded, we can only forward it
4380   // if DefMI is being erased.
4381   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
4382     return KillDefMI;
4383 
4384   return true;
4385 }
4386 
4387 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
4388                                              const MachineInstr &DefMI,
4389                                              const ImmInstrInfo &III,
4390                                              int64_t &Imm,
4391                                              int64_t BaseImm) const {
4392   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
4393   if (DefMI.getOpcode() == PPC::ADDItocL) {
4394     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
4395     // However, we know that, it is 16-bit width, and has the alignment of 4.
4396     // Check if the instruction met the requirement.
4397     if (III.ImmMustBeMultipleOf > 4 ||
4398        III.TruncateImmTo || III.ImmWidth != 16)
4399       return false;
4400 
4401     // Going from XForm to DForm loads means that the displacement needs to be
4402     // not just an immediate but also a multiple of 4, or 16 depending on the
4403     // load. A DForm load cannot be represented if it is a multiple of say 2.
4404     // XForm loads do not have this restriction.
4405     if (ImmMO.isGlobal()) {
4406       const DataLayout &DL = ImmMO.getGlobal()->getParent()->getDataLayout();
4407       if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf)
4408         return false;
4409     }
4410 
4411     return true;
4412   }
4413 
4414   if (ImmMO.isImm()) {
4415     // It is Imm, we need to check if the Imm fit the range.
4416     // Sign-extend to 64-bits.
4417     // DefMI may be folded with another imm form instruction, the result Imm is
4418     // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
4419     APInt ActualValue(64, ImmMO.getImm() + BaseImm, true);
4420     if (III.SignedImm && !ActualValue.isSignedIntN(III.ImmWidth))
4421       return false;
4422     if (!III.SignedImm && !ActualValue.isIntN(III.ImmWidth))
4423       return false;
4424     Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
4425 
4426     if (Imm % III.ImmMustBeMultipleOf)
4427       return false;
4428     if (III.TruncateImmTo)
4429       Imm &= ((1 << III.TruncateImmTo) - 1);
4430   }
4431   else
4432     return false;
4433 
4434   // This ImmMO is forwarded if it meets the requriement describle
4435   // in ImmInstrInfo
4436   return true;
4437 }
4438 
4439 bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4440                                 unsigned OpNoForForwarding,
4441                                 MachineInstr **KilledDef) const {
4442   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4443       !DefMI.getOperand(1).isImm())
4444     return false;
4445 
4446   MachineFunction *MF = MI.getParent()->getParent();
4447   MachineRegisterInfo *MRI = &MF->getRegInfo();
4448   bool PostRA = !MRI->isSSA();
4449 
4450   int64_t Immediate = DefMI.getOperand(1).getImm();
4451   // Sign-extend to 64-bits.
4452   int64_t SExtImm = SignExtend64<16>(Immediate);
4453 
4454   bool IsForwardingOperandKilled = MI.getOperand(OpNoForForwarding).isKill();
4455   Register ForwardingOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4456 
4457   bool ReplaceWithLI = false;
4458   bool Is64BitLI = false;
4459   int64_t NewImm = 0;
4460   bool SetCR = false;
4461   unsigned Opc = MI.getOpcode();
4462   switch (Opc) {
4463   default:
4464     return false;
4465 
4466   // FIXME: Any branches conditional on such a comparison can be made
4467   // unconditional. At this time, this happens too infrequently to be worth
4468   // the implementation effort, but if that ever changes, we could convert
4469   // such a pattern here.
4470   case PPC::CMPWI:
4471   case PPC::CMPLWI:
4472   case PPC::CMPDI:
4473   case PPC::CMPLDI: {
4474     // Doing this post-RA would require dataflow analysis to reliably find uses
4475     // of the CR register set by the compare.
4476     // No need to fixup killed/dead flag since this transformation is only valid
4477     // before RA.
4478     if (PostRA)
4479       return false;
4480     // If a compare-immediate is fed by an immediate and is itself an input of
4481     // an ISEL (the most common case) into a COPY of the correct register.
4482     bool Changed = false;
4483     Register DefReg = MI.getOperand(0).getReg();
4484     int64_t Comparand = MI.getOperand(2).getImm();
4485     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4486                                 ? (Comparand | 0xFFFFFFFFFFFF0000)
4487                                 : Comparand;
4488 
4489     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
4490       unsigned UseOpc = CompareUseMI.getOpcode();
4491       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4492         continue;
4493       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
4494       Register TrueReg = CompareUseMI.getOperand(1).getReg();
4495       Register FalseReg = CompareUseMI.getOperand(2).getReg();
4496       unsigned RegToCopy =
4497           selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
4498       if (RegToCopy == PPC::NoRegister)
4499         continue;
4500       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4501       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4502         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4503         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
4504         CompareUseMI.RemoveOperand(3);
4505         CompareUseMI.RemoveOperand(2);
4506         continue;
4507       }
4508       LLVM_DEBUG(
4509           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4510       LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4511       LLVM_DEBUG(dbgs() << "Is converted to:\n");
4512       // Convert to copy and remove unneeded operands.
4513       CompareUseMI.setDesc(get(PPC::COPY));
4514       CompareUseMI.RemoveOperand(3);
4515       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
4516       CmpIselsConverted++;
4517       Changed = true;
4518       LLVM_DEBUG(CompareUseMI.dump());
4519     }
4520     if (Changed)
4521       return true;
4522     // This may end up incremented multiple times since this function is called
4523     // during a fixed-point transformation, but it is only meant to indicate the
4524     // presence of this opportunity.
4525     MissedConvertibleImmediateInstrs++;
4526     return false;
4527   }
4528 
4529   // Immediate forms - may simply be convertable to an LI.
4530   case PPC::ADDI:
4531   case PPC::ADDI8: {
4532     // Does the sum fit in a 16-bit signed field?
4533     int64_t Addend = MI.getOperand(2).getImm();
4534     if (isInt<16>(Addend + SExtImm)) {
4535       ReplaceWithLI = true;
4536       Is64BitLI = Opc == PPC::ADDI8;
4537       NewImm = Addend + SExtImm;
4538       break;
4539     }
4540     return false;
4541   }
4542   case PPC::SUBFIC:
4543   case PPC::SUBFIC8: {
4544     // Only transform this if the CARRY implicit operand is dead.
4545     if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
4546       return false;
4547     int64_t Minuend = MI.getOperand(2).getImm();
4548     if (isInt<16>(Minuend - SExtImm)) {
4549       ReplaceWithLI = true;
4550       Is64BitLI = Opc == PPC::SUBFIC8;
4551       NewImm = Minuend - SExtImm;
4552       break;
4553     }
4554     return false;
4555   }
4556   case PPC::RLDICL:
4557   case PPC::RLDICL_rec:
4558   case PPC::RLDICL_32:
4559   case PPC::RLDICL_32_64: {
4560     // Use APInt's rotate function.
4561     int64_t SH = MI.getOperand(2).getImm();
4562     int64_t MB = MI.getOperand(3).getImm();
4563     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4564                 SExtImm, true);
4565     InVal = InVal.rotl(SH);
4566     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4567     InVal &= Mask;
4568     // Can't replace negative values with an LI as that will sign-extend
4569     // and not clear the left bits. If we're setting the CR bit, we will use
4570     // ANDI_rec which won't sign extend, so that's safe.
4571     if (isUInt<15>(InVal.getSExtValue()) ||
4572         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
4573       ReplaceWithLI = true;
4574       Is64BitLI = Opc != PPC::RLDICL_32;
4575       NewImm = InVal.getSExtValue();
4576       SetCR = Opc == PPC::RLDICL_rec;
4577       break;
4578     }
4579     return false;
4580   }
4581   case PPC::RLWINM:
4582   case PPC::RLWINM8:
4583   case PPC::RLWINM_rec:
4584   case PPC::RLWINM8_rec: {
4585     int64_t SH = MI.getOperand(2).getImm();
4586     int64_t MB = MI.getOperand(3).getImm();
4587     int64_t ME = MI.getOperand(4).getImm();
4588     APInt InVal(32, SExtImm, true);
4589     InVal = InVal.rotl(SH);
4590     APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
4591     InVal &= Mask;
4592     // Can't replace negative values with an LI as that will sign-extend
4593     // and not clear the left bits. If we're setting the CR bit, we will use
4594     // ANDI_rec which won't sign extend, so that's safe.
4595     bool ValueFits = isUInt<15>(InVal.getSExtValue());
4596     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4597                   isUInt<16>(InVal.getSExtValue()));
4598     if (ValueFits) {
4599       ReplaceWithLI = true;
4600       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4601       NewImm = InVal.getSExtValue();
4602       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4603       break;
4604     }
4605     return false;
4606   }
4607   case PPC::ORI:
4608   case PPC::ORI8:
4609   case PPC::XORI:
4610   case PPC::XORI8: {
4611     int64_t LogicalImm = MI.getOperand(2).getImm();
4612     int64_t Result = 0;
4613     if (Opc == PPC::ORI || Opc == PPC::ORI8)
4614       Result = LogicalImm | SExtImm;
4615     else
4616       Result = LogicalImm ^ SExtImm;
4617     if (isInt<16>(Result)) {
4618       ReplaceWithLI = true;
4619       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4620       NewImm = Result;
4621       break;
4622     }
4623     return false;
4624   }
4625   }
4626 
4627   if (ReplaceWithLI) {
4628     // We need to be careful with CR-setting instructions we're replacing.
4629     if (SetCR) {
4630       // We don't know anything about uses when we're out of SSA, so only
4631       // replace if the new immediate will be reproduced.
4632       bool ImmChanged = (SExtImm & NewImm) != NewImm;
4633       if (PostRA && ImmChanged)
4634         return false;
4635 
4636       if (!PostRA) {
4637         // If the defining load-immediate has no other uses, we can just replace
4638         // the immediate with the new immediate.
4639         if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
4640           DefMI.getOperand(1).setImm(NewImm);
4641 
4642         // If we're not using the GPR result of the CR-setting instruction, we
4643         // just need to and with zero/non-zero depending on the new immediate.
4644         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
4645           if (NewImm) {
4646             assert(Immediate && "Transformation converted zero to non-zero?");
4647             NewImm = Immediate;
4648           }
4649         } else if (ImmChanged)
4650           return false;
4651       }
4652     }
4653 
4654     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4655     LLVM_DEBUG(MI.dump());
4656     LLVM_DEBUG(dbgs() << "Fed by:\n");
4657     LLVM_DEBUG(DefMI.dump());
4658     LoadImmediateInfo LII;
4659     LII.Imm = NewImm;
4660     LII.Is64Bit = Is64BitLI;
4661     LII.SetCR = SetCR;
4662     // If we're setting the CR, the original load-immediate must be kept (as an
4663     // operand to ANDI_rec/ANDI8_rec).
4664     if (KilledDef && SetCR)
4665       *KilledDef = nullptr;
4666     replaceInstrWithLI(MI, LII);
4667 
4668     // Fixup killed/dead flag after transformation.
4669     // Pattern:
4670     // ForwardingOperandReg = LI imm1
4671     // y = op2 imm2, ForwardingOperandReg(killed)
4672     if (IsForwardingOperandKilled)
4673       fixupIsDeadOrKill(&DefMI, &MI, ForwardingOperandReg);
4674 
4675     LLVM_DEBUG(dbgs() << "With:\n");
4676     LLVM_DEBUG(MI.dump());
4677     return true;
4678   }
4679   return false;
4680 }
4681 
4682 bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4683     MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4684   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4685   bool PostRA = !MRI->isSSA();
4686   // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4687   // for post-ra.
4688   if (PostRA)
4689     return false;
4690 
4691   // Only handle load/store.
4692   if (!MI.mayLoadOrStore())
4693     return false;
4694 
4695   unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
4696 
4697   assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4698          "MI must have x-form opcode");
4699 
4700   // get Imm Form info.
4701   ImmInstrInfo III;
4702   bool IsVFReg = MI.getOperand(0).isReg()
4703                      ? isVFRegister(MI.getOperand(0).getReg())
4704                      : false;
4705 
4706   if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
4707     return false;
4708 
4709   if (!III.IsSummingOperands)
4710     return false;
4711 
4712   if (OpNoForForwarding != III.OpNoForForwarding)
4713     return false;
4714 
4715   MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
4716   if (!ImmOperandMI.isImm())
4717     return false;
4718 
4719   // Check DefMI.
4720   MachineOperand *ImmMO = nullptr;
4721   MachineOperand *RegMO = nullptr;
4722   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4723     return false;
4724   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4725 
4726   // Check Imm.
4727   // Set ImmBase from imm instruction as base and get new Imm inside
4728   // isImmElgibleForForwarding.
4729   int64_t ImmBase = ImmOperandMI.getImm();
4730   int64_t Imm = 0;
4731   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
4732     return false;
4733 
4734   // Get killed info in case fixup needed after transformation.
4735   unsigned ForwardKilledOperandReg = ~0U;
4736   if (MI.getOperand(III.OpNoForForwarding).isKill())
4737     ForwardKilledOperandReg = MI.getOperand(III.OpNoForForwarding).getReg();
4738 
4739   // Do the transform
4740   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4741   LLVM_DEBUG(MI.dump());
4742   LLVM_DEBUG(dbgs() << "Fed by:\n");
4743   LLVM_DEBUG(DefMI.dump());
4744 
4745   MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
4746   MI.getOperand(III.OpNoForForwarding).setIsKill(RegMO->isKill());
4747   MI.getOperand(III.ImmOpNo).setImm(Imm);
4748 
4749   // FIXME: fix kill/dead flag if MI and DefMI are not in same basic block.
4750   if (DefMI.getParent() == MI.getParent()) {
4751     // Check if reg is killed between MI and DefMI.
4752     auto IsKilledFor = [&](unsigned Reg) {
4753       MachineBasicBlock::const_reverse_iterator It = MI;
4754       MachineBasicBlock::const_reverse_iterator E = DefMI;
4755       It++;
4756       for (; It != E; ++It) {
4757         if (It->killsRegister(Reg))
4758           return true;
4759       }
4760       return false;
4761     };
4762 
4763     // Update kill flag
4764     if (RegMO->isKill() || IsKilledFor(RegMO->getReg()))
4765       fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4766     if (ForwardKilledOperandReg != ~0U)
4767       fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4768   }
4769 
4770   LLVM_DEBUG(dbgs() << "With:\n");
4771   LLVM_DEBUG(MI.dump());
4772   return true;
4773 }
4774 
4775 // If an X-Form instruction is fed by an add-immediate and one of its operands
4776 // is the literal zero, attempt to forward the source of the add-immediate to
4777 // the corresponding D-Form instruction with the displacement coming from
4778 // the immediate being added.
4779 bool PPCInstrInfo::transformToImmFormFedByAdd(
4780     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4781     MachineInstr &DefMI, bool KillDefMI) const {
4782   //         RegMO ImmMO
4783   //           |    |
4784   // x = addi reg, imm  <----- DefMI
4785   // y = op    0 ,  x   <----- MI
4786   //                |
4787   //         OpNoForForwarding
4788   // Check if the MI meet the requirement described in the III.
4789   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4790     return false;
4791 
4792   // Check if the DefMI meet the requirement
4793   // described in the III. If yes, set the ImmMO and RegMO accordingly.
4794   MachineOperand *ImmMO = nullptr;
4795   MachineOperand *RegMO = nullptr;
4796   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4797     return false;
4798   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4799 
4800   // As we get the Imm operand now, we need to check if the ImmMO meet
4801   // the requirement described in the III. If yes set the Imm.
4802   int64_t Imm = 0;
4803   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
4804     return false;
4805 
4806   bool IsFwdFeederRegKilled = false;
4807   // Check if the RegMO can be forwarded to MI.
4808   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
4809                                  IsFwdFeederRegKilled))
4810     return false;
4811 
4812   // Get killed info in case fixup needed after transformation.
4813   unsigned ForwardKilledOperandReg = ~0U;
4814   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4815   bool PostRA = !MRI.isSSA();
4816   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
4817     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4818 
4819   // We know that, the MI and DefMI both meet the pattern, and
4820   // the Imm also meet the requirement with the new Imm-form.
4821   // It is safe to do the transformation now.
4822   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4823   LLVM_DEBUG(MI.dump());
4824   LLVM_DEBUG(dbgs() << "Fed by:\n");
4825   LLVM_DEBUG(DefMI.dump());
4826 
4827   // Update the base reg first.
4828   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
4829                                                         false, false,
4830                                                         RegMO->isKill());
4831 
4832   // Then, update the imm.
4833   if (ImmMO->isImm()) {
4834     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
4835     // directly.
4836     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
4837   }
4838   else {
4839     // Otherwise, it is Constant Pool Index(CPI) or Global,
4840     // which is relocation in fact. We need to replace the special zero
4841     // register with ImmMO.
4842     // Before that, we need to fixup the target flags for imm.
4843     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
4844     if (DefMI.getOpcode() == PPC::ADDItocL)
4845       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
4846 
4847     // MI didn't have the interface such as MI.setOperand(i) though
4848     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
4849     // ImmMO, we need to remove ZERO operand and all the operands behind it,
4850     // and, add the ImmMO, then, move back all the operands behind ZERO.
4851     SmallVector<MachineOperand, 2> MOps;
4852     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
4853       MOps.push_back(MI.getOperand(i));
4854       MI.RemoveOperand(i);
4855     }
4856 
4857     // Remove the last MO in the list, which is ZERO operand in fact.
4858     MOps.pop_back();
4859     // Add the imm operand.
4860     MI.addOperand(*ImmMO);
4861     // Now add the rest back.
4862     for (auto &MO : MOps)
4863       MI.addOperand(MO);
4864   }
4865 
4866   // Update the opcode.
4867   MI.setDesc(get(III.ImmOpcode));
4868 
4869   // Fix up killed/dead flag after transformation.
4870   // Pattern 1:
4871   // x = ADD KilledFwdFeederReg, imm
4872   // n = opn KilledFwdFeederReg(killed), regn
4873   // y = XOP 0, x
4874   // Pattern 2:
4875   // x = ADD reg(killed), imm
4876   // y = XOP 0, x
4877   if (IsFwdFeederRegKilled || RegMO->isKill())
4878     fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4879   // Pattern 3:
4880   // ForwardKilledOperandReg = ADD reg, imm
4881   // y = XOP 0, ForwardKilledOperandReg(killed)
4882   if (ForwardKilledOperandReg != ~0U)
4883     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4884 
4885   LLVM_DEBUG(dbgs() << "With:\n");
4886   LLVM_DEBUG(MI.dump());
4887 
4888   return true;
4889 }
4890 
4891 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
4892                                              const ImmInstrInfo &III,
4893                                              unsigned ConstantOpNo,
4894                                              MachineInstr &DefMI) const {
4895   // DefMI must be LI or LI8.
4896   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4897       !DefMI.getOperand(1).isImm())
4898     return false;
4899 
4900   // Get Imm operand and Sign-extend to 64-bits.
4901   int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
4902 
4903   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4904   bool PostRA = !MRI.isSSA();
4905   // Exit early if we can't convert this.
4906   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
4907     return false;
4908   if (Imm % III.ImmMustBeMultipleOf)
4909     return false;
4910   if (III.TruncateImmTo)
4911     Imm &= ((1 << III.TruncateImmTo) - 1);
4912   if (III.SignedImm) {
4913     APInt ActualValue(64, Imm, true);
4914     if (!ActualValue.isSignedIntN(III.ImmWidth))
4915       return false;
4916   } else {
4917     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
4918     if ((uint64_t)Imm > UnsignedMax)
4919       return false;
4920   }
4921 
4922   // If we're post-RA, the instructions don't agree on whether register zero is
4923   // special, we can transform this as long as the register operand that will
4924   // end up in the location where zero is special isn't R0.
4925   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
4926     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
4927       III.ZeroIsSpecialNew + 1;
4928     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
4929     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
4930     // If R0 is in the operand where zero is special for the new instruction,
4931     // it is unsafe to transform if the constant operand isn't that operand.
4932     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
4933         ConstantOpNo != III.ZeroIsSpecialNew)
4934       return false;
4935     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
4936         ConstantOpNo != PosForOrigZero)
4937       return false;
4938   }
4939 
4940   // Get killed info in case fixup needed after transformation.
4941   unsigned ForwardKilledOperandReg = ~0U;
4942   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
4943     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
4944 
4945   unsigned Opc = MI.getOpcode();
4946   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
4947                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
4948                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
4949                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
4950   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
4951                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
4952   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
4953                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
4954   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
4955                     Opc == PPC::SRD_rec;
4956 
4957   MI.setDesc(get(III.ImmOpcode));
4958   if (ConstantOpNo == III.OpNoForForwarding) {
4959     // Converting shifts to immediate form is a bit tricky since they may do
4960     // one of three things:
4961     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
4962     // 2. If the shift amount is zero, the result is unchanged (save for maybe
4963     //    setting CR0)
4964     // 3. If the shift amount is in [1, OpSize), it's just a shift
4965     if (SpecialShift32 || SpecialShift64) {
4966       LoadImmediateInfo LII;
4967       LII.Imm = 0;
4968       LII.SetCR = SetCR;
4969       LII.Is64Bit = SpecialShift64;
4970       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
4971       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
4972         replaceInstrWithLI(MI, LII);
4973       // Shifts by zero don't change the value. If we don't need to set CR0,
4974       // just convert this to a COPY. Can't do this post-RA since we've already
4975       // cleaned up the copies.
4976       else if (!SetCR && ShAmt == 0 && !PostRA) {
4977         MI.RemoveOperand(2);
4978         MI.setDesc(get(PPC::COPY));
4979       } else {
4980         // The 32 bit and 64 bit instructions are quite different.
4981         if (SpecialShift32) {
4982           // Left shifts use (N, 0, 31-N).
4983           // Right shifts use (32-N, N, 31) if 0 < N < 32.
4984           //              use (0, 0, 31)    if N == 0.
4985           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
4986           uint64_t MB = RightShift ? ShAmt : 0;
4987           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
4988           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4989           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
4990             .addImm(ME);
4991         } else {
4992           // Left shifts use (N, 63-N).
4993           // Right shifts use (64-N, N) if 0 < N < 64.
4994           //              use (0, 0)    if N == 0.
4995           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
4996           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
4997           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4998           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
4999         }
5000       }
5001     } else
5002       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5003   }
5004   // Convert commutative instructions (switch the operands and convert the
5005   // desired one to an immediate.
5006   else if (III.IsCommutative) {
5007     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5008     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
5009   } else
5010     llvm_unreachable("Should have exited early!");
5011 
5012   // For instructions for which the constant register replaces a different
5013   // operand than where the immediate goes, we need to swap them.
5014   if (III.OpNoForForwarding != III.ImmOpNo)
5015     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
5016 
5017   // If the special R0/X0 register index are different for original instruction
5018   // and new instruction, we need to fix up the register class in new
5019   // instruction.
5020   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5021     if (III.ZeroIsSpecialNew) {
5022       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
5023       // need to fix up register class.
5024       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
5025       if (Register::isVirtualRegister(RegToModify)) {
5026         const TargetRegisterClass *NewRC =
5027           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
5028           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
5029         MRI.setRegClass(RegToModify, NewRC);
5030       }
5031     }
5032   }
5033 
5034   // Fix up killed/dead flag after transformation.
5035   // Pattern:
5036   // ForwardKilledOperandReg = LI imm
5037   // y = XOP reg, ForwardKilledOperandReg(killed)
5038   if (ForwardKilledOperandReg != ~0U)
5039     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
5040   return true;
5041 }
5042 
5043 const TargetRegisterClass *
5044 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
5045   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
5046     return &PPC::VSRCRegClass;
5047   return RC;
5048 }
5049 
5050 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
5051   return PPC::getRecordFormOpcode(Opcode);
5052 }
5053 
5054 // This function returns true if the machine instruction
5055 // always outputs a value by sign-extending a 32 bit value,
5056 // i.e. 0 to 31-th bits are same as 32-th bit.
5057 static bool isSignExtendingOp(const MachineInstr &MI) {
5058   int Opcode = MI.getOpcode();
5059   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
5060       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
5061       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
5062       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
5063       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
5064       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
5065       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
5066       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
5067       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
5068       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
5069       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
5070       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
5071       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
5072       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
5073       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
5074       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
5075       Opcode == PPC::EXTSB8_32_64)
5076     return true;
5077 
5078   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
5079     return true;
5080 
5081   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5082        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
5083       MI.getOperand(3).getImm() > 0 &&
5084       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
5085     return true;
5086 
5087   return false;
5088 }
5089 
5090 // This function returns true if the machine instruction
5091 // always outputs zeros in higher 32 bits.
5092 static bool isZeroExtendingOp(const MachineInstr &MI) {
5093   int Opcode = MI.getOpcode();
5094   // The 16-bit immediate is sign-extended in li/lis.
5095   // If the most significant bit is zero, all higher bits are zero.
5096   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
5097       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
5098     int64_t Imm = MI.getOperand(1).getImm();
5099     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
5100       return true;
5101   }
5102 
5103   // We have some variations of rotate-and-mask instructions
5104   // that clear higher 32-bits.
5105   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
5106        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
5107        Opcode == PPC::RLDICL_32_64) &&
5108       MI.getOperand(3).getImm() >= 32)
5109     return true;
5110 
5111   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
5112       MI.getOperand(3).getImm() >= 32 &&
5113       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
5114     return true;
5115 
5116   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5117        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
5118        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
5119       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
5120     return true;
5121 
5122   // There are other instructions that clear higher 32-bits.
5123   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
5124       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
5125       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
5126       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
5127       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
5128       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
5129       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
5130       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
5131       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
5132       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
5133       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
5134       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
5135       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
5136       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
5137       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
5138       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
5139       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
5140       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
5141       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
5142       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
5143       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
5144       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
5145       Opcode == PPC::MFVSRWZ)
5146     return true;
5147 
5148   return false;
5149 }
5150 
5151 // This function returns true if the input MachineInstr is a TOC save
5152 // instruction.
5153 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
5154   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
5155     return false;
5156   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5157   unsigned StackOffset = MI.getOperand(1).getImm();
5158   Register StackReg = MI.getOperand(2).getReg();
5159   Register SPReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
5160   if (StackReg == SPReg && StackOffset == TOCSaveOffset)
5161     return true;
5162 
5163   return false;
5164 }
5165 
5166 // We limit the max depth to track incoming values of PHIs or binary ops
5167 // (e.g. AND) to avoid excessive cost.
5168 const unsigned MAX_DEPTH = 1;
5169 
5170 bool
5171 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
5172                                    const unsigned Depth) const {
5173   const MachineFunction *MF = MI.getParent()->getParent();
5174   const MachineRegisterInfo *MRI = &MF->getRegInfo();
5175 
5176   // If we know this instruction returns sign- or zero-extended result,
5177   // return true.
5178   if (SignExt ? isSignExtendingOp(MI):
5179                 isZeroExtendingOp(MI))
5180     return true;
5181 
5182   switch (MI.getOpcode()) {
5183   case PPC::COPY: {
5184     Register SrcReg = MI.getOperand(1).getReg();
5185 
5186     // In both ELFv1 and v2 ABI, method parameters and the return value
5187     // are sign- or zero-extended.
5188     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5189       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
5190       // We check the ZExt/SExt flags for a method parameter.
5191       if (MI.getParent()->getBasicBlock() ==
5192           &MF->getFunction().getEntryBlock()) {
5193         Register VReg = MI.getOperand(0).getReg();
5194         if (MF->getRegInfo().isLiveIn(VReg))
5195           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
5196                            FuncInfo->isLiveInZExt(VReg);
5197       }
5198 
5199       // For a method return value, we check the ZExt/SExt flags in attribute.
5200       // We assume the following code sequence for method call.
5201       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
5202       //   BL8_NOP @func,...
5203       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
5204       //   %5 = COPY %x3; G8RC:%5
5205       if (SrcReg == PPC::X3) {
5206         const MachineBasicBlock *MBB = MI.getParent();
5207         MachineBasicBlock::const_instr_iterator II =
5208           MachineBasicBlock::const_instr_iterator(&MI);
5209         if (II != MBB->instr_begin() &&
5210             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
5211           const MachineInstr &CallMI = *(--II);
5212           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
5213             const Function *CalleeFn =
5214               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
5215             if (!CalleeFn)
5216               return false;
5217             const IntegerType *IntTy =
5218               dyn_cast<IntegerType>(CalleeFn->getReturnType());
5219             const AttributeSet &Attrs =
5220               CalleeFn->getAttributes().getRetAttributes();
5221             if (IntTy && IntTy->getBitWidth() <= 32)
5222               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
5223                                                   Attribute::ZExt);
5224           }
5225         }
5226       }
5227     }
5228 
5229     // If this is a copy from another register, we recursively check source.
5230     if (!Register::isVirtualRegister(SrcReg))
5231       return false;
5232     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
5233     if (SrcMI != NULL)
5234       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
5235 
5236     return false;
5237   }
5238 
5239   case PPC::ANDI_rec:
5240   case PPC::ANDIS_rec:
5241   case PPC::ORI:
5242   case PPC::ORIS:
5243   case PPC::XORI:
5244   case PPC::XORIS:
5245   case PPC::ANDI8_rec:
5246   case PPC::ANDIS8_rec:
5247   case PPC::ORI8:
5248   case PPC::ORIS8:
5249   case PPC::XORI8:
5250   case PPC::XORIS8: {
5251     // logical operation with 16-bit immediate does not change the upper bits.
5252     // So, we track the operand register as we do for register copy.
5253     Register SrcReg = MI.getOperand(1).getReg();
5254     if (!Register::isVirtualRegister(SrcReg))
5255       return false;
5256     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
5257     if (SrcMI != NULL)
5258       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
5259 
5260     return false;
5261   }
5262 
5263   // If all incoming values are sign-/zero-extended,
5264   // the output of OR, ISEL or PHI is also sign-/zero-extended.
5265   case PPC::OR:
5266   case PPC::OR8:
5267   case PPC::ISEL:
5268   case PPC::PHI: {
5269     if (Depth >= MAX_DEPTH)
5270       return false;
5271 
5272     // The input registers for PHI are operand 1, 3, ...
5273     // The input registers for others are operand 1 and 2.
5274     unsigned E = 3, D = 1;
5275     if (MI.getOpcode() == PPC::PHI) {
5276       E = MI.getNumOperands();
5277       D = 2;
5278     }
5279 
5280     for (unsigned I = 1; I != E; I += D) {
5281       if (MI.getOperand(I).isReg()) {
5282         Register SrcReg = MI.getOperand(I).getReg();
5283         if (!Register::isVirtualRegister(SrcReg))
5284           return false;
5285         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
5286         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
5287           return false;
5288       }
5289       else
5290         return false;
5291     }
5292     return true;
5293   }
5294 
5295   // If at least one of the incoming values of an AND is zero extended
5296   // then the output is also zero-extended. If both of the incoming values
5297   // are sign-extended then the output is also sign extended.
5298   case PPC::AND:
5299   case PPC::AND8: {
5300     if (Depth >= MAX_DEPTH)
5301        return false;
5302 
5303     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
5304 
5305     Register SrcReg1 = MI.getOperand(1).getReg();
5306     Register SrcReg2 = MI.getOperand(2).getReg();
5307 
5308     if (!Register::isVirtualRegister(SrcReg1) ||
5309         !Register::isVirtualRegister(SrcReg2))
5310       return false;
5311 
5312     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
5313     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
5314     if (!MISrc1 || !MISrc2)
5315         return false;
5316 
5317     if(SignExt)
5318         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
5319                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
5320     else
5321         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
5322                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
5323   }
5324 
5325   default:
5326     break;
5327   }
5328   return false;
5329 }
5330 
5331 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
5332   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
5333 }
5334 
5335 namespace {
5336 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
5337   MachineInstr *Loop, *EndLoop, *LoopCount;
5338   MachineFunction *MF;
5339   const TargetInstrInfo *TII;
5340   int64_t TripCount;
5341 
5342 public:
5343   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
5344                        MachineInstr *LoopCount)
5345       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
5346         MF(Loop->getParent()->getParent()),
5347         TII(MF->getSubtarget().getInstrInfo()) {
5348     // Inspect the Loop instruction up-front, as it may be deleted when we call
5349     // createTripCountGreaterCondition.
5350     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
5351       TripCount = LoopCount->getOperand(1).getImm();
5352     else
5353       TripCount = -1;
5354   }
5355 
5356   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
5357     // Only ignore the terminator.
5358     return MI == EndLoop;
5359   }
5360 
5361   Optional<bool>
5362   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
5363                                   SmallVectorImpl<MachineOperand> &Cond) override {
5364     if (TripCount == -1) {
5365       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5366       // so we don't need to generate any thing here.
5367       Cond.push_back(MachineOperand::CreateImm(0));
5368       Cond.push_back(MachineOperand::CreateReg(
5369           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
5370           true));
5371       return {};
5372     }
5373 
5374     return TripCount > TC;
5375   }
5376 
5377   void setPreheader(MachineBasicBlock *NewPreheader) override {
5378     // Do nothing. We want the LOOP setup instruction to stay in the *old*
5379     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
5380   }
5381 
5382   void adjustTripCount(int TripCountAdjust) override {
5383     // If the loop trip count is a compile-time value, then just change the
5384     // value.
5385     if (LoopCount->getOpcode() == PPC::LI8 ||
5386         LoopCount->getOpcode() == PPC::LI) {
5387       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
5388       LoopCount->getOperand(1).setImm(TripCount);
5389       return;
5390     }
5391 
5392     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5393     // so we don't need to generate any thing here.
5394   }
5395 
5396   void disposed() override {
5397     Loop->eraseFromParent();
5398     // Ensure the loop setup instruction is deleted too.
5399     LoopCount->eraseFromParent();
5400   }
5401 };
5402 } // namespace
5403 
5404 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
5405 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
5406   // We really "analyze" only hardware loops right now.
5407   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
5408   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
5409   if (Preheader == LoopBB)
5410     Preheader = *std::next(LoopBB->pred_begin());
5411   MachineFunction *MF = Preheader->getParent();
5412 
5413   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
5414     SmallPtrSet<MachineBasicBlock *, 8> Visited;
5415     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
5416       Register LoopCountReg = LoopInst->getOperand(0).getReg();
5417       MachineRegisterInfo &MRI = MF->getRegInfo();
5418       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
5419       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
5420     }
5421   }
5422   return nullptr;
5423 }
5424 
5425 MachineInstr *PPCInstrInfo::findLoopInstr(
5426     MachineBasicBlock &PreHeader,
5427     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
5428 
5429   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5430 
5431   // The loop set-up instruction should be in preheader
5432   for (auto &I : PreHeader.instrs())
5433     if (I.getOpcode() == LOOPi)
5434       return &I;
5435   return nullptr;
5436 }
5437 
5438 // Return true if get the base operand, byte offset of an instruction and the
5439 // memory width. Width is the size of memory that is being loaded/stored.
5440 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
5441     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
5442     unsigned &Width, const TargetRegisterInfo *TRI) const {
5443   if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5444     return false;
5445 
5446   // Handle only loads/stores with base register followed by immediate offset.
5447   if (!LdSt.getOperand(1).isImm() ||
5448       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5449     return false;
5450   if (!LdSt.getOperand(1).isImm() ||
5451       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5452     return false;
5453 
5454   if (!LdSt.hasOneMemOperand())
5455     return false;
5456 
5457   Width = (*LdSt.memoperands_begin())->getSize();
5458   Offset = LdSt.getOperand(1).getImm();
5459   BaseReg = &LdSt.getOperand(2);
5460   return true;
5461 }
5462 
5463 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
5464     const MachineInstr &MIa, const MachineInstr &MIb) const {
5465   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5466   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5467 
5468   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
5469       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
5470     return false;
5471 
5472   // Retrieve the base register, offset from the base register and width. Width
5473   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
5474   // base registers are identical, and the offset of a lower memory access +
5475   // the width doesn't overlap the offset of a higher memory access,
5476   // then the memory accesses are different.
5477   const TargetRegisterInfo *TRI = &getRegisterInfo();
5478   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5479   int64_t OffsetA = 0, OffsetB = 0;
5480   unsigned int WidthA = 0, WidthB = 0;
5481   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
5482       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
5483     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
5484       int LowOffset = std::min(OffsetA, OffsetB);
5485       int HighOffset = std::max(OffsetA, OffsetB);
5486       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5487       if (LowOffset + LowWidth <= HighOffset)
5488         return true;
5489     }
5490   }
5491   return false;
5492 }
5493