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