LLVM  mainline
PPCInstrInfo.cpp
Go to the documentation of this file.
00001 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the PowerPC implementation of the TargetInstrInfo class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCInstrInfo.h"
00015 #include "MCTargetDesc/PPCPredicates.h"
00016 #include "PPC.h"
00017 #include "PPCHazardRecognizers.h"
00018 #include "PPCInstrBuilder.h"
00019 #include "PPCMachineFunctionInfo.h"
00020 #include "PPCTargetMachine.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunctionPass.h"
00026 #include "llvm/CodeGen/MachineInstrBuilder.h"
00027 #include "llvm/CodeGen/MachineMemOperand.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/PseudoSourceValue.h"
00030 #include "llvm/CodeGen/ScheduleDAG.h"
00031 #include "llvm/CodeGen/SlotIndexes.h"
00032 #include "llvm/CodeGen/StackMaps.h"
00033 #include "llvm/MC/MCAsmInfo.h"
00034 #include "llvm/MC/MCInst.h"
00035 #include "llvm/Support/CommandLine.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/TargetRegistry.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "ppc-instr-info"
00044 
00045 #define GET_INSTRMAP_INFO
00046 #define GET_INSTRINFO_CTOR_DTOR
00047 #include "PPCGenInstrInfo.inc"
00048 
00049 static cl::
00050 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
00051             cl::desc("Disable analysis for CTR loops"));
00052 
00053 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
00054 cl::desc("Disable compare instruction optimization"), cl::Hidden);
00055 
00056 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
00057 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
00058 cl::Hidden);
00059 
00060 // Pin the vtable to this file.
00061 void PPCInstrInfo::anchor() {}
00062 
00063 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
00064     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
00065       Subtarget(STI), RI(STI.getTargetMachine()) {}
00066 
00067 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
00068 /// this target when scheduling the DAG.
00069 ScheduleHazardRecognizer *
00070 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
00071                                            const ScheduleDAG *DAG) const {
00072   unsigned Directive =
00073       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
00074   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
00075       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
00076     const InstrItineraryData *II =
00077         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
00078     return new ScoreboardHazardRecognizer(II, DAG);
00079   }
00080 
00081   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
00082 }
00083 
00084 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
00085 /// to use for this target when scheduling the DAG.
00086 ScheduleHazardRecognizer *
00087 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
00088                                                  const ScheduleDAG *DAG) const {
00089   unsigned Directive =
00090       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
00091 
00092   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
00093     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
00094 
00095   // Most subtargets use a PPC970 recognizer.
00096   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
00097       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
00098     assert(DAG->TII && "No InstrInfo?");
00099 
00100     return new PPCHazardRecognizer970(*DAG);
00101   }
00102 
00103   return new ScoreboardHazardRecognizer(II, DAG);
00104 }
00105 
00106 
00107 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
00108                                     const MachineInstr *DefMI, unsigned DefIdx,
00109                                     const MachineInstr *UseMI,
00110                                     unsigned UseIdx) const {
00111   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
00112                                                    UseMI, UseIdx);
00113 
00114   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
00115   unsigned Reg = DefMO.getReg();
00116 
00117   bool IsRegCR;
00118   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00119     const MachineRegisterInfo *MRI =
00120       &DefMI->getParent()->getParent()->getRegInfo();
00121     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
00122               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
00123   } else {
00124     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
00125               PPC::CRBITRCRegClass.contains(Reg);
00126   }
00127 
00128   if (UseMI->isBranch() && IsRegCR) {
00129     if (Latency < 0)
00130       Latency = getInstrLatency(ItinData, DefMI);
00131 
00132     // On some cores, there is an additional delay between writing to a condition
00133     // register, and using it from a branch.
00134     unsigned Directive = Subtarget.getDarwinDirective();
00135     switch (Directive) {
00136     default: break;
00137     case PPC::DIR_7400:
00138     case PPC::DIR_750:
00139     case PPC::DIR_970:
00140     case PPC::DIR_E5500:
00141     case PPC::DIR_PWR4:
00142     case PPC::DIR_PWR5:
00143     case PPC::DIR_PWR5X:
00144     case PPC::DIR_PWR6:
00145     case PPC::DIR_PWR6X:
00146     case PPC::DIR_PWR7:
00147     case PPC::DIR_PWR8:
00148       Latency += 2;
00149       break;
00150     }
00151   }
00152 
00153   return Latency;
00154 }
00155 
00156 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
00157 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
00158                                          unsigned &SrcReg, unsigned &DstReg,
00159                                          unsigned &SubIdx) const {
00160   switch (MI.getOpcode()) {
00161   default: return false;
00162   case PPC::EXTSW:
00163   case PPC::EXTSW_32_64:
00164     SrcReg = MI.getOperand(1).getReg();
00165     DstReg = MI.getOperand(0).getReg();
00166     SubIdx = PPC::sub_32;
00167     return true;
00168   }
00169 }
00170 
00171 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
00172                                            int &FrameIndex) const {
00173   // Note: This list must be kept consistent with LoadRegFromStackSlot.
00174   switch (MI->getOpcode()) {
00175   default: break;
00176   case PPC::LD:
00177   case PPC::LWZ:
00178   case PPC::LFS:
00179   case PPC::LFD:
00180   case PPC::RESTORE_CR:
00181   case PPC::RESTORE_CRBIT:
00182   case PPC::LVX:
00183   case PPC::LXVD2X:
00184   case PPC::QVLFDX:
00185   case PPC::QVLFSXs:
00186   case PPC::QVLFDXb:
00187   case PPC::RESTORE_VRSAVE:
00188     // Check for the operands added by addFrameReference (the immediate is the
00189     // offset which defaults to 0).
00190     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00191         MI->getOperand(2).isFI()) {
00192       FrameIndex = MI->getOperand(2).getIndex();
00193       return MI->getOperand(0).getReg();
00194     }
00195     break;
00196   }
00197   return 0;
00198 }
00199 
00200 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
00201                                           int &FrameIndex) const {
00202   // Note: This list must be kept consistent with StoreRegToStackSlot.
00203   switch (MI->getOpcode()) {
00204   default: break;
00205   case PPC::STD:
00206   case PPC::STW:
00207   case PPC::STFS:
00208   case PPC::STFD:
00209   case PPC::SPILL_CR:
00210   case PPC::SPILL_CRBIT:
00211   case PPC::STVX:
00212   case PPC::STXVD2X:
00213   case PPC::QVSTFDX:
00214   case PPC::QVSTFSXs:
00215   case PPC::QVSTFDXb:
00216   case PPC::SPILL_VRSAVE:
00217     // Check for the operands added by addFrameReference (the immediate is the
00218     // offset which defaults to 0).
00219     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00220         MI->getOperand(2).isFI()) {
00221       FrameIndex = MI->getOperand(2).getIndex();
00222       return MI->getOperand(0).getReg();
00223     }
00224     break;
00225   }
00226   return 0;
00227 }
00228 
00229 // commuteInstruction - We can commute rlwimi instructions, but only if the
00230 // rotate amt is zero.  We also have to munge the immediates a bit.
00231 MachineInstr *
00232 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
00233   MachineFunction &MF = *MI->getParent()->getParent();
00234 
00235   // Normal instructions can be commuted the obvious way.
00236   if (MI->getOpcode() != PPC::RLWIMI &&
00237       MI->getOpcode() != PPC::RLWIMIo)
00238     return TargetInstrInfo::commuteInstruction(MI, NewMI);
00239   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
00240   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
00241   // changing the relative order of the mask operands might change what happens
00242   // to the high-bits of the mask (and, thus, the result).
00243 
00244   // Cannot commute if it has a non-zero rotate count.
00245   if (MI->getOperand(3).getImm() != 0)
00246     return nullptr;
00247 
00248   // If we have a zero rotate count, we have:
00249   //   M = mask(MB,ME)
00250   //   Op0 = (Op1 & ~M) | (Op2 & M)
00251   // Change this to:
00252   //   M = mask((ME+1)&31, (MB-1)&31)
00253   //   Op0 = (Op2 & ~M) | (Op1 & M)
00254 
00255   // Swap op1/op2
00256   unsigned Reg0 = MI->getOperand(0).getReg();
00257   unsigned Reg1 = MI->getOperand(1).getReg();
00258   unsigned Reg2 = MI->getOperand(2).getReg();
00259   unsigned SubReg1 = MI->getOperand(1).getSubReg();
00260   unsigned SubReg2 = MI->getOperand(2).getSubReg();
00261   bool Reg1IsKill = MI->getOperand(1).isKill();
00262   bool Reg2IsKill = MI->getOperand(2).isKill();
00263   bool ChangeReg0 = false;
00264   // If machine instrs are no longer in two-address forms, update
00265   // destination register as well.
00266   if (Reg0 == Reg1) {
00267     // Must be two address instruction!
00268     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
00269            "Expecting a two-address instruction!");
00270     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
00271     Reg2IsKill = false;
00272     ChangeReg0 = true;
00273   }
00274 
00275   // Masks.
00276   unsigned MB = MI->getOperand(4).getImm();
00277   unsigned ME = MI->getOperand(5).getImm();
00278 
00279   if (NewMI) {
00280     // Create a new instruction.
00281     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
00282     bool Reg0IsDead = MI->getOperand(0).isDead();
00283     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
00284       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
00285       .addReg(Reg2, getKillRegState(Reg2IsKill))
00286       .addReg(Reg1, getKillRegState(Reg1IsKill))
00287       .addImm((ME+1) & 31)
00288       .addImm((MB-1) & 31);
00289   }
00290 
00291   if (ChangeReg0) {
00292     MI->getOperand(0).setReg(Reg2);
00293     MI->getOperand(0).setSubReg(SubReg2);
00294   }
00295   MI->getOperand(2).setReg(Reg1);
00296   MI->getOperand(1).setReg(Reg2);
00297   MI->getOperand(2).setSubReg(SubReg1);
00298   MI->getOperand(1).setSubReg(SubReg2);
00299   MI->getOperand(2).setIsKill(Reg1IsKill);
00300   MI->getOperand(1).setIsKill(Reg2IsKill);
00301 
00302   // Swap the mask around.
00303   MI->getOperand(4).setImm((ME+1) & 31);
00304   MI->getOperand(5).setImm((MB-1) & 31);
00305   return MI;
00306 }
00307 
00308 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
00309                                          unsigned &SrcOpIdx2) const {
00310   // For VSX A-Type FMA instructions, it is the first two operands that can be
00311   // commuted, however, because the non-encoded tied input operand is listed
00312   // first, the operands to swap are actually the second and third.
00313 
00314   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
00315   if (AltOpc == -1)
00316     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
00317 
00318   SrcOpIdx1 = 2;
00319   SrcOpIdx2 = 3;
00320   return true;
00321 }
00322 
00323 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
00324                               MachineBasicBlock::iterator MI) const {
00325   // This function is used for scheduling, and the nop wanted here is the type
00326   // that terminates dispatch groups on the POWER cores.
00327   unsigned Directive = Subtarget.getDarwinDirective();
00328   unsigned Opcode;
00329   switch (Directive) {
00330   default:            Opcode = PPC::NOP; break;
00331   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
00332   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
00333   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
00334   }
00335 
00336   DebugLoc DL;
00337   BuildMI(MBB, MI, DL, get(Opcode));
00338 }
00339 
00340 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
00341 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
00342   NopInst.setOpcode(PPC::NOP);
00343 }
00344 
00345 // Branch analysis.
00346 // Note: If the condition register is set to CTR or CTR8 then this is a
00347 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
00348 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
00349                                  MachineBasicBlock *&FBB,
00350                                  SmallVectorImpl<MachineOperand> &Cond,
00351                                  bool AllowModify) const {
00352   bool isPPC64 = Subtarget.isPPC64();
00353 
00354   // If the block has no terminators, it just falls into the block after it.
00355   MachineBasicBlock::iterator I = MBB.end();
00356   if (I == MBB.begin())
00357     return false;
00358   --I;
00359   while (I->isDebugValue()) {
00360     if (I == MBB.begin())
00361       return false;
00362     --I;
00363   }
00364   if (!isUnpredicatedTerminator(I))
00365     return false;
00366 
00367   // Get the last instruction in the block.
00368   MachineInstr *LastInst = I;
00369 
00370   // If there is only one terminator instruction, process it.
00371   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
00372     if (LastInst->getOpcode() == PPC::B) {
00373       if (!LastInst->getOperand(0).isMBB())
00374         return true;
00375       TBB = LastInst->getOperand(0).getMBB();
00376       return false;
00377     } else if (LastInst->getOpcode() == PPC::BCC) {
00378       if (!LastInst->getOperand(2).isMBB())
00379         return true;
00380       // Block ends with fall-through condbranch.
00381       TBB = LastInst->getOperand(2).getMBB();
00382       Cond.push_back(LastInst->getOperand(0));
00383       Cond.push_back(LastInst->getOperand(1));
00384       return false;
00385     } else if (LastInst->getOpcode() == PPC::BC) {
00386       if (!LastInst->getOperand(1).isMBB())
00387         return true;
00388       // Block ends with fall-through condbranch.
00389       TBB = LastInst->getOperand(1).getMBB();
00390       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00391       Cond.push_back(LastInst->getOperand(0));
00392       return false;
00393     } else if (LastInst->getOpcode() == PPC::BCn) {
00394       if (!LastInst->getOperand(1).isMBB())
00395         return true;
00396       // Block ends with fall-through condbranch.
00397       TBB = LastInst->getOperand(1).getMBB();
00398       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00399       Cond.push_back(LastInst->getOperand(0));
00400       return false;
00401     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
00402                LastInst->getOpcode() == PPC::BDNZ) {
00403       if (!LastInst->getOperand(0).isMBB())
00404         return true;
00405       if (DisableCTRLoopAnal)
00406         return true;
00407       TBB = LastInst->getOperand(0).getMBB();
00408       Cond.push_back(MachineOperand::CreateImm(1));
00409       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00410                                                true));
00411       return false;
00412     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
00413                LastInst->getOpcode() == PPC::BDZ) {
00414       if (!LastInst->getOperand(0).isMBB())
00415         return true;
00416       if (DisableCTRLoopAnal)
00417         return true;
00418       TBB = LastInst->getOperand(0).getMBB();
00419       Cond.push_back(MachineOperand::CreateImm(0));
00420       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00421                                                true));
00422       return false;
00423     }
00424 
00425     // Otherwise, don't know what this is.
00426     return true;
00427   }
00428 
00429   // Get the instruction before it if it's a terminator.
00430   MachineInstr *SecondLastInst = I;
00431 
00432   // If there are three terminators, we don't know what sort of block this is.
00433   if (SecondLastInst && I != MBB.begin() &&
00434       isUnpredicatedTerminator(--I))
00435     return true;
00436 
00437   // If the block ends with PPC::B and PPC:BCC, handle it.
00438   if (SecondLastInst->getOpcode() == PPC::BCC &&
00439       LastInst->getOpcode() == PPC::B) {
00440     if (!SecondLastInst->getOperand(2).isMBB() ||
00441         !LastInst->getOperand(0).isMBB())
00442       return true;
00443     TBB =  SecondLastInst->getOperand(2).getMBB();
00444     Cond.push_back(SecondLastInst->getOperand(0));
00445     Cond.push_back(SecondLastInst->getOperand(1));
00446     FBB = LastInst->getOperand(0).getMBB();
00447     return false;
00448   } else if (SecondLastInst->getOpcode() == PPC::BC &&
00449       LastInst->getOpcode() == PPC::B) {
00450     if (!SecondLastInst->getOperand(1).isMBB() ||
00451         !LastInst->getOperand(0).isMBB())
00452       return true;
00453     TBB =  SecondLastInst->getOperand(1).getMBB();
00454     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00455     Cond.push_back(SecondLastInst->getOperand(0));
00456     FBB = LastInst->getOperand(0).getMBB();
00457     return false;
00458   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
00459       LastInst->getOpcode() == PPC::B) {
00460     if (!SecondLastInst->getOperand(1).isMBB() ||
00461         !LastInst->getOperand(0).isMBB())
00462       return true;
00463     TBB =  SecondLastInst->getOperand(1).getMBB();
00464     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00465     Cond.push_back(SecondLastInst->getOperand(0));
00466     FBB = LastInst->getOperand(0).getMBB();
00467     return false;
00468   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
00469               SecondLastInst->getOpcode() == PPC::BDNZ) &&
00470       LastInst->getOpcode() == PPC::B) {
00471     if (!SecondLastInst->getOperand(0).isMBB() ||
00472         !LastInst->getOperand(0).isMBB())
00473       return true;
00474     if (DisableCTRLoopAnal)
00475       return true;
00476     TBB = SecondLastInst->getOperand(0).getMBB();
00477     Cond.push_back(MachineOperand::CreateImm(1));
00478     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00479                                              true));
00480     FBB = LastInst->getOperand(0).getMBB();
00481     return false;
00482   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
00483               SecondLastInst->getOpcode() == PPC::BDZ) &&
00484       LastInst->getOpcode() == PPC::B) {
00485     if (!SecondLastInst->getOperand(0).isMBB() ||
00486         !LastInst->getOperand(0).isMBB())
00487       return true;
00488     if (DisableCTRLoopAnal)
00489       return true;
00490     TBB = SecondLastInst->getOperand(0).getMBB();
00491     Cond.push_back(MachineOperand::CreateImm(0));
00492     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00493                                              true));
00494     FBB = LastInst->getOperand(0).getMBB();
00495     return false;
00496   }
00497 
00498   // If the block ends with two PPC:Bs, handle it.  The second one is not
00499   // executed, so remove it.
00500   if (SecondLastInst->getOpcode() == PPC::B &&
00501       LastInst->getOpcode() == PPC::B) {
00502     if (!SecondLastInst->getOperand(0).isMBB())
00503       return true;
00504     TBB = SecondLastInst->getOperand(0).getMBB();
00505     I = LastInst;
00506     if (AllowModify)
00507       I->eraseFromParent();
00508     return false;
00509   }
00510 
00511   // Otherwise, can't handle this.
00512   return true;
00513 }
00514 
00515 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
00516   MachineBasicBlock::iterator I = MBB.end();
00517   if (I == MBB.begin()) return 0;
00518   --I;
00519   while (I->isDebugValue()) {
00520     if (I == MBB.begin())
00521       return 0;
00522     --I;
00523   }
00524   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
00525       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00526       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00527       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00528     return 0;
00529 
00530   // Remove the branch.
00531   I->eraseFromParent();
00532 
00533   I = MBB.end();
00534 
00535   if (I == MBB.begin()) return 1;
00536   --I;
00537   if (I->getOpcode() != PPC::BCC &&
00538       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00539       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00540       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00541     return 1;
00542 
00543   // Remove the branch.
00544   I->eraseFromParent();
00545   return 2;
00546 }
00547 
00548 unsigned
00549 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
00550                            MachineBasicBlock *FBB,
00551                            ArrayRef<MachineOperand> Cond,
00552                            DebugLoc DL) const {
00553   // Shouldn't be a fall through.
00554   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
00555   assert((Cond.size() == 2 || Cond.size() == 0) &&
00556          "PPC branch conditions have two components!");
00557 
00558   bool isPPC64 = Subtarget.isPPC64();
00559 
00560   // One-way branch.
00561   if (!FBB) {
00562     if (Cond.empty())   // Unconditional branch
00563       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
00564     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00565       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00566                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00567                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00568     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00569       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00570     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00571       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00572     else                // Conditional branch
00573       BuildMI(&MBB, DL, get(PPC::BCC))
00574         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00575     return 1;
00576   }
00577 
00578   // Two-way Conditional Branch.
00579   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00580     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00581                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00582                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00583   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00584     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00585   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00586     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00587   else
00588     BuildMI(&MBB, DL, get(PPC::BCC))
00589       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00590   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
00591   return 2;
00592 }
00593 
00594 // Select analysis.
00595 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
00596                 ArrayRef<MachineOperand> Cond,
00597                 unsigned TrueReg, unsigned FalseReg,
00598                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
00599   if (!Subtarget.hasISEL())
00600     return false;
00601 
00602   if (Cond.size() != 2)
00603     return false;
00604 
00605   // If this is really a bdnz-like condition, then it cannot be turned into a
00606   // select.
00607   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00608     return false;
00609 
00610   // Check register classes.
00611   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00612   const TargetRegisterClass *RC =
00613     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00614   if (!RC)
00615     return false;
00616 
00617   // isel is for regular integer GPRs only.
00618   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
00619       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
00620       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
00621       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
00622     return false;
00623 
00624   // FIXME: These numbers are for the A2, how well they work for other cores is
00625   // an open question. On the A2, the isel instruction has a 2-cycle latency
00626   // but single-cycle throughput. These numbers are used in combination with
00627   // the MispredictPenalty setting from the active SchedMachineModel.
00628   CondCycles = 1;
00629   TrueCycles = 1;
00630   FalseCycles = 1;
00631 
00632   return true;
00633 }
00634 
00635 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
00636                                 MachineBasicBlock::iterator MI, DebugLoc dl,
00637                                 unsigned DestReg, ArrayRef<MachineOperand> Cond,
00638                                 unsigned TrueReg, unsigned FalseReg) const {
00639   assert(Cond.size() == 2 &&
00640          "PPC branch conditions have two components!");
00641 
00642   assert(Subtarget.hasISEL() &&
00643          "Cannot insert select on target without ISEL support");
00644 
00645   // Get the register classes.
00646   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00647   const TargetRegisterClass *RC =
00648     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00649   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
00650 
00651   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
00652                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
00653   assert((Is64Bit ||
00654           PPC::GPRCRegClass.hasSubClassEq(RC) ||
00655           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
00656          "isel is for regular integer GPRs only");
00657 
00658   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
00659   unsigned SelectPred = Cond[0].getImm();
00660 
00661   unsigned SubIdx;
00662   bool SwapOps;
00663   switch (SelectPred) {
00664   default: llvm_unreachable("invalid predicate for isel");
00665   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
00666   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
00667   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
00668   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
00669   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
00670   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
00671   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
00672   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
00673   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
00674   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
00675   }
00676 
00677   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
00678            SecondReg = SwapOps ? TrueReg  : FalseReg;
00679 
00680   // The first input register of isel cannot be r0. If it is a member
00681   // of a register class that can be r0, then copy it first (the
00682   // register allocator should eliminate the copy).
00683   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
00684       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
00685     const TargetRegisterClass *FirstRC =
00686       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
00687         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
00688     unsigned OldFirstReg = FirstReg;
00689     FirstReg = MRI.createVirtualRegister(FirstRC);
00690     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
00691       .addReg(OldFirstReg);
00692   }
00693 
00694   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
00695     .addReg(FirstReg).addReg(SecondReg)
00696     .addReg(Cond[1].getReg(), 0, SubIdx);
00697 }
00698 
00699 static unsigned getCRBitValue(unsigned CRBit) {
00700   unsigned Ret = 4;
00701   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
00702       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
00703       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
00704       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
00705     Ret = 3;
00706   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
00707       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
00708       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
00709       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
00710     Ret = 2;
00711   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
00712       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
00713       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
00714       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
00715     Ret = 1;
00716   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
00717       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
00718       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
00719       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
00720     Ret = 0;
00721 
00722   assert(Ret != 4 && "Invalid CR bit register");
00723   return Ret;
00724 }
00725 
00726 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
00727                                MachineBasicBlock::iterator I, DebugLoc DL,
00728                                unsigned DestReg, unsigned SrcReg,
00729                                bool KillSrc) const {
00730   // We can end up with self copies and similar things as a result of VSX copy
00731   // legalization. Promote them here.
00732   const TargetRegisterInfo *TRI = &getRegisterInfo();
00733   if (PPC::F8RCRegClass.contains(DestReg) &&
00734       PPC::VSRCRegClass.contains(SrcReg)) {
00735     unsigned SuperReg =
00736       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
00737 
00738     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00739       llvm_unreachable("nop VSX copy");
00740 
00741     DestReg = SuperReg;
00742   } else if (PPC::VRRCRegClass.contains(DestReg) &&
00743              PPC::VSRCRegClass.contains(SrcReg)) {
00744     unsigned SuperReg =
00745       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
00746 
00747     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00748       llvm_unreachable("nop VSX copy");
00749 
00750     DestReg = SuperReg;
00751   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
00752              PPC::VSRCRegClass.contains(DestReg)) {
00753     unsigned SuperReg =
00754       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
00755 
00756     if (VSXSelfCopyCrash && DestReg == SuperReg)
00757       llvm_unreachable("nop VSX copy");
00758 
00759     SrcReg = SuperReg;
00760   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
00761              PPC::VSRCRegClass.contains(DestReg)) {
00762     unsigned SuperReg =
00763       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
00764 
00765     if (VSXSelfCopyCrash && DestReg == SuperReg)
00766       llvm_unreachable("nop VSX copy");
00767 
00768     SrcReg = SuperReg;
00769   }
00770 
00771   // Different class register copy
00772   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
00773       PPC::GPRCRegClass.contains(DestReg)) {
00774     unsigned CRReg = getCRFromCRBit(SrcReg);
00775     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
00776        .addReg(CRReg), getKillRegState(KillSrc);
00777     // Rotate the CR bit in the CR fields to be the least significant bit and
00778     // then mask with 0x1 (MB = ME = 31).
00779     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
00780        .addReg(DestReg, RegState::Kill)
00781        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
00782        .addImm(31)
00783        .addImm(31);
00784     return;
00785   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
00786       PPC::G8RCRegClass.contains(DestReg)) {
00787     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg)
00788        .addReg(SrcReg), getKillRegState(KillSrc);
00789     return;
00790   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
00791       PPC::GPRCRegClass.contains(DestReg)) {
00792     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
00793        .addReg(SrcReg), getKillRegState(KillSrc);
00794     return;
00795    }
00796 
00797   unsigned Opc;
00798   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
00799     Opc = PPC::OR;
00800   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
00801     Opc = PPC::OR8;
00802   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
00803     Opc = PPC::FMR;
00804   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
00805     Opc = PPC::MCRF;
00806   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
00807     Opc = PPC::VOR;
00808   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
00809     // There are two different ways this can be done:
00810     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
00811     //      issue in VSU pipeline 0.
00812     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
00813     //      can go to either pipeline.
00814     // We'll always use xxlor here, because in practically all cases where
00815     // copies are generated, they are close enough to some use that the
00816     // lower-latency form is preferable.
00817     Opc = PPC::XXLOR;
00818   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
00819            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
00820     Opc = PPC::XXLORf;
00821   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
00822     Opc = PPC::QVFMR;
00823   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
00824     Opc = PPC::QVFMRs;
00825   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
00826     Opc = PPC::QVFMRb;
00827   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
00828     Opc = PPC::CROR;
00829   else
00830     llvm_unreachable("Impossible reg-to-reg copy");
00831 
00832   const MCInstrDesc &MCID = get(Opc);
00833   if (MCID.getNumOperands() == 3)
00834     BuildMI(MBB, I, DL, MCID, DestReg)
00835       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
00836   else
00837     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
00838 }
00839 
00840 // This function returns true if a CR spill is necessary and false otherwise.
00841 bool
00842 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
00843                                   unsigned SrcReg, bool isKill,
00844                                   int FrameIdx,
00845                                   const TargetRegisterClass *RC,
00846                                   SmallVectorImpl<MachineInstr*> &NewMIs,
00847                                   bool &NonRI, bool &SpillsVRS) const{
00848   // Note: If additional store instructions are added here,
00849   // update isStoreToStackSlot.
00850 
00851   DebugLoc DL;
00852   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00853       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00854     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
00855                                        .addReg(SrcReg,
00856                                                getKillRegState(isKill)),
00857                                        FrameIdx));
00858   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00859              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00860     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
00861                                        .addReg(SrcReg,
00862                                                getKillRegState(isKill)),
00863                                        FrameIdx));
00864   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00865     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
00866                                        .addReg(SrcReg,
00867                                                getKillRegState(isKill)),
00868                                        FrameIdx));
00869   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00870     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
00871                                        .addReg(SrcReg,
00872                                                getKillRegState(isKill)),
00873                                        FrameIdx));
00874   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00875     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
00876                                        .addReg(SrcReg,
00877                                                getKillRegState(isKill)),
00878                                        FrameIdx));
00879     return true;
00880   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00881     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
00882                                        .addReg(SrcReg,
00883                                                getKillRegState(isKill)),
00884                                        FrameIdx));
00885     return true;
00886   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00887     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
00888                                        .addReg(SrcReg,
00889                                                getKillRegState(isKill)),
00890                                        FrameIdx));
00891     NonRI = true;
00892   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00893     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
00894                                        .addReg(SrcReg,
00895                                                getKillRegState(isKill)),
00896                                        FrameIdx));
00897     NonRI = true;
00898   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00899     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
00900                                        .addReg(SrcReg,
00901                                                getKillRegState(isKill)),
00902                                        FrameIdx));
00903     NonRI = true;
00904   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
00905     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSSPX))
00906                                        .addReg(SrcReg,
00907                                                getKillRegState(isKill)),
00908                                        FrameIdx));
00909     NonRI = true;
00910   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00911     assert(Subtarget.isDarwin() &&
00912            "VRSAVE only needs spill/restore on Darwin");
00913     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
00914                                        .addReg(SrcReg,
00915                                                getKillRegState(isKill)),
00916                                        FrameIdx));
00917     SpillsVRS = true;
00918   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
00919     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
00920                                        .addReg(SrcReg,
00921                                                getKillRegState(isKill)),
00922                                        FrameIdx));
00923     NonRI = true;
00924   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
00925     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
00926                                        .addReg(SrcReg,
00927                                                getKillRegState(isKill)),
00928                                        FrameIdx));
00929     NonRI = true;
00930   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
00931     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
00932                                        .addReg(SrcReg,
00933                                                getKillRegState(isKill)),
00934                                        FrameIdx));
00935     NonRI = true;
00936   } else {
00937     llvm_unreachable("Unknown regclass!");
00938   }
00939 
00940   return false;
00941 }
00942 
00943 void
00944 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
00945                                   MachineBasicBlock::iterator MI,
00946                                   unsigned SrcReg, bool isKill, int FrameIdx,
00947                                   const TargetRegisterClass *RC,
00948                                   const TargetRegisterInfo *TRI) const {
00949   MachineFunction &MF = *MBB.getParent();
00950   SmallVector<MachineInstr*, 4> NewMIs;
00951 
00952   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00953   FuncInfo->setHasSpills();
00954 
00955   bool NonRI = false, SpillsVRS = false;
00956   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
00957                           NonRI, SpillsVRS))
00958     FuncInfo->setSpillsCR();
00959 
00960   if (SpillsVRS)
00961     FuncInfo->setSpillsVRSAVE();
00962 
00963   if (NonRI)
00964     FuncInfo->setHasNonRISpills();
00965 
00966   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00967     MBB.insert(MI, NewMIs[i]);
00968 
00969   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00970   MachineMemOperand *MMO =
00971     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00972                             MachineMemOperand::MOStore,
00973                             MFI.getObjectSize(FrameIdx),
00974                             MFI.getObjectAlignment(FrameIdx));
00975   NewMIs.back()->addMemOperand(MF, MMO);
00976 }
00977 
00978 bool
00979 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
00980                                    unsigned DestReg, int FrameIdx,
00981                                    const TargetRegisterClass *RC,
00982                                    SmallVectorImpl<MachineInstr*> &NewMIs,
00983                                    bool &NonRI, bool &SpillsVRS) const{
00984   // Note: If additional load instructions are added here,
00985   // update isLoadFromStackSlot.
00986 
00987   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00988       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00989     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
00990                                                DestReg), FrameIdx));
00991   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00992              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00993     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
00994                                        FrameIdx));
00995   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00996     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
00997                                        FrameIdx));
00998   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00999     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
01000                                        FrameIdx));
01001   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
01002     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01003                                                get(PPC::RESTORE_CR), DestReg),
01004                                        FrameIdx));
01005     return true;
01006   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
01007     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01008                                                get(PPC::RESTORE_CRBIT), DestReg),
01009                                        FrameIdx));
01010     return true;
01011   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
01012     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
01013                                        FrameIdx));
01014     NonRI = true;
01015   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
01016     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
01017                                        FrameIdx));
01018     NonRI = true;
01019   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
01020     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
01021                                        FrameIdx));
01022     NonRI = true;
01023   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
01024     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSSPX), DestReg),
01025                                        FrameIdx));
01026     NonRI = true;
01027   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
01028     assert(Subtarget.isDarwin() &&
01029            "VRSAVE only needs spill/restore on Darwin");
01030     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01031                                                get(PPC::RESTORE_VRSAVE),
01032                                                DestReg),
01033                                        FrameIdx));
01034     SpillsVRS = true;
01035   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
01036     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
01037                                        FrameIdx));
01038     NonRI = true;
01039   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
01040     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
01041                                        FrameIdx));
01042     NonRI = true;
01043   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
01044     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
01045                                        FrameIdx));
01046     NonRI = true;
01047   } else {
01048     llvm_unreachable("Unknown regclass!");
01049   }
01050 
01051   return false;
01052 }
01053 
01054 void
01055 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
01056                                    MachineBasicBlock::iterator MI,
01057                                    unsigned DestReg, int FrameIdx,
01058                                    const TargetRegisterClass *RC,
01059                                    const TargetRegisterInfo *TRI) const {
01060   MachineFunction &MF = *MBB.getParent();
01061   SmallVector<MachineInstr*, 4> NewMIs;
01062   DebugLoc DL;
01063   if (MI != MBB.end()) DL = MI->getDebugLoc();
01064 
01065   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01066   FuncInfo->setHasSpills();
01067 
01068   bool NonRI = false, SpillsVRS = false;
01069   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
01070                            NonRI, SpillsVRS))
01071     FuncInfo->setSpillsCR();
01072 
01073   if (SpillsVRS)
01074     FuncInfo->setSpillsVRSAVE();
01075 
01076   if (NonRI)
01077     FuncInfo->setHasNonRISpills();
01078 
01079   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
01080     MBB.insert(MI, NewMIs[i]);
01081 
01082   const MachineFrameInfo &MFI = *MF.getFrameInfo();
01083   MachineMemOperand *MMO =
01084     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
01085                             MachineMemOperand::MOLoad,
01086                             MFI.getObjectSize(FrameIdx),
01087                             MFI.getObjectAlignment(FrameIdx));
01088   NewMIs.back()->addMemOperand(MF, MMO);
01089 }
01090 
01091 bool PPCInstrInfo::
01092 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
01093   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
01094   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
01095     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
01096   else
01097     // Leave the CR# the same, but invert the condition.
01098     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
01099   return false;
01100 }
01101 
01102 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
01103                              unsigned Reg, MachineRegisterInfo *MRI) const {
01104   // For some instructions, it is legal to fold ZERO into the RA register field.
01105   // A zero immediate should always be loaded with a single li.
01106   unsigned DefOpc = DefMI->getOpcode();
01107   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
01108     return false;
01109   if (!DefMI->getOperand(1).isImm())
01110     return false;
01111   if (DefMI->getOperand(1).getImm() != 0)
01112     return false;
01113 
01114   // Note that we cannot here invert the arguments of an isel in order to fold
01115   // a ZERO into what is presented as the second argument. All we have here
01116   // is the condition bit, and that might come from a CR-logical bit operation.
01117 
01118   const MCInstrDesc &UseMCID = UseMI->getDesc();
01119 
01120   // Only fold into real machine instructions.
01121   if (UseMCID.isPseudo())
01122     return false;
01123 
01124   unsigned UseIdx;
01125   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
01126     if (UseMI->getOperand(UseIdx).isReg() &&
01127         UseMI->getOperand(UseIdx).getReg() == Reg)
01128       break;
01129 
01130   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
01131   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
01132 
01133   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
01134 
01135   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
01136   // register (which might also be specified as a pointer class kind).
01137   if (UseInfo->isLookupPtrRegClass()) {
01138     if (UseInfo->RegClass /* Kind */ != 1)
01139       return false;
01140   } else {
01141     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
01142         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
01143       return false;
01144   }
01145 
01146   // Make sure this is not tied to an output register (or otherwise
01147   // constrained). This is true for ST?UX registers, for example, which
01148   // are tied to their output registers.
01149   if (UseInfo->Constraints != 0)
01150     return false;
01151 
01152   unsigned ZeroReg;
01153   if (UseInfo->isLookupPtrRegClass()) {
01154     bool isPPC64 = Subtarget.isPPC64();
01155     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
01156   } else {
01157     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
01158               PPC::ZERO8 : PPC::ZERO;
01159   }
01160 
01161   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
01162   UseMI->getOperand(UseIdx).setReg(ZeroReg);
01163 
01164   if (DeleteDef)
01165     DefMI->eraseFromParent();
01166 
01167   return true;
01168 }
01169 
01170 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
01171   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01172        I != IE; ++I)
01173     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
01174       return true;
01175   return false;
01176 }
01177 
01178 // We should make sure that, if we're going to predicate both sides of a
01179 // condition (a diamond), that both sides don't define the counter register. We
01180 // can predicate counter-decrement-based branches, but while that predicates
01181 // the branching, it does not predicate the counter decrement. If we tried to
01182 // merge the triangle into one predicated block, we'd decrement the counter
01183 // twice.
01184 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
01185                      unsigned NumT, unsigned ExtraT,
01186                      MachineBasicBlock &FMBB,
01187                      unsigned NumF, unsigned ExtraF,
01188                      const BranchProbability &Probability) const {
01189   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
01190 }
01191 
01192 
01193 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
01194   // The predicated branches are identified by their type, not really by the
01195   // explicit presence of a predicate. Furthermore, some of them can be
01196   // predicated more than once. Because if conversion won't try to predicate
01197   // any instruction which already claims to be predicated (by returning true
01198   // here), always return false. In doing so, we let isPredicable() be the
01199   // final word on whether not the instruction can be (further) predicated.
01200 
01201   return false;
01202 }
01203 
01204 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
01205   if (!MI->isTerminator())
01206     return false;
01207 
01208   // Conditional branch is a special case.
01209   if (MI->isBranch() && !MI->isBarrier())
01210     return true;
01211 
01212   return !isPredicated(MI);
01213 }
01214 
01215 bool PPCInstrInfo::PredicateInstruction(MachineInstr *MI,
01216                                         ArrayRef<MachineOperand> Pred) const {
01217   unsigned OpC = MI->getOpcode();
01218   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
01219     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01220       bool isPPC64 = Subtarget.isPPC64();
01221       MI->setDesc(get(Pred[0].getImm() ?
01222                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
01223                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
01224     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01225       MI->setDesc(get(PPC::BCLR));
01226       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01227         .addReg(Pred[1].getReg());
01228     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01229       MI->setDesc(get(PPC::BCLRn));
01230       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01231         .addReg(Pred[1].getReg());
01232     } else {
01233       MI->setDesc(get(PPC::BCCLR));
01234       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01235         .addImm(Pred[0].getImm())
01236         .addReg(Pred[1].getReg());
01237     }
01238 
01239     return true;
01240   } else if (OpC == PPC::B) {
01241     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01242       bool isPPC64 = Subtarget.isPPC64();
01243       MI->setDesc(get(Pred[0].getImm() ?
01244                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01245                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
01246     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01247       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01248       MI->RemoveOperand(0);
01249 
01250       MI->setDesc(get(PPC::BC));
01251       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01252         .addReg(Pred[1].getReg())
01253         .addMBB(MBB);
01254     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01255       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01256       MI->RemoveOperand(0);
01257 
01258       MI->setDesc(get(PPC::BCn));
01259       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01260         .addReg(Pred[1].getReg())
01261         .addMBB(MBB);
01262     } else {
01263       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01264       MI->RemoveOperand(0);
01265 
01266       MI->setDesc(get(PPC::BCC));
01267       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01268         .addImm(Pred[0].getImm())
01269         .addReg(Pred[1].getReg())
01270         .addMBB(MBB);
01271     }
01272 
01273     return true;
01274   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
01275              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
01276     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
01277       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
01278 
01279     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
01280     bool isPPC64 = Subtarget.isPPC64();
01281 
01282     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01283       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
01284                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
01285       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01286         .addReg(Pred[1].getReg());
01287       return true;
01288     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01289       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
01290                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
01291       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01292         .addReg(Pred[1].getReg());
01293       return true;
01294     }
01295 
01296     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
01297                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
01298     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01299       .addImm(Pred[0].getImm())
01300       .addReg(Pred[1].getReg());
01301     return true;
01302   }
01303 
01304   return false;
01305 }
01306 
01307 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
01308                                      ArrayRef<MachineOperand> Pred2) const {
01309   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
01310   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
01311 
01312   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
01313     return false;
01314   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
01315     return false;
01316 
01317   // P1 can only subsume P2 if they test the same condition register.
01318   if (Pred1[1].getReg() != Pred2[1].getReg())
01319     return false;
01320 
01321   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
01322   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
01323 
01324   if (P1 == P2)
01325     return true;
01326 
01327   // Does P1 subsume P2, e.g. GE subsumes GT.
01328   if (P1 == PPC::PRED_LE &&
01329       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
01330     return true;
01331   if (P1 == PPC::PRED_GE &&
01332       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
01333     return true;
01334 
01335   return false;
01336 }
01337 
01338 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
01339                                     std::vector<MachineOperand> &Pred) const {
01340   // Note: At the present time, the contents of Pred from this function is
01341   // unused by IfConversion. This implementation follows ARM by pushing the
01342   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
01343   // predicate, instructions defining CTR or CTR8 are also included as
01344   // predicate-defining instructions.
01345 
01346   const TargetRegisterClass *RCs[] =
01347     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
01348       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
01349 
01350   bool Found = false;
01351   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01352     const MachineOperand &MO = MI->getOperand(i);
01353     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
01354       const TargetRegisterClass *RC = RCs[c];
01355       if (MO.isReg()) {
01356         if (MO.isDef() && RC->contains(MO.getReg())) {
01357           Pred.push_back(MO);
01358           Found = true;
01359         }
01360       } else if (MO.isRegMask()) {
01361         for (TargetRegisterClass::iterator I = RC->begin(),
01362              IE = RC->end(); I != IE; ++I)
01363           if (MO.clobbersPhysReg(*I)) {
01364             Pred.push_back(MO);
01365             Found = true;
01366           }
01367       }
01368     }
01369   }
01370 
01371   return Found;
01372 }
01373 
01374 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
01375   unsigned OpC = MI->getOpcode();
01376   switch (OpC) {
01377   default:
01378     return false;
01379   case PPC::B:
01380   case PPC::BLR:
01381   case PPC::BLR8:
01382   case PPC::BCTR:
01383   case PPC::BCTR8:
01384   case PPC::BCTRL:
01385   case PPC::BCTRL8:
01386     return true;
01387   }
01388 }
01389 
01390 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
01391                                   unsigned &SrcReg, unsigned &SrcReg2,
01392                                   int &Mask, int &Value) const {
01393   unsigned Opc = MI->getOpcode();
01394 
01395   switch (Opc) {
01396   default: return false;
01397   case PPC::CMPWI:
01398   case PPC::CMPLWI:
01399   case PPC::CMPDI:
01400   case PPC::CMPLDI:
01401     SrcReg = MI->getOperand(1).getReg();
01402     SrcReg2 = 0;
01403     Value = MI->getOperand(2).getImm();
01404     Mask = 0xFFFF;
01405     return true;
01406   case PPC::CMPW:
01407   case PPC::CMPLW:
01408   case PPC::CMPD:
01409   case PPC::CMPLD:
01410   case PPC::FCMPUS:
01411   case PPC::FCMPUD:
01412     SrcReg = MI->getOperand(1).getReg();
01413     SrcReg2 = MI->getOperand(2).getReg();
01414     return true;
01415   }
01416 }
01417 
01418 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
01419                                         unsigned SrcReg, unsigned SrcReg2,
01420                                         int Mask, int Value,
01421                                         const MachineRegisterInfo *MRI) const {
01422   if (DisableCmpOpt)
01423     return false;
01424 
01425   int OpC = CmpInstr->getOpcode();
01426   unsigned CRReg = CmpInstr->getOperand(0).getReg();
01427 
01428   // FP record forms set CR1 based on the execption status bits, not a
01429   // comparison with zero.
01430   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
01431     return false;
01432 
01433   // The record forms set the condition register based on a signed comparison
01434   // with zero (so says the ISA manual). This is not as straightforward as it
01435   // seems, however, because this is always a 64-bit comparison on PPC64, even
01436   // for instructions that are 32-bit in nature (like slw for example).
01437   // So, on PPC32, for unsigned comparisons, we can use the record forms only
01438   // for equality checks (as those don't depend on the sign). On PPC64,
01439   // we are restricted to equality for unsigned 64-bit comparisons and for
01440   // signed 32-bit comparisons the applicability is more restricted.
01441   bool isPPC64 = Subtarget.isPPC64();
01442   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
01443   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
01444   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
01445 
01446   // Get the unique definition of SrcReg.
01447   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
01448   if (!MI) return false;
01449   int MIOpC = MI->getOpcode();
01450 
01451   bool equalityOnly = false;
01452   bool noSub = false;
01453   if (isPPC64) {
01454     if (is32BitSignedCompare) {
01455       // We can perform this optimization only if MI is sign-extending.
01456       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
01457           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
01458           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
01459           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
01460           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
01461         noSub = true;
01462       } else
01463         return false;
01464     } else if (is32BitUnsignedCompare) {
01465       // We can perform this optimization, equality only, if MI is
01466       // zero-extending.
01467       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
01468           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
01469           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
01470         noSub = true;
01471         equalityOnly = true;
01472       } else
01473         return false;
01474     } else
01475       equalityOnly = is64BitUnsignedCompare;
01476   } else
01477     equalityOnly = is32BitUnsignedCompare;
01478 
01479   if (equalityOnly) {
01480     // We need to check the uses of the condition register in order to reject
01481     // non-equality comparisons.
01482     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
01483          IE = MRI->use_instr_end(); I != IE; ++I) {
01484       MachineInstr *UseMI = &*I;
01485       if (UseMI->getOpcode() == PPC::BCC) {
01486         unsigned Pred = UseMI->getOperand(0).getImm();
01487         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
01488           return false;
01489       } else if (UseMI->getOpcode() == PPC::ISEL ||
01490                  UseMI->getOpcode() == PPC::ISEL8) {
01491         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
01492         if (SubIdx != PPC::sub_eq)
01493           return false;
01494       } else
01495         return false;
01496     }
01497   }
01498 
01499   MachineBasicBlock::iterator I = CmpInstr;
01500 
01501   // Scan forward to find the first use of the compare.
01502   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
01503        I != EL; ++I) {
01504     bool FoundUse = false;
01505     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
01506          JE = MRI->use_instr_end(); J != JE; ++J)
01507       if (&*J == &*I) {
01508         FoundUse = true;
01509         break;
01510       }
01511 
01512     if (FoundUse)
01513       break;
01514   }
01515 
01516   // There are two possible candidates which can be changed to set CR[01].
01517   // One is MI, the other is a SUB instruction.
01518   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
01519   MachineInstr *Sub = nullptr;
01520   if (SrcReg2 != 0)
01521     // MI is not a candidate for CMPrr.
01522     MI = nullptr;
01523   // FIXME: Conservatively refuse to convert an instruction which isn't in the
01524   // same BB as the comparison. This is to allow the check below to avoid calls
01525   // (and other explicit clobbers); instead we should really check for these
01526   // more explicitly (in at least a few predecessors).
01527   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
01528     // PPC does not have a record-form SUBri.
01529     return false;
01530   }
01531 
01532   // Search for Sub.
01533   const TargetRegisterInfo *TRI = &getRegisterInfo();
01534   --I;
01535 
01536   // Get ready to iterate backward from CmpInstr.
01537   MachineBasicBlock::iterator E = MI,
01538                               B = CmpInstr->getParent()->begin();
01539 
01540   for (; I != E && !noSub; --I) {
01541     const MachineInstr &Instr = *I;
01542     unsigned IOpC = Instr.getOpcode();
01543 
01544     if (&*I != CmpInstr && (
01545         Instr.modifiesRegister(PPC::CR0, TRI) ||
01546         Instr.readsRegister(PPC::CR0, TRI)))
01547       // This instruction modifies or uses the record condition register after
01548       // the one we want to change. While we could do this transformation, it
01549       // would likely not be profitable. This transformation removes one
01550       // instruction, and so even forcing RA to generate one move probably
01551       // makes it unprofitable.
01552       return false;
01553 
01554     // Check whether CmpInstr can be made redundant by the current instruction.
01555     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
01556          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
01557         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
01558         ((Instr.getOperand(1).getReg() == SrcReg &&
01559           Instr.getOperand(2).getReg() == SrcReg2) ||
01560         (Instr.getOperand(1).getReg() == SrcReg2 &&
01561          Instr.getOperand(2).getReg() == SrcReg))) {
01562       Sub = &*I;
01563       break;
01564     }
01565 
01566     if (I == B)
01567       // The 'and' is below the comparison instruction.
01568       return false;
01569   }
01570 
01571   // Return false if no candidates exist.
01572   if (!MI && !Sub)
01573     return false;
01574 
01575   // The single candidate is called MI.
01576   if (!MI) MI = Sub;
01577 
01578   int NewOpC = -1;
01579   MIOpC = MI->getOpcode();
01580   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
01581     NewOpC = MIOpC;
01582   else {
01583     NewOpC = PPC::getRecordFormOpcode(MIOpC);
01584     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
01585       NewOpC = MIOpC;
01586   }
01587 
01588   // FIXME: On the non-embedded POWER architectures, only some of the record
01589   // forms are fast, and we should use only the fast ones.
01590 
01591   // The defining instruction has a record form (or is already a record
01592   // form). It is possible, however, that we'll need to reverse the condition
01593   // code of the users.
01594   if (NewOpC == -1)
01595     return false;
01596 
01597   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
01598   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
01599 
01600   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
01601   // needs to be updated to be based on SUB.  Push the condition code
01602   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
01603   // condition code of these operands will be modified.
01604   bool ShouldSwap = false;
01605   if (Sub) {
01606     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
01607       Sub->getOperand(2).getReg() == SrcReg;
01608 
01609     // The operands to subf are the opposite of sub, so only in the fixed-point
01610     // case, invert the order.
01611     ShouldSwap = !ShouldSwap;
01612   }
01613 
01614   if (ShouldSwap)
01615     for (MachineRegisterInfo::use_instr_iterator
01616          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
01617          I != IE; ++I) {
01618       MachineInstr *UseMI = &*I;
01619       if (UseMI->getOpcode() == PPC::BCC) {
01620         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
01621         assert((!equalityOnly ||
01622                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
01623                "Invalid predicate for equality-only optimization");
01624         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
01625                                 PPC::getSwappedPredicate(Pred)));
01626       } else if (UseMI->getOpcode() == PPC::ISEL ||
01627                  UseMI->getOpcode() == PPC::ISEL8) {
01628         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
01629         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
01630                "Invalid CR bit for equality-only optimization");
01631 
01632         if (NewSubReg == PPC::sub_lt)
01633           NewSubReg = PPC::sub_gt;
01634         else if (NewSubReg == PPC::sub_gt)
01635           NewSubReg = PPC::sub_lt;
01636 
01637         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
01638                                                  NewSubReg));
01639       } else // We need to abort on a user we don't understand.
01640         return false;
01641     }
01642 
01643   // Create a new virtual register to hold the value of the CR set by the
01644   // record-form instruction. If the instruction was not previously in
01645   // record form, then set the kill flag on the CR.
01646   CmpInstr->eraseFromParent();
01647 
01648   MachineBasicBlock::iterator MII = MI;
01649   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
01650           get(TargetOpcode::COPY), CRReg)
01651     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
01652 
01653   if (MIOpC != NewOpC) {
01654     // We need to be careful here: we're replacing one instruction with
01655     // another, and we need to make sure that we get all of the right
01656     // implicit uses and defs. On the other hand, the caller may be holding
01657     // an iterator to this instruction, and so we can't delete it (this is
01658     // specifically the case if this is the instruction directly after the
01659     // compare).
01660 
01661     const MCInstrDesc &NewDesc = get(NewOpC);
01662     MI->setDesc(NewDesc);
01663 
01664     if (NewDesc.ImplicitDefs)
01665       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
01666            *ImpDefs; ++ImpDefs)
01667         if (!MI->definesRegister(*ImpDefs))
01668           MI->addOperand(*MI->getParent()->getParent(),
01669                          MachineOperand::CreateReg(*ImpDefs, true, true));
01670     if (NewDesc.ImplicitUses)
01671       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
01672            *ImpUses; ++ImpUses)
01673         if (!MI->readsRegister(*ImpUses))
01674           MI->addOperand(*MI->getParent()->getParent(),
01675                          MachineOperand::CreateReg(*ImpUses, false, true));
01676   }
01677 
01678   // Modify the condition code of operands in OperandsToUpdate.
01679   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
01680   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
01681   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
01682     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
01683 
01684   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
01685     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
01686 
01687   return true;
01688 }
01689 
01690 /// GetInstSize - Return the number of bytes of code the specified
01691 /// instruction may be.  This returns the maximum number of bytes.
01692 ///
01693 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
01694   unsigned Opcode = MI->getOpcode();
01695 
01696   if (Opcode == PPC::INLINEASM) {
01697     const MachineFunction *MF = MI->getParent()->getParent();
01698     const char *AsmStr = MI->getOperand(0).getSymbolName();
01699     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
01700   } else if (Opcode == TargetOpcode::STACKMAP) {
01701     return MI->getOperand(1).getImm();
01702   } else if (Opcode == TargetOpcode::PATCHPOINT) {
01703     PatchPointOpers Opers(MI);
01704     return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
01705   } else {
01706     const MCInstrDesc &Desc = get(Opcode);
01707     return Desc.getSize();
01708   }
01709 }
01710