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