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                            const SmallVectorImpl<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                 const SmallVectorImpl<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,
00638                                 const SmallVectorImpl<MachineOperand> &Cond,
00639                                 unsigned TrueReg, unsigned FalseReg) const {
00640   assert(Cond.size() == 2 &&
00641          "PPC branch conditions have two components!");
00642 
00643   assert(Subtarget.hasISEL() &&
00644          "Cannot insert select on target without ISEL support");
00645 
00646   // Get the register classes.
00647   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00648   const TargetRegisterClass *RC =
00649     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00650   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
00651 
00652   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
00653                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
00654   assert((Is64Bit ||
00655           PPC::GPRCRegClass.hasSubClassEq(RC) ||
00656           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
00657          "isel is for regular integer GPRs only");
00658 
00659   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
00660   unsigned SelectPred = Cond[0].getImm();
00661 
00662   unsigned SubIdx;
00663   bool SwapOps;
00664   switch (SelectPred) {
00665   default: llvm_unreachable("invalid predicate for isel");
00666   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
00667   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
00668   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
00669   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
00670   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
00671   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
00672   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
00673   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
00674   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
00675   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
00676   }
00677 
00678   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
00679            SecondReg = SwapOps ? TrueReg  : FalseReg;
00680 
00681   // The first input register of isel cannot be r0. If it is a member
00682   // of a register class that can be r0, then copy it first (the
00683   // register allocator should eliminate the copy).
00684   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
00685       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
00686     const TargetRegisterClass *FirstRC =
00687       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
00688         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
00689     unsigned OldFirstReg = FirstReg;
00690     FirstReg = MRI.createVirtualRegister(FirstRC);
00691     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
00692       .addReg(OldFirstReg);
00693   }
00694 
00695   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
00696     .addReg(FirstReg).addReg(SecondReg)
00697     .addReg(Cond[1].getReg(), 0, SubIdx);
00698 }
00699 
00700 static unsigned getCRBitValue(unsigned CRBit) {
00701   unsigned Ret = 4;
00702   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
00703       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
00704       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
00705       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
00706     Ret = 3;
00707   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
00708       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
00709       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
00710       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
00711     Ret = 2;
00712   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
00713       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
00714       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
00715       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
00716     Ret = 1;
00717   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
00718       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
00719       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
00720       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
00721     Ret = 0;
00722 
00723   assert(Ret != 4 && "Invalid CR bit register");
00724   return Ret;
00725 }
00726 
00727 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
00728                                MachineBasicBlock::iterator I, DebugLoc DL,
00729                                unsigned DestReg, unsigned SrcReg,
00730                                bool KillSrc) const {
00731   // We can end up with self copies and similar things as a result of VSX copy
00732   // legalization. Promote them here.
00733   const TargetRegisterInfo *TRI = &getRegisterInfo();
00734   if (PPC::F8RCRegClass.contains(DestReg) &&
00735       PPC::VSRCRegClass.contains(SrcReg)) {
00736     unsigned SuperReg =
00737       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
00738 
00739     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00740       llvm_unreachable("nop VSX copy");
00741 
00742     DestReg = SuperReg;
00743   } else if (PPC::VRRCRegClass.contains(DestReg) &&
00744              PPC::VSRCRegClass.contains(SrcReg)) {
00745     unsigned SuperReg =
00746       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
00747 
00748     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00749       llvm_unreachable("nop VSX copy");
00750 
00751     DestReg = SuperReg;
00752   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
00753              PPC::VSRCRegClass.contains(DestReg)) {
00754     unsigned SuperReg =
00755       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
00756 
00757     if (VSXSelfCopyCrash && DestReg == SuperReg)
00758       llvm_unreachable("nop VSX copy");
00759 
00760     SrcReg = SuperReg;
00761   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
00762              PPC::VSRCRegClass.contains(DestReg)) {
00763     unsigned SuperReg =
00764       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
00765 
00766     if (VSXSelfCopyCrash && DestReg == SuperReg)
00767       llvm_unreachable("nop VSX copy");
00768 
00769     SrcReg = SuperReg;
00770   }
00771 
00772   // Different class register copy
00773   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
00774       PPC::GPRCRegClass.contains(DestReg)) {
00775     unsigned CRReg = getCRFromCRBit(SrcReg);
00776     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
00777        .addReg(CRReg), getKillRegState(KillSrc);
00778     // Rotate the CR bit in the CR fields to be the least significant bit and
00779     // then mask with 0x1 (MB = ME = 31).
00780     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
00781        .addReg(DestReg, RegState::Kill)
00782        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
00783        .addImm(31)
00784        .addImm(31);
00785     return;
00786   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
00787       PPC::G8RCRegClass.contains(DestReg)) {
00788     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg)
00789        .addReg(SrcReg), getKillRegState(KillSrc);
00790     return;
00791   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
00792       PPC::GPRCRegClass.contains(DestReg)) {
00793     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
00794        .addReg(SrcReg), getKillRegState(KillSrc);
00795     return;
00796    }
00797 
00798   unsigned Opc;
00799   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
00800     Opc = PPC::OR;
00801   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
00802     Opc = PPC::OR8;
00803   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
00804     Opc = PPC::FMR;
00805   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
00806     Opc = PPC::MCRF;
00807   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
00808     Opc = PPC::VOR;
00809   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
00810     // There are two different ways this can be done:
00811     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
00812     //      issue in VSU pipeline 0.
00813     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
00814     //      can go to either pipeline.
00815     // We'll always use xxlor here, because in practically all cases where
00816     // copies are generated, they are close enough to some use that the
00817     // lower-latency form is preferable.
00818     Opc = PPC::XXLOR;
00819   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
00820            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
00821     Opc = PPC::XXLORf;
00822   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
00823     Opc = PPC::QVFMR;
00824   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
00825     Opc = PPC::QVFMRs;
00826   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
00827     Opc = PPC::QVFMRb;
00828   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
00829     Opc = PPC::CROR;
00830   else
00831     llvm_unreachable("Impossible reg-to-reg copy");
00832 
00833   const MCInstrDesc &MCID = get(Opc);
00834   if (MCID.getNumOperands() == 3)
00835     BuildMI(MBB, I, DL, MCID, DestReg)
00836       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
00837   else
00838     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
00839 }
00840 
00841 // This function returns true if a CR spill is necessary and false otherwise.
00842 bool
00843 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
00844                                   unsigned SrcReg, bool isKill,
00845                                   int FrameIdx,
00846                                   const TargetRegisterClass *RC,
00847                                   SmallVectorImpl<MachineInstr*> &NewMIs,
00848                                   bool &NonRI, bool &SpillsVRS) const{
00849   // Note: If additional store instructions are added here,
00850   // update isStoreToStackSlot.
00851 
00852   DebugLoc DL;
00853   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00854       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00855     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
00856                                        .addReg(SrcReg,
00857                                                getKillRegState(isKill)),
00858                                        FrameIdx));
00859   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00860              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00861     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
00862                                        .addReg(SrcReg,
00863                                                getKillRegState(isKill)),
00864                                        FrameIdx));
00865   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00866     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
00867                                        .addReg(SrcReg,
00868                                                getKillRegState(isKill)),
00869                                        FrameIdx));
00870   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00871     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
00872                                        .addReg(SrcReg,
00873                                                getKillRegState(isKill)),
00874                                        FrameIdx));
00875   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00876     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
00877                                        .addReg(SrcReg,
00878                                                getKillRegState(isKill)),
00879                                        FrameIdx));
00880     return true;
00881   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00882     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
00883                                        .addReg(SrcReg,
00884                                                getKillRegState(isKill)),
00885                                        FrameIdx));
00886     return true;
00887   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00888     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
00889                                        .addReg(SrcReg,
00890                                                getKillRegState(isKill)),
00891                                        FrameIdx));
00892     NonRI = true;
00893   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00894     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
00895                                        .addReg(SrcReg,
00896                                                getKillRegState(isKill)),
00897                                        FrameIdx));
00898     NonRI = true;
00899   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00900     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
00901                                        .addReg(SrcReg,
00902                                                getKillRegState(isKill)),
00903                                        FrameIdx));
00904     NonRI = true;
00905   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
00906     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSSPX))
00907                                        .addReg(SrcReg,
00908                                                getKillRegState(isKill)),
00909                                        FrameIdx));
00910     NonRI = true;
00911   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00912     assert(Subtarget.isDarwin() &&
00913            "VRSAVE only needs spill/restore on Darwin");
00914     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
00915                                        .addReg(SrcReg,
00916                                                getKillRegState(isKill)),
00917                                        FrameIdx));
00918     SpillsVRS = true;
00919   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
00920     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
00921                                        .addReg(SrcReg,
00922                                                getKillRegState(isKill)),
00923                                        FrameIdx));
00924     NonRI = true;
00925   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
00926     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
00927                                        .addReg(SrcReg,
00928                                                getKillRegState(isKill)),
00929                                        FrameIdx));
00930     NonRI = true;
00931   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
00932     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
00933                                        .addReg(SrcReg,
00934                                                getKillRegState(isKill)),
00935                                        FrameIdx));
00936     NonRI = true;
00937   } else {
00938     llvm_unreachable("Unknown regclass!");
00939   }
00940 
00941   return false;
00942 }
00943 
00944 void
00945 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
00946                                   MachineBasicBlock::iterator MI,
00947                                   unsigned SrcReg, bool isKill, int FrameIdx,
00948                                   const TargetRegisterClass *RC,
00949                                   const TargetRegisterInfo *TRI) const {
00950   MachineFunction &MF = *MBB.getParent();
00951   SmallVector<MachineInstr*, 4> NewMIs;
00952 
00953   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00954   FuncInfo->setHasSpills();
00955 
00956   bool NonRI = false, SpillsVRS = false;
00957   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
00958                           NonRI, SpillsVRS))
00959     FuncInfo->setSpillsCR();
00960 
00961   if (SpillsVRS)
00962     FuncInfo->setSpillsVRSAVE();
00963 
00964   if (NonRI)
00965     FuncInfo->setHasNonRISpills();
00966 
00967   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00968     MBB.insert(MI, NewMIs[i]);
00969 
00970   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00971   MachineMemOperand *MMO =
00972     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00973                             MachineMemOperand::MOStore,
00974                             MFI.getObjectSize(FrameIdx),
00975                             MFI.getObjectAlignment(FrameIdx));
00976   NewMIs.back()->addMemOperand(MF, MMO);
00977 }
00978 
00979 bool
00980 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
00981                                    unsigned DestReg, int FrameIdx,
00982                                    const TargetRegisterClass *RC,
00983                                    SmallVectorImpl<MachineInstr*> &NewMIs,
00984                                    bool &NonRI, bool &SpillsVRS) const{
00985   // Note: If additional load instructions are added here,
00986   // update isLoadFromStackSlot.
00987 
00988   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00989       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00990     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
00991                                                DestReg), FrameIdx));
00992   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00993              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00994     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
00995                                        FrameIdx));
00996   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00997     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
00998                                        FrameIdx));
00999   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
01000     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
01001                                        FrameIdx));
01002   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
01003     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01004                                                get(PPC::RESTORE_CR), DestReg),
01005                                        FrameIdx));
01006     return true;
01007   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
01008     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01009                                                get(PPC::RESTORE_CRBIT), DestReg),
01010                                        FrameIdx));
01011     return true;
01012   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
01013     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
01014                                        FrameIdx));
01015     NonRI = true;
01016   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
01017     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
01018                                        FrameIdx));
01019     NonRI = true;
01020   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
01021     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
01022                                        FrameIdx));
01023     NonRI = true;
01024   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
01025     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSSPX), DestReg),
01026                                        FrameIdx));
01027     NonRI = true;
01028   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
01029     assert(Subtarget.isDarwin() &&
01030            "VRSAVE only needs spill/restore on Darwin");
01031     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
01032                                                get(PPC::RESTORE_VRSAVE),
01033                                                DestReg),
01034                                        FrameIdx));
01035     SpillsVRS = true;
01036   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
01037     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
01038                                        FrameIdx));
01039     NonRI = true;
01040   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
01041     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
01042                                        FrameIdx));
01043     NonRI = true;
01044   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
01045     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
01046                                        FrameIdx));
01047     NonRI = true;
01048   } else {
01049     llvm_unreachable("Unknown regclass!");
01050   }
01051 
01052   return false;
01053 }
01054 
01055 void
01056 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
01057                                    MachineBasicBlock::iterator MI,
01058                                    unsigned DestReg, int FrameIdx,
01059                                    const TargetRegisterClass *RC,
01060                                    const TargetRegisterInfo *TRI) const {
01061   MachineFunction &MF = *MBB.getParent();
01062   SmallVector<MachineInstr*, 4> NewMIs;
01063   DebugLoc DL;
01064   if (MI != MBB.end()) DL = MI->getDebugLoc();
01065 
01066   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01067   FuncInfo->setHasSpills();
01068 
01069   bool NonRI = false, SpillsVRS = false;
01070   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
01071                            NonRI, SpillsVRS))
01072     FuncInfo->setSpillsCR();
01073 
01074   if (SpillsVRS)
01075     FuncInfo->setSpillsVRSAVE();
01076 
01077   if (NonRI)
01078     FuncInfo->setHasNonRISpills();
01079 
01080   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
01081     MBB.insert(MI, NewMIs[i]);
01082 
01083   const MachineFrameInfo &MFI = *MF.getFrameInfo();
01084   MachineMemOperand *MMO =
01085     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
01086                             MachineMemOperand::MOLoad,
01087                             MFI.getObjectSize(FrameIdx),
01088                             MFI.getObjectAlignment(FrameIdx));
01089   NewMIs.back()->addMemOperand(MF, MMO);
01090 }
01091 
01092 bool PPCInstrInfo::
01093 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
01094   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
01095   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
01096     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
01097   else
01098     // Leave the CR# the same, but invert the condition.
01099     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
01100   return false;
01101 }
01102 
01103 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
01104                              unsigned Reg, MachineRegisterInfo *MRI) const {
01105   // For some instructions, it is legal to fold ZERO into the RA register field.
01106   // A zero immediate should always be loaded with a single li.
01107   unsigned DefOpc = DefMI->getOpcode();
01108   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
01109     return false;
01110   if (!DefMI->getOperand(1).isImm())
01111     return false;
01112   if (DefMI->getOperand(1).getImm() != 0)
01113     return false;
01114 
01115   // Note that we cannot here invert the arguments of an isel in order to fold
01116   // a ZERO into what is presented as the second argument. All we have here
01117   // is the condition bit, and that might come from a CR-logical bit operation.
01118 
01119   const MCInstrDesc &UseMCID = UseMI->getDesc();
01120 
01121   // Only fold into real machine instructions.
01122   if (UseMCID.isPseudo())
01123     return false;
01124 
01125   unsigned UseIdx;
01126   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
01127     if (UseMI->getOperand(UseIdx).isReg() &&
01128         UseMI->getOperand(UseIdx).getReg() == Reg)
01129       break;
01130 
01131   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
01132   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
01133 
01134   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
01135 
01136   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
01137   // register (which might also be specified as a pointer class kind).
01138   if (UseInfo->isLookupPtrRegClass()) {
01139     if (UseInfo->RegClass /* Kind */ != 1)
01140       return false;
01141   } else {
01142     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
01143         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
01144       return false;
01145   }
01146 
01147   // Make sure this is not tied to an output register (or otherwise
01148   // constrained). This is true for ST?UX registers, for example, which
01149   // are tied to their output registers.
01150   if (UseInfo->Constraints != 0)
01151     return false;
01152 
01153   unsigned ZeroReg;
01154   if (UseInfo->isLookupPtrRegClass()) {
01155     bool isPPC64 = Subtarget.isPPC64();
01156     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
01157   } else {
01158     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
01159               PPC::ZERO8 : PPC::ZERO;
01160   }
01161 
01162   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
01163   UseMI->getOperand(UseIdx).setReg(ZeroReg);
01164 
01165   if (DeleteDef)
01166     DefMI->eraseFromParent();
01167 
01168   return true;
01169 }
01170 
01171 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
01172   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01173        I != IE; ++I)
01174     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
01175       return true;
01176   return false;
01177 }
01178 
01179 // We should make sure that, if we're going to predicate both sides of a
01180 // condition (a diamond), that both sides don't define the counter register. We
01181 // can predicate counter-decrement-based branches, but while that predicates
01182 // the branching, it does not predicate the counter decrement. If we tried to
01183 // merge the triangle into one predicated block, we'd decrement the counter
01184 // twice.
01185 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
01186                      unsigned NumT, unsigned ExtraT,
01187                      MachineBasicBlock &FMBB,
01188                      unsigned NumF, unsigned ExtraF,
01189                      const BranchProbability &Probability) const {
01190   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
01191 }
01192 
01193 
01194 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
01195   // The predicated branches are identified by their type, not really by the
01196   // explicit presence of a predicate. Furthermore, some of them can be
01197   // predicated more than once. Because if conversion won't try to predicate
01198   // any instruction which already claims to be predicated (by returning true
01199   // here), always return false. In doing so, we let isPredicable() be the
01200   // final word on whether not the instruction can be (further) predicated.
01201 
01202   return false;
01203 }
01204 
01205 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
01206   if (!MI->isTerminator())
01207     return false;
01208 
01209   // Conditional branch is a special case.
01210   if (MI->isBranch() && !MI->isBarrier())
01211     return true;
01212 
01213   return !isPredicated(MI);
01214 }
01215 
01216 bool PPCInstrInfo::PredicateInstruction(
01217                      MachineInstr *MI,
01218                      const SmallVectorImpl<MachineOperand> &Pred) const {
01219   unsigned OpC = MI->getOpcode();
01220   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
01221     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01222       bool isPPC64 = Subtarget.isPPC64();
01223       MI->setDesc(get(Pred[0].getImm() ?
01224                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
01225                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
01226     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01227       MI->setDesc(get(PPC::BCLR));
01228       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01229         .addReg(Pred[1].getReg());
01230     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01231       MI->setDesc(get(PPC::BCLRn));
01232       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01233         .addReg(Pred[1].getReg());
01234     } else {
01235       MI->setDesc(get(PPC::BCCLR));
01236       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01237         .addImm(Pred[0].getImm())
01238         .addReg(Pred[1].getReg());
01239     }
01240 
01241     return true;
01242   } else if (OpC == PPC::B) {
01243     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01244       bool isPPC64 = Subtarget.isPPC64();
01245       MI->setDesc(get(Pred[0].getImm() ?
01246                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01247                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
01248     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01249       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01250       MI->RemoveOperand(0);
01251 
01252       MI->setDesc(get(PPC::BC));
01253       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01254         .addReg(Pred[1].getReg())
01255         .addMBB(MBB);
01256     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01257       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01258       MI->RemoveOperand(0);
01259 
01260       MI->setDesc(get(PPC::BCn));
01261       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01262         .addReg(Pred[1].getReg())
01263         .addMBB(MBB);
01264     } else {
01265       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01266       MI->RemoveOperand(0);
01267 
01268       MI->setDesc(get(PPC::BCC));
01269       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01270         .addImm(Pred[0].getImm())
01271         .addReg(Pred[1].getReg())
01272         .addMBB(MBB);
01273     }
01274 
01275     return true;
01276   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
01277              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
01278     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
01279       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
01280 
01281     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
01282     bool isPPC64 = Subtarget.isPPC64();
01283 
01284     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01285       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
01286                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
01287       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01288         .addReg(Pred[1].getReg());
01289       return true;
01290     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01291       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
01292                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
01293       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01294         .addReg(Pred[1].getReg());
01295       return true;
01296     }
01297 
01298     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
01299                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
01300     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01301       .addImm(Pred[0].getImm())
01302       .addReg(Pred[1].getReg());
01303     return true;
01304   }
01305 
01306   return false;
01307 }
01308 
01309 bool PPCInstrInfo::SubsumesPredicate(
01310                      const SmallVectorImpl<MachineOperand> &Pred1,
01311                      const SmallVectorImpl<MachineOperand> &Pred2) const {
01312   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
01313   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
01314 
01315   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
01316     return false;
01317   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
01318     return false;
01319 
01320   // P1 can only subsume P2 if they test the same condition register.
01321   if (Pred1[1].getReg() != Pred2[1].getReg())
01322     return false;
01323 
01324   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
01325   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
01326 
01327   if (P1 == P2)
01328     return true;
01329 
01330   // Does P1 subsume P2, e.g. GE subsumes GT.
01331   if (P1 == PPC::PRED_LE &&
01332       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
01333     return true;
01334   if (P1 == PPC::PRED_GE &&
01335       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
01336     return true;
01337 
01338   return false;
01339 }
01340 
01341 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
01342                                     std::vector<MachineOperand> &Pred) const {
01343   // Note: At the present time, the contents of Pred from this function is
01344   // unused by IfConversion. This implementation follows ARM by pushing the
01345   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
01346   // predicate, instructions defining CTR or CTR8 are also included as
01347   // predicate-defining instructions.
01348 
01349   const TargetRegisterClass *RCs[] =
01350     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
01351       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
01352 
01353   bool Found = false;
01354   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01355     const MachineOperand &MO = MI->getOperand(i);
01356     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
01357       const TargetRegisterClass *RC = RCs[c];
01358       if (MO.isReg()) {
01359         if (MO.isDef() && RC->contains(MO.getReg())) {
01360           Pred.push_back(MO);
01361           Found = true;
01362         }
01363       } else if (MO.isRegMask()) {
01364         for (TargetRegisterClass::iterator I = RC->begin(),
01365              IE = RC->end(); I != IE; ++I)
01366           if (MO.clobbersPhysReg(*I)) {
01367             Pred.push_back(MO);
01368             Found = true;
01369           }
01370       }
01371     }
01372   }
01373 
01374   return Found;
01375 }
01376 
01377 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
01378   unsigned OpC = MI->getOpcode();
01379   switch (OpC) {
01380   default:
01381     return false;
01382   case PPC::B:
01383   case PPC::BLR:
01384   case PPC::BLR8:
01385   case PPC::BCTR:
01386   case PPC::BCTR8:
01387   case PPC::BCTRL:
01388   case PPC::BCTRL8:
01389     return true;
01390   }
01391 }
01392 
01393 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
01394                                   unsigned &SrcReg, unsigned &SrcReg2,
01395                                   int &Mask, int &Value) const {
01396   unsigned Opc = MI->getOpcode();
01397 
01398   switch (Opc) {
01399   default: return false;
01400   case PPC::CMPWI:
01401   case PPC::CMPLWI:
01402   case PPC::CMPDI:
01403   case PPC::CMPLDI:
01404     SrcReg = MI->getOperand(1).getReg();
01405     SrcReg2 = 0;
01406     Value = MI->getOperand(2).getImm();
01407     Mask = 0xFFFF;
01408     return true;
01409   case PPC::CMPW:
01410   case PPC::CMPLW:
01411   case PPC::CMPD:
01412   case PPC::CMPLD:
01413   case PPC::FCMPUS:
01414   case PPC::FCMPUD:
01415     SrcReg = MI->getOperand(1).getReg();
01416     SrcReg2 = MI->getOperand(2).getReg();
01417     return true;
01418   }
01419 }
01420 
01421 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
01422                                         unsigned SrcReg, unsigned SrcReg2,
01423                                         int Mask, int Value,
01424                                         const MachineRegisterInfo *MRI) const {
01425   if (DisableCmpOpt)
01426     return false;
01427 
01428   int OpC = CmpInstr->getOpcode();
01429   unsigned CRReg = CmpInstr->getOperand(0).getReg();
01430 
01431   // FP record forms set CR1 based on the execption status bits, not a
01432   // comparison with zero.
01433   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
01434     return false;
01435 
01436   // The record forms set the condition register based on a signed comparison
01437   // with zero (so says the ISA manual). This is not as straightforward as it
01438   // seems, however, because this is always a 64-bit comparison on PPC64, even
01439   // for instructions that are 32-bit in nature (like slw for example).
01440   // So, on PPC32, for unsigned comparisons, we can use the record forms only
01441   // for equality checks (as those don't depend on the sign). On PPC64,
01442   // we are restricted to equality for unsigned 64-bit comparisons and for
01443   // signed 32-bit comparisons the applicability is more restricted.
01444   bool isPPC64 = Subtarget.isPPC64();
01445   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
01446   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
01447   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
01448 
01449   // Get the unique definition of SrcReg.
01450   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
01451   if (!MI) return false;
01452   int MIOpC = MI->getOpcode();
01453 
01454   bool equalityOnly = false;
01455   bool noSub = false;
01456   if (isPPC64) {
01457     if (is32BitSignedCompare) {
01458       // We can perform this optimization only if MI is sign-extending.
01459       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
01460           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
01461           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
01462           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
01463           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
01464         noSub = true;
01465       } else
01466         return false;
01467     } else if (is32BitUnsignedCompare) {
01468       // We can perform this optimization, equality only, if MI is
01469       // zero-extending.
01470       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
01471           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
01472           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
01473         noSub = true;
01474         equalityOnly = true;
01475       } else
01476         return false;
01477     } else
01478       equalityOnly = is64BitUnsignedCompare;
01479   } else
01480     equalityOnly = is32BitUnsignedCompare;
01481 
01482   if (equalityOnly) {
01483     // We need to check the uses of the condition register in order to reject
01484     // non-equality comparisons.
01485     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
01486          IE = MRI->use_instr_end(); I != IE; ++I) {
01487       MachineInstr *UseMI = &*I;
01488       if (UseMI->getOpcode() == PPC::BCC) {
01489         unsigned Pred = UseMI->getOperand(0).getImm();
01490         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
01491           return false;
01492       } else if (UseMI->getOpcode() == PPC::ISEL ||
01493                  UseMI->getOpcode() == PPC::ISEL8) {
01494         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
01495         if (SubIdx != PPC::sub_eq)
01496           return false;
01497       } else
01498         return false;
01499     }
01500   }
01501 
01502   MachineBasicBlock::iterator I = CmpInstr;
01503 
01504   // Scan forward to find the first use of the compare.
01505   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
01506        I != EL; ++I) {
01507     bool FoundUse = false;
01508     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
01509          JE = MRI->use_instr_end(); J != JE; ++J)
01510       if (&*J == &*I) {
01511         FoundUse = true;
01512         break;
01513       }
01514 
01515     if (FoundUse)
01516       break;
01517   }
01518 
01519   // There are two possible candidates which can be changed to set CR[01].
01520   // One is MI, the other is a SUB instruction.
01521   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
01522   MachineInstr *Sub = nullptr;
01523   if (SrcReg2 != 0)
01524     // MI is not a candidate for CMPrr.
01525     MI = nullptr;
01526   // FIXME: Conservatively refuse to convert an instruction which isn't in the
01527   // same BB as the comparison. This is to allow the check below to avoid calls
01528   // (and other explicit clobbers); instead we should really check for these
01529   // more explicitly (in at least a few predecessors).
01530   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
01531     // PPC does not have a record-form SUBri.
01532     return false;
01533   }
01534 
01535   // Search for Sub.
01536   const TargetRegisterInfo *TRI = &getRegisterInfo();
01537   --I;
01538 
01539   // Get ready to iterate backward from CmpInstr.
01540   MachineBasicBlock::iterator E = MI,
01541                               B = CmpInstr->getParent()->begin();
01542 
01543   for (; I != E && !noSub; --I) {
01544     const MachineInstr &Instr = *I;
01545     unsigned IOpC = Instr.getOpcode();
01546 
01547     if (&*I != CmpInstr && (
01548         Instr.modifiesRegister(PPC::CR0, TRI) ||
01549         Instr.readsRegister(PPC::CR0, TRI)))
01550       // This instruction modifies or uses the record condition register after
01551       // the one we want to change. While we could do this transformation, it
01552       // would likely not be profitable. This transformation removes one
01553       // instruction, and so even forcing RA to generate one move probably
01554       // makes it unprofitable.
01555       return false;
01556 
01557     // Check whether CmpInstr can be made redundant by the current instruction.
01558     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
01559          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
01560         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
01561         ((Instr.getOperand(1).getReg() == SrcReg &&
01562           Instr.getOperand(2).getReg() == SrcReg2) ||
01563         (Instr.getOperand(1).getReg() == SrcReg2 &&
01564          Instr.getOperand(2).getReg() == SrcReg))) {
01565       Sub = &*I;
01566       break;
01567     }
01568 
01569     if (I == B)
01570       // The 'and' is below the comparison instruction.
01571       return false;
01572   }
01573 
01574   // Return false if no candidates exist.
01575   if (!MI && !Sub)
01576     return false;
01577 
01578   // The single candidate is called MI.
01579   if (!MI) MI = Sub;
01580 
01581   int NewOpC = -1;
01582   MIOpC = MI->getOpcode();
01583   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
01584     NewOpC = MIOpC;
01585   else {
01586     NewOpC = PPC::getRecordFormOpcode(MIOpC);
01587     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
01588       NewOpC = MIOpC;
01589   }
01590 
01591   // FIXME: On the non-embedded POWER architectures, only some of the record
01592   // forms are fast, and we should use only the fast ones.
01593 
01594   // The defining instruction has a record form (or is already a record
01595   // form). It is possible, however, that we'll need to reverse the condition
01596   // code of the users.
01597   if (NewOpC == -1)
01598     return false;
01599 
01600   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
01601   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
01602 
01603   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
01604   // needs to be updated to be based on SUB.  Push the condition code
01605   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
01606   // condition code of these operands will be modified.
01607   bool ShouldSwap = false;
01608   if (Sub) {
01609     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
01610       Sub->getOperand(2).getReg() == SrcReg;
01611 
01612     // The operands to subf are the opposite of sub, so only in the fixed-point
01613     // case, invert the order.
01614     ShouldSwap = !ShouldSwap;
01615   }
01616 
01617   if (ShouldSwap)
01618     for (MachineRegisterInfo::use_instr_iterator
01619          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
01620          I != IE; ++I) {
01621       MachineInstr *UseMI = &*I;
01622       if (UseMI->getOpcode() == PPC::BCC) {
01623         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
01624         assert((!equalityOnly ||
01625                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
01626                "Invalid predicate for equality-only optimization");
01627         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
01628                                 PPC::getSwappedPredicate(Pred)));
01629       } else if (UseMI->getOpcode() == PPC::ISEL ||
01630                  UseMI->getOpcode() == PPC::ISEL8) {
01631         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
01632         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
01633                "Invalid CR bit for equality-only optimization");
01634 
01635         if (NewSubReg == PPC::sub_lt)
01636           NewSubReg = PPC::sub_gt;
01637         else if (NewSubReg == PPC::sub_gt)
01638           NewSubReg = PPC::sub_lt;
01639 
01640         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
01641                                                  NewSubReg));
01642       } else // We need to abort on a user we don't understand.
01643         return false;
01644     }
01645 
01646   // Create a new virtual register to hold the value of the CR set by the
01647   // record-form instruction. If the instruction was not previously in
01648   // record form, then set the kill flag on the CR.
01649   CmpInstr->eraseFromParent();
01650 
01651   MachineBasicBlock::iterator MII = MI;
01652   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
01653           get(TargetOpcode::COPY), CRReg)
01654     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
01655 
01656   if (MIOpC != NewOpC) {
01657     // We need to be careful here: we're replacing one instruction with
01658     // another, and we need to make sure that we get all of the right
01659     // implicit uses and defs. On the other hand, the caller may be holding
01660     // an iterator to this instruction, and so we can't delete it (this is
01661     // specifically the case if this is the instruction directly after the
01662     // compare).
01663 
01664     const MCInstrDesc &NewDesc = get(NewOpC);
01665     MI->setDesc(NewDesc);
01666 
01667     if (NewDesc.ImplicitDefs)
01668       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
01669            *ImpDefs; ++ImpDefs)
01670         if (!MI->definesRegister(*ImpDefs))
01671           MI->addOperand(*MI->getParent()->getParent(),
01672                          MachineOperand::CreateReg(*ImpDefs, true, true));
01673     if (NewDesc.ImplicitUses)
01674       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
01675            *ImpUses; ++ImpUses)
01676         if (!MI->readsRegister(*ImpUses))
01677           MI->addOperand(*MI->getParent()->getParent(),
01678                          MachineOperand::CreateReg(*ImpUses, false, true));
01679   }
01680 
01681   // Modify the condition code of operands in OperandsToUpdate.
01682   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
01683   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
01684   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
01685     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
01686 
01687   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
01688     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
01689 
01690   return true;
01691 }
01692 
01693 /// GetInstSize - Return the number of bytes of code the specified
01694 /// instruction may be.  This returns the maximum number of bytes.
01695 ///
01696 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
01697   unsigned Opcode = MI->getOpcode();
01698 
01699   if (Opcode == PPC::INLINEASM) {
01700     const MachineFunction *MF = MI->getParent()->getParent();
01701     const char *AsmStr = MI->getOperand(0).getSymbolName();
01702     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
01703   } else if (Opcode == TargetOpcode::STACKMAP) {
01704     return MI->getOperand(1).getImm();
01705   } else if (Opcode == TargetOpcode::PATCHPOINT) {
01706     PatchPointOpers Opers(MI);
01707     return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
01708   } else {
01709     const MCInstrDesc &Desc = get(Opcode);
01710     return Desc.getSize();
01711   }
01712 }
01713