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