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