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