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