LLVM API Documentation

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/SlotIndexes.h"
00031 #include "llvm/MC/MCAsmInfo.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/TargetRegistry.h"
00036 #include "llvm/Support/raw_ostream.h"
00037 
00038 #define GET_INSTRMAP_INFO
00039 #define GET_INSTRINFO_CTOR_DTOR
00040 #include "PPCGenInstrInfo.inc"
00041 
00042 using namespace llvm;
00043 
00044 static cl::
00045 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
00046             cl::desc("Disable analysis for CTR loops"));
00047 
00048 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
00049 cl::desc("Disable compare instruction optimization"), cl::Hidden);
00050 
00051 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
00052 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
00053 
00054 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
00055 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
00056 cl::Hidden);
00057 
00058 // Pin the vtable to this file.
00059 void PPCInstrInfo::anchor() {}
00060 
00061 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
00062   : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
00063     TM(tm), RI(*TM.getSubtargetImpl()) {}
00064 
00065 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
00066 /// this target when scheduling the DAG.
00067 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
00068   const TargetMachine *TM,
00069   const ScheduleDAG *DAG) const {
00070   unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
00071   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
00072       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
00073     const InstrItineraryData *II = TM->getInstrItineraryData();
00074     return new ScoreboardHazardRecognizer(II, DAG);
00075   }
00076 
00077   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
00078 }
00079 
00080 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
00081 /// to use for this target when scheduling the DAG.
00082 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
00083   const InstrItineraryData *II,
00084   const ScheduleDAG *DAG) const {
00085   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
00086 
00087   if (Directive == PPC::DIR_PWR7)
00088     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
00089 
00090   // Most subtargets use a PPC970 recognizer.
00091   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
00092       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
00093     assert(TM.getInstrInfo() && "No InstrInfo?");
00094 
00095     return new PPCHazardRecognizer970(TM);
00096   }
00097 
00098   return new ScoreboardHazardRecognizer(II, DAG);
00099 }
00100 
00101 
00102 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
00103                                     const MachineInstr *DefMI, unsigned DefIdx,
00104                                     const MachineInstr *UseMI,
00105                                     unsigned UseIdx) const {
00106   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
00107                                                    UseMI, UseIdx);
00108 
00109   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
00110   unsigned Reg = DefMO.getReg();
00111 
00112   const TargetRegisterInfo *TRI = &getRegisterInfo();
00113   bool IsRegCR;
00114   if (TRI->isVirtualRegister(Reg)) {
00115     const MachineRegisterInfo *MRI =
00116       &DefMI->getParent()->getParent()->getRegInfo();
00117     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
00118               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
00119   } else {
00120     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
00121               PPC::CRBITRCRegClass.contains(Reg);
00122   }
00123 
00124   if (UseMI->isBranch() && IsRegCR) {
00125     if (Latency < 0)
00126       Latency = getInstrLatency(ItinData, DefMI);
00127 
00128     // On some cores, there is an additional delay between writing to a condition
00129     // register, and using it from a branch.
00130     unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
00131     switch (Directive) {
00132     default: break;
00133     case PPC::DIR_7400:
00134     case PPC::DIR_750:
00135     case PPC::DIR_970:
00136     case PPC::DIR_E5500:
00137     case PPC::DIR_PWR4:
00138     case PPC::DIR_PWR5:
00139     case PPC::DIR_PWR5X:
00140     case PPC::DIR_PWR6:
00141     case PPC::DIR_PWR6X:
00142     case PPC::DIR_PWR7:
00143       Latency += 2;
00144       break;
00145     }
00146   }
00147 
00148   return Latency;
00149 }
00150 
00151 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
00152 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
00153                                          unsigned &SrcReg, unsigned &DstReg,
00154                                          unsigned &SubIdx) const {
00155   switch (MI.getOpcode()) {
00156   default: return false;
00157   case PPC::EXTSW:
00158   case PPC::EXTSW_32_64:
00159     SrcReg = MI.getOperand(1).getReg();
00160     DstReg = MI.getOperand(0).getReg();
00161     SubIdx = PPC::sub_32;
00162     return true;
00163   }
00164 }
00165 
00166 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
00167                                            int &FrameIndex) const {
00168   // Note: This list must be kept consistent with LoadRegFromStackSlot.
00169   switch (MI->getOpcode()) {
00170   default: break;
00171   case PPC::LD:
00172   case PPC::LWZ:
00173   case PPC::LFS:
00174   case PPC::LFD:
00175   case PPC::RESTORE_CR:
00176   case PPC::RESTORE_CRBIT:
00177   case PPC::LVX:
00178   case PPC::LXVD2X:
00179   case PPC::RESTORE_VRSAVE:
00180     // Check for the operands added by addFrameReference (the immediate is the
00181     // offset which defaults to 0).
00182     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00183         MI->getOperand(2).isFI()) {
00184       FrameIndex = MI->getOperand(2).getIndex();
00185       return MI->getOperand(0).getReg();
00186     }
00187     break;
00188   }
00189   return 0;
00190 }
00191 
00192 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
00193                                           int &FrameIndex) const {
00194   // Note: This list must be kept consistent with StoreRegToStackSlot.
00195   switch (MI->getOpcode()) {
00196   default: break;
00197   case PPC::STD:
00198   case PPC::STW:
00199   case PPC::STFS:
00200   case PPC::STFD:
00201   case PPC::SPILL_CR:
00202   case PPC::SPILL_CRBIT:
00203   case PPC::STVX:
00204   case PPC::STXVD2X:
00205   case PPC::SPILL_VRSAVE:
00206     // Check for the operands added by addFrameReference (the immediate is the
00207     // offset which defaults to 0).
00208     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00209         MI->getOperand(2).isFI()) {
00210       FrameIndex = MI->getOperand(2).getIndex();
00211       return MI->getOperand(0).getReg();
00212     }
00213     break;
00214   }
00215   return 0;
00216 }
00217 
00218 // commuteInstruction - We can commute rlwimi instructions, but only if the
00219 // rotate amt is zero.  We also have to munge the immediates a bit.
00220 MachineInstr *
00221 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
00222   MachineFunction &MF = *MI->getParent()->getParent();
00223 
00224   // Normal instructions can be commuted the obvious way.
00225   if (MI->getOpcode() != PPC::RLWIMI &&
00226       MI->getOpcode() != PPC::RLWIMIo &&
00227       MI->getOpcode() != PPC::RLWIMI8 &&
00228       MI->getOpcode() != PPC::RLWIMI8o)
00229     return TargetInstrInfo::commuteInstruction(MI, NewMI);
00230 
00231   // Cannot commute if it has a non-zero rotate count.
00232   if (MI->getOperand(3).getImm() != 0)
00233     return 0;
00234 
00235   // If we have a zero rotate count, we have:
00236   //   M = mask(MB,ME)
00237   //   Op0 = (Op1 & ~M) | (Op2 & M)
00238   // Change this to:
00239   //   M = mask((ME+1)&31, (MB-1)&31)
00240   //   Op0 = (Op2 & ~M) | (Op1 & M)
00241 
00242   // Swap op1/op2
00243   unsigned Reg0 = MI->getOperand(0).getReg();
00244   unsigned Reg1 = MI->getOperand(1).getReg();
00245   unsigned Reg2 = MI->getOperand(2).getReg();
00246   unsigned SubReg1 = MI->getOperand(1).getSubReg();
00247   unsigned SubReg2 = MI->getOperand(2).getSubReg();
00248   bool Reg1IsKill = MI->getOperand(1).isKill();
00249   bool Reg2IsKill = MI->getOperand(2).isKill();
00250   bool ChangeReg0 = false;
00251   // If machine instrs are no longer in two-address forms, update
00252   // destination register as well.
00253   if (Reg0 == Reg1) {
00254     // Must be two address instruction!
00255     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
00256            "Expecting a two-address instruction!");
00257     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
00258     Reg2IsKill = false;
00259     ChangeReg0 = true;
00260   }
00261 
00262   // Masks.
00263   unsigned MB = MI->getOperand(4).getImm();
00264   unsigned ME = MI->getOperand(5).getImm();
00265 
00266   if (NewMI) {
00267     // Create a new instruction.
00268     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
00269     bool Reg0IsDead = MI->getOperand(0).isDead();
00270     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
00271       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
00272       .addReg(Reg2, getKillRegState(Reg2IsKill))
00273       .addReg(Reg1, getKillRegState(Reg1IsKill))
00274       .addImm((ME+1) & 31)
00275       .addImm((MB-1) & 31);
00276   }
00277 
00278   if (ChangeReg0) {
00279     MI->getOperand(0).setReg(Reg2);
00280     MI->getOperand(0).setSubReg(SubReg2);
00281   }
00282   MI->getOperand(2).setReg(Reg1);
00283   MI->getOperand(1).setReg(Reg2);
00284   MI->getOperand(2).setSubReg(SubReg1);
00285   MI->getOperand(1).setSubReg(SubReg2);
00286   MI->getOperand(2).setIsKill(Reg1IsKill);
00287   MI->getOperand(1).setIsKill(Reg2IsKill);
00288 
00289   // Swap the mask around.
00290   MI->getOperand(4).setImm((ME+1) & 31);
00291   MI->getOperand(5).setImm((MB-1) & 31);
00292   return MI;
00293 }
00294 
00295 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
00296                                          unsigned &SrcOpIdx2) const {
00297   // For VSX A-Type FMA instructions, it is the first two operands that can be
00298   // commuted, however, because the non-encoded tied input operand is listed
00299   // first, the operands to swap are actually the second and third.
00300 
00301   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
00302   if (AltOpc == -1)
00303     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
00304 
00305   SrcOpIdx1 = 2;
00306   SrcOpIdx2 = 3;
00307   return true;
00308 }
00309 
00310 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
00311                               MachineBasicBlock::iterator MI) const {
00312   // This function is used for scheduling, and the nop wanted here is the type
00313   // that terminates dispatch groups on the POWER cores.
00314   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
00315   unsigned Opcode;
00316   switch (Directive) {
00317   default:            Opcode = PPC::NOP; break;
00318   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
00319   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
00320   }
00321 
00322   DebugLoc DL;
00323   BuildMI(MBB, MI, DL, get(Opcode));
00324 }
00325 
00326 // Branch analysis.
00327 // Note: If the condition register is set to CTR or CTR8 then this is a
00328 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
00329 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
00330                                  MachineBasicBlock *&FBB,
00331                                  SmallVectorImpl<MachineOperand> &Cond,
00332                                  bool AllowModify) const {
00333   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
00334 
00335   // If the block has no terminators, it just falls into the block after it.
00336   MachineBasicBlock::iterator I = MBB.end();
00337   if (I == MBB.begin())
00338     return false;
00339   --I;
00340   while (I->isDebugValue()) {
00341     if (I == MBB.begin())
00342       return false;
00343     --I;
00344   }
00345   if (!isUnpredicatedTerminator(I))
00346     return false;
00347 
00348   // Get the last instruction in the block.
00349   MachineInstr *LastInst = I;
00350 
00351   // If there is only one terminator instruction, process it.
00352   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
00353     if (LastInst->getOpcode() == PPC::B) {
00354       if (!LastInst->getOperand(0).isMBB())
00355         return true;
00356       TBB = LastInst->getOperand(0).getMBB();
00357       return false;
00358     } else if (LastInst->getOpcode() == PPC::BCC) {
00359       if (!LastInst->getOperand(2).isMBB())
00360         return true;
00361       // Block ends with fall-through condbranch.
00362       TBB = LastInst->getOperand(2).getMBB();
00363       Cond.push_back(LastInst->getOperand(0));
00364       Cond.push_back(LastInst->getOperand(1));
00365       return false;
00366     } else if (LastInst->getOpcode() == PPC::BC) {
00367       if (!LastInst->getOperand(1).isMBB())
00368         return true;
00369       // Block ends with fall-through condbranch.
00370       TBB = LastInst->getOperand(1).getMBB();
00371       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00372       Cond.push_back(LastInst->getOperand(0));
00373       return false;
00374     } else if (LastInst->getOpcode() == PPC::BCn) {
00375       if (!LastInst->getOperand(1).isMBB())
00376         return true;
00377       // Block ends with fall-through condbranch.
00378       TBB = LastInst->getOperand(1).getMBB();
00379       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00380       Cond.push_back(LastInst->getOperand(0));
00381       return false;
00382     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
00383                LastInst->getOpcode() == PPC::BDNZ) {
00384       if (!LastInst->getOperand(0).isMBB())
00385         return true;
00386       if (DisableCTRLoopAnal)
00387         return true;
00388       TBB = LastInst->getOperand(0).getMBB();
00389       Cond.push_back(MachineOperand::CreateImm(1));
00390       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00391                                                true));
00392       return false;
00393     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
00394                LastInst->getOpcode() == PPC::BDZ) {
00395       if (!LastInst->getOperand(0).isMBB())
00396         return true;
00397       if (DisableCTRLoopAnal)
00398         return true;
00399       TBB = LastInst->getOperand(0).getMBB();
00400       Cond.push_back(MachineOperand::CreateImm(0));
00401       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00402                                                true));
00403       return false;
00404     }
00405 
00406     // Otherwise, don't know what this is.
00407     return true;
00408   }
00409 
00410   // Get the instruction before it if it's a terminator.
00411   MachineInstr *SecondLastInst = I;
00412 
00413   // If there are three terminators, we don't know what sort of block this is.
00414   if (SecondLastInst && I != MBB.begin() &&
00415       isUnpredicatedTerminator(--I))
00416     return true;
00417 
00418   // If the block ends with PPC::B and PPC:BCC, handle it.
00419   if (SecondLastInst->getOpcode() == PPC::BCC &&
00420       LastInst->getOpcode() == PPC::B) {
00421     if (!SecondLastInst->getOperand(2).isMBB() ||
00422         !LastInst->getOperand(0).isMBB())
00423       return true;
00424     TBB =  SecondLastInst->getOperand(2).getMBB();
00425     Cond.push_back(SecondLastInst->getOperand(0));
00426     Cond.push_back(SecondLastInst->getOperand(1));
00427     FBB = LastInst->getOperand(0).getMBB();
00428     return false;
00429   } else if (SecondLastInst->getOpcode() == PPC::BC &&
00430       LastInst->getOpcode() == PPC::B) {
00431     if (!SecondLastInst->getOperand(1).isMBB() ||
00432         !LastInst->getOperand(0).isMBB())
00433       return true;
00434     TBB =  SecondLastInst->getOperand(1).getMBB();
00435     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00436     Cond.push_back(SecondLastInst->getOperand(0));
00437     FBB = LastInst->getOperand(0).getMBB();
00438     return false;
00439   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
00440       LastInst->getOpcode() == PPC::B) {
00441     if (!SecondLastInst->getOperand(1).isMBB() ||
00442         !LastInst->getOperand(0).isMBB())
00443       return true;
00444     TBB =  SecondLastInst->getOperand(1).getMBB();
00445     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00446     Cond.push_back(SecondLastInst->getOperand(0));
00447     FBB = LastInst->getOperand(0).getMBB();
00448     return false;
00449   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
00450               SecondLastInst->getOpcode() == PPC::BDNZ) &&
00451       LastInst->getOpcode() == PPC::B) {
00452     if (!SecondLastInst->getOperand(0).isMBB() ||
00453         !LastInst->getOperand(0).isMBB())
00454       return true;
00455     if (DisableCTRLoopAnal)
00456       return true;
00457     TBB = SecondLastInst->getOperand(0).getMBB();
00458     Cond.push_back(MachineOperand::CreateImm(1));
00459     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00460                                              true));
00461     FBB = LastInst->getOperand(0).getMBB();
00462     return false;
00463   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
00464               SecondLastInst->getOpcode() == PPC::BDZ) &&
00465       LastInst->getOpcode() == PPC::B) {
00466     if (!SecondLastInst->getOperand(0).isMBB() ||
00467         !LastInst->getOperand(0).isMBB())
00468       return true;
00469     if (DisableCTRLoopAnal)
00470       return true;
00471     TBB = SecondLastInst->getOperand(0).getMBB();
00472     Cond.push_back(MachineOperand::CreateImm(0));
00473     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00474                                              true));
00475     FBB = LastInst->getOperand(0).getMBB();
00476     return false;
00477   }
00478 
00479   // If the block ends with two PPC:Bs, handle it.  The second one is not
00480   // executed, so remove it.
00481   if (SecondLastInst->getOpcode() == PPC::B &&
00482       LastInst->getOpcode() == PPC::B) {
00483     if (!SecondLastInst->getOperand(0).isMBB())
00484       return true;
00485     TBB = SecondLastInst->getOperand(0).getMBB();
00486     I = LastInst;
00487     if (AllowModify)
00488       I->eraseFromParent();
00489     return false;
00490   }
00491 
00492   // Otherwise, can't handle this.
00493   return true;
00494 }
00495 
00496 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
00497   MachineBasicBlock::iterator I = MBB.end();
00498   if (I == MBB.begin()) return 0;
00499   --I;
00500   while (I->isDebugValue()) {
00501     if (I == MBB.begin())
00502       return 0;
00503     --I;
00504   }
00505   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
00506       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00507       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00508       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00509     return 0;
00510 
00511   // Remove the branch.
00512   I->eraseFromParent();
00513 
00514   I = MBB.end();
00515 
00516   if (I == MBB.begin()) return 1;
00517   --I;
00518   if (I->getOpcode() != PPC::BCC &&
00519       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00520       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00521       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00522     return 1;
00523 
00524   // Remove the branch.
00525   I->eraseFromParent();
00526   return 2;
00527 }
00528 
00529 unsigned
00530 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
00531                            MachineBasicBlock *FBB,
00532                            const SmallVectorImpl<MachineOperand> &Cond,
00533                            DebugLoc DL) const {
00534   // Shouldn't be a fall through.
00535   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
00536   assert((Cond.size() == 2 || Cond.size() == 0) &&
00537          "PPC branch conditions have two components!");
00538 
00539   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
00540 
00541   // One-way branch.
00542   if (FBB == 0) {
00543     if (Cond.empty())   // Unconditional branch
00544       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
00545     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00546       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00547                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00548                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00549     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00550       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00551     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00552       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00553     else                // Conditional branch
00554       BuildMI(&MBB, DL, get(PPC::BCC))
00555         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00556     return 1;
00557   }
00558 
00559   // Two-way Conditional Branch.
00560   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00561     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00562                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00563                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00564   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00565     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00566   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00567     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00568   else
00569     BuildMI(&MBB, DL, get(PPC::BCC))
00570       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00571   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
00572   return 2;
00573 }
00574 
00575 // Select analysis.
00576 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
00577                 const SmallVectorImpl<MachineOperand> &Cond,
00578                 unsigned TrueReg, unsigned FalseReg,
00579                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
00580   if (!TM.getSubtargetImpl()->hasISEL())
00581     return false;
00582 
00583   if (Cond.size() != 2)
00584     return false;
00585 
00586   // If this is really a bdnz-like condition, then it cannot be turned into a
00587   // select.
00588   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00589     return false;
00590 
00591   // Check register classes.
00592   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00593   const TargetRegisterClass *RC =
00594     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00595   if (!RC)
00596     return false;
00597 
00598   // isel is for regular integer GPRs only.
00599   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
00600       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
00601       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
00602       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
00603     return false;
00604 
00605   // FIXME: These numbers are for the A2, how well they work for other cores is
00606   // an open question. On the A2, the isel instruction has a 2-cycle latency
00607   // but single-cycle throughput. These numbers are used in combination with
00608   // the MispredictPenalty setting from the active SchedMachineModel.
00609   CondCycles = 1;
00610   TrueCycles = 1;
00611   FalseCycles = 1;
00612 
00613   return true;
00614 }
00615 
00616 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
00617                                 MachineBasicBlock::iterator MI, DebugLoc dl,
00618                                 unsigned DestReg,
00619                                 const SmallVectorImpl<MachineOperand> &Cond,
00620                                 unsigned TrueReg, unsigned FalseReg) const {
00621   assert(Cond.size() == 2 &&
00622          "PPC branch conditions have two components!");
00623 
00624   assert(TM.getSubtargetImpl()->hasISEL() &&
00625          "Cannot insert select on target without ISEL support");
00626 
00627   // Get the register classes.
00628   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00629   const TargetRegisterClass *RC =
00630     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00631   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
00632 
00633   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
00634                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
00635   assert((Is64Bit ||
00636           PPC::GPRCRegClass.hasSubClassEq(RC) ||
00637           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
00638          "isel is for regular integer GPRs only");
00639 
00640   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
00641   unsigned SelectPred = Cond[0].getImm();
00642 
00643   unsigned SubIdx;
00644   bool SwapOps;
00645   switch (SelectPred) {
00646   default: llvm_unreachable("invalid predicate for isel");
00647   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
00648   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
00649   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
00650   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
00651   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
00652   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
00653   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
00654   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
00655   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
00656   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
00657   }
00658 
00659   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
00660            SecondReg = SwapOps ? TrueReg  : FalseReg;
00661 
00662   // The first input register of isel cannot be r0. If it is a member
00663   // of a register class that can be r0, then copy it first (the
00664   // register allocator should eliminate the copy).
00665   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
00666       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
00667     const TargetRegisterClass *FirstRC =
00668       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
00669         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
00670     unsigned OldFirstReg = FirstReg;
00671     FirstReg = MRI.createVirtualRegister(FirstRC);
00672     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
00673       .addReg(OldFirstReg);
00674   }
00675 
00676   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
00677     .addReg(FirstReg).addReg(SecondReg)
00678     .addReg(Cond[1].getReg(), 0, SubIdx);
00679 }
00680 
00681 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
00682                                MachineBasicBlock::iterator I, DebugLoc DL,
00683                                unsigned DestReg, unsigned SrcReg,
00684                                bool KillSrc) const {
00685   // We can end up with self copies and similar things as a result of VSX copy
00686   // legalization. Promote them here.
00687   const TargetRegisterInfo *TRI = &getRegisterInfo();
00688   if (PPC::F8RCRegClass.contains(DestReg) &&
00689       PPC::VSLRCRegClass.contains(SrcReg)) {
00690     unsigned SuperReg =
00691       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
00692 
00693     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00694       llvm_unreachable("nop VSX copy");
00695 
00696     DestReg = SuperReg;
00697   } else if (PPC::VRRCRegClass.contains(DestReg) &&
00698              PPC::VSHRCRegClass.contains(SrcReg)) {
00699     unsigned SuperReg =
00700       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
00701 
00702     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00703       llvm_unreachable("nop VSX copy");
00704 
00705     DestReg = SuperReg;
00706   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
00707              PPC::VSLRCRegClass.contains(DestReg)) {
00708     unsigned SuperReg =
00709       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
00710 
00711     if (VSXSelfCopyCrash && DestReg == SuperReg)
00712       llvm_unreachable("nop VSX copy");
00713 
00714     SrcReg = SuperReg;
00715   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
00716              PPC::VSHRCRegClass.contains(DestReg)) {
00717     unsigned SuperReg =
00718       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
00719 
00720     if (VSXSelfCopyCrash && DestReg == SuperReg)
00721       llvm_unreachable("nop VSX copy");
00722 
00723     SrcReg = SuperReg;
00724   }
00725 
00726   unsigned Opc;
00727   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
00728     Opc = PPC::OR;
00729   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
00730     Opc = PPC::OR8;
00731   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
00732     Opc = PPC::FMR;
00733   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
00734     Opc = PPC::MCRF;
00735   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
00736     Opc = PPC::VOR;
00737   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
00738     // There are two different ways this can be done:
00739     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
00740     //      issue in VSU pipeline 0.
00741     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
00742     //      can go to either pipeline.
00743     // We'll always use xxlor here, because in practically all cases where
00744     // copies are generated, they are close enough to some use that the
00745     // lower-latency form is preferable.
00746     Opc = PPC::XXLOR;
00747   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
00748     Opc = PPC::XXLORf;
00749   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
00750     Opc = PPC::CROR;
00751   else
00752     llvm_unreachable("Impossible reg-to-reg copy");
00753 
00754   const MCInstrDesc &MCID = get(Opc);
00755   if (MCID.getNumOperands() == 3)
00756     BuildMI(MBB, I, DL, MCID, DestReg)
00757       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
00758   else
00759     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
00760 }
00761 
00762 // This function returns true if a CR spill is necessary and false otherwise.
00763 bool
00764 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
00765                                   unsigned SrcReg, bool isKill,
00766                                   int FrameIdx,
00767                                   const TargetRegisterClass *RC,
00768                                   SmallVectorImpl<MachineInstr*> &NewMIs,
00769                                   bool &NonRI, bool &SpillsVRS) const{
00770   // Note: If additional store instructions are added here,
00771   // update isStoreToStackSlot.
00772 
00773   DebugLoc DL;
00774   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00775       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00776     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
00777                                        .addReg(SrcReg,
00778                                                getKillRegState(isKill)),
00779                                        FrameIdx));
00780   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00781              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00782     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
00783                                        .addReg(SrcReg,
00784                                                getKillRegState(isKill)),
00785                                        FrameIdx));
00786   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00787     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
00788                                        .addReg(SrcReg,
00789                                                getKillRegState(isKill)),
00790                                        FrameIdx));
00791   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00792     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
00793                                        .addReg(SrcReg,
00794                                                getKillRegState(isKill)),
00795                                        FrameIdx));
00796   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00797     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
00798                                        .addReg(SrcReg,
00799                                                getKillRegState(isKill)),
00800                                        FrameIdx));
00801     return true;
00802   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00803     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
00804                                        .addReg(SrcReg,
00805                                                getKillRegState(isKill)),
00806                                        FrameIdx));
00807     return true;
00808   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00809     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
00810                                        .addReg(SrcReg,
00811                                                getKillRegState(isKill)),
00812                                        FrameIdx));
00813     NonRI = true;
00814   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00815     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
00816                                        .addReg(SrcReg,
00817                                                getKillRegState(isKill)),
00818                                        FrameIdx));
00819     NonRI = true;
00820   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00821     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
00822                                        .addReg(SrcReg,
00823                                                getKillRegState(isKill)),
00824                                        FrameIdx));
00825     NonRI = true;
00826   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00827     assert(TM.getSubtargetImpl()->isDarwin() &&
00828            "VRSAVE only needs spill/restore on Darwin");
00829     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
00830                                        .addReg(SrcReg,
00831                                                getKillRegState(isKill)),
00832                                        FrameIdx));
00833     SpillsVRS = true;
00834   } else {
00835     llvm_unreachable("Unknown regclass!");
00836   }
00837 
00838   return false;
00839 }
00840 
00841 void
00842 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
00843                                   MachineBasicBlock::iterator MI,
00844                                   unsigned SrcReg, bool isKill, int FrameIdx,
00845                                   const TargetRegisterClass *RC,
00846                                   const TargetRegisterInfo *TRI) const {
00847   MachineFunction &MF = *MBB.getParent();
00848   SmallVector<MachineInstr*, 4> NewMIs;
00849 
00850   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00851   FuncInfo->setHasSpills();
00852 
00853   bool NonRI = false, SpillsVRS = false;
00854   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
00855                           NonRI, SpillsVRS))
00856     FuncInfo->setSpillsCR();
00857 
00858   if (SpillsVRS)
00859     FuncInfo->setSpillsVRSAVE();
00860 
00861   if (NonRI)
00862     FuncInfo->setHasNonRISpills();
00863 
00864   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00865     MBB.insert(MI, NewMIs[i]);
00866 
00867   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00868   MachineMemOperand *MMO =
00869     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00870                             MachineMemOperand::MOStore,
00871                             MFI.getObjectSize(FrameIdx),
00872                             MFI.getObjectAlignment(FrameIdx));
00873   NewMIs.back()->addMemOperand(MF, MMO);
00874 }
00875 
00876 bool
00877 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
00878                                    unsigned DestReg, int FrameIdx,
00879                                    const TargetRegisterClass *RC,
00880                                    SmallVectorImpl<MachineInstr*> &NewMIs,
00881                                    bool &NonRI, bool &SpillsVRS) const{
00882   // Note: If additional load instructions are added here,
00883   // update isLoadFromStackSlot.
00884 
00885   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00886       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00887     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
00888                                                DestReg), FrameIdx));
00889   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00890              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00891     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
00892                                        FrameIdx));
00893   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00894     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
00895                                        FrameIdx));
00896   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00897     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
00898                                        FrameIdx));
00899   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00900     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00901                                                get(PPC::RESTORE_CR), DestReg),
00902                                        FrameIdx));
00903     return true;
00904   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00905     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00906                                                get(PPC::RESTORE_CRBIT), DestReg),
00907                                        FrameIdx));
00908     return true;
00909   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00910     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
00911                                        FrameIdx));
00912     NonRI = true;
00913   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00914     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
00915                                        FrameIdx));
00916     NonRI = true;
00917   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00918     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
00919                                        FrameIdx));
00920     NonRI = true;
00921   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00922     assert(TM.getSubtargetImpl()->isDarwin() &&
00923            "VRSAVE only needs spill/restore on Darwin");
00924     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00925                                                get(PPC::RESTORE_VRSAVE),
00926                                                DestReg),
00927                                        FrameIdx));
00928     SpillsVRS = true;
00929   } else {
00930     llvm_unreachable("Unknown regclass!");
00931   }
00932 
00933   return false;
00934 }
00935 
00936 void
00937 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
00938                                    MachineBasicBlock::iterator MI,
00939                                    unsigned DestReg, int FrameIdx,
00940                                    const TargetRegisterClass *RC,
00941                                    const TargetRegisterInfo *TRI) const {
00942   MachineFunction &MF = *MBB.getParent();
00943   SmallVector<MachineInstr*, 4> NewMIs;
00944   DebugLoc DL;
00945   if (MI != MBB.end()) DL = MI->getDebugLoc();
00946 
00947   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00948   FuncInfo->setHasSpills();
00949 
00950   bool NonRI = false, SpillsVRS = false;
00951   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
00952                            NonRI, SpillsVRS))
00953     FuncInfo->setSpillsCR();
00954 
00955   if (SpillsVRS)
00956     FuncInfo->setSpillsVRSAVE();
00957 
00958   if (NonRI)
00959     FuncInfo->setHasNonRISpills();
00960 
00961   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00962     MBB.insert(MI, NewMIs[i]);
00963 
00964   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00965   MachineMemOperand *MMO =
00966     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00967                             MachineMemOperand::MOLoad,
00968                             MFI.getObjectSize(FrameIdx),
00969                             MFI.getObjectAlignment(FrameIdx));
00970   NewMIs.back()->addMemOperand(MF, MMO);
00971 }
00972 
00973 bool PPCInstrInfo::
00974 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
00975   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
00976   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
00977     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
00978   else
00979     // Leave the CR# the same, but invert the condition.
00980     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
00981   return false;
00982 }
00983 
00984 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
00985                              unsigned Reg, MachineRegisterInfo *MRI) const {
00986   // For some instructions, it is legal to fold ZERO into the RA register field.
00987   // A zero immediate should always be loaded with a single li.
00988   unsigned DefOpc = DefMI->getOpcode();
00989   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
00990     return false;
00991   if (!DefMI->getOperand(1).isImm())
00992     return false;
00993   if (DefMI->getOperand(1).getImm() != 0)
00994     return false;
00995 
00996   // Note that we cannot here invert the arguments of an isel in order to fold
00997   // a ZERO into what is presented as the second argument. All we have here
00998   // is the condition bit, and that might come from a CR-logical bit operation.
00999 
01000   const MCInstrDesc &UseMCID = UseMI->getDesc();
01001 
01002   // Only fold into real machine instructions.
01003   if (UseMCID.isPseudo())
01004     return false;
01005 
01006   unsigned UseIdx;
01007   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
01008     if (UseMI->getOperand(UseIdx).isReg() &&
01009         UseMI->getOperand(UseIdx).getReg() == Reg)
01010       break;
01011 
01012   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
01013   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
01014 
01015   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
01016 
01017   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
01018   // register (which might also be specified as a pointer class kind).
01019   if (UseInfo->isLookupPtrRegClass()) {
01020     if (UseInfo->RegClass /* Kind */ != 1)
01021       return false;
01022   } else {
01023     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
01024         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
01025       return false;
01026   }
01027 
01028   // Make sure this is not tied to an output register (or otherwise
01029   // constrained). This is true for ST?UX registers, for example, which
01030   // are tied to their output registers.
01031   if (UseInfo->Constraints != 0)
01032     return false;
01033 
01034   unsigned ZeroReg;
01035   if (UseInfo->isLookupPtrRegClass()) {
01036     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
01037     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
01038   } else {
01039     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
01040               PPC::ZERO8 : PPC::ZERO;
01041   }
01042 
01043   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
01044   UseMI->getOperand(UseIdx).setReg(ZeroReg);
01045 
01046   if (DeleteDef)
01047     DefMI->eraseFromParent();
01048 
01049   return true;
01050 }
01051 
01052 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
01053   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01054        I != IE; ++I)
01055     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
01056       return true;
01057   return false;
01058 }
01059 
01060 // We should make sure that, if we're going to predicate both sides of a
01061 // condition (a diamond), that both sides don't define the counter register. We
01062 // can predicate counter-decrement-based branches, but while that predicates
01063 // the branching, it does not predicate the counter decrement. If we tried to
01064 // merge the triangle into one predicated block, we'd decrement the counter
01065 // twice.
01066 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
01067                      unsigned NumT, unsigned ExtraT,
01068                      MachineBasicBlock &FMBB,
01069                      unsigned NumF, unsigned ExtraF,
01070                      const BranchProbability &Probability) const {
01071   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
01072 }
01073 
01074 
01075 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
01076   // The predicated branches are identified by their type, not really by the
01077   // explicit presence of a predicate. Furthermore, some of them can be
01078   // predicated more than once. Because if conversion won't try to predicate
01079   // any instruction which already claims to be predicated (by returning true
01080   // here), always return false. In doing so, we let isPredicable() be the
01081   // final word on whether not the instruction can be (further) predicated.
01082 
01083   return false;
01084 }
01085 
01086 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
01087   if (!MI->isTerminator())
01088     return false;
01089 
01090   // Conditional branch is a special case.
01091   if (MI->isBranch() && !MI->isBarrier())
01092     return true;
01093 
01094   return !isPredicated(MI);
01095 }
01096 
01097 bool PPCInstrInfo::PredicateInstruction(
01098                      MachineInstr *MI,
01099                      const SmallVectorImpl<MachineOperand> &Pred) const {
01100   unsigned OpC = MI->getOpcode();
01101   if (OpC == PPC::BLR) {
01102     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01103       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
01104       MI->setDesc(get(Pred[0].getImm() ?
01105                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
01106                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
01107     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01108       MI->setDesc(get(PPC::BCLR));
01109       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01110         .addReg(Pred[1].getReg());
01111     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01112       MI->setDesc(get(PPC::BCLRn));
01113       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01114         .addReg(Pred[1].getReg());
01115     } else {
01116       MI->setDesc(get(PPC::BCCLR));
01117       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01118         .addImm(Pred[0].getImm())
01119         .addReg(Pred[1].getReg());
01120     }
01121 
01122     return true;
01123   } else if (OpC == PPC::B) {
01124     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01125       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
01126       MI->setDesc(get(Pred[0].getImm() ?
01127                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01128                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
01129     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01130       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01131       MI->RemoveOperand(0);
01132 
01133       MI->setDesc(get(PPC::BC));
01134       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01135         .addReg(Pred[1].getReg())
01136         .addMBB(MBB);
01137     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01138       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01139       MI->RemoveOperand(0);
01140 
01141       MI->setDesc(get(PPC::BCn));
01142       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01143         .addReg(Pred[1].getReg())
01144         .addMBB(MBB);
01145     } else {
01146       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01147       MI->RemoveOperand(0);
01148 
01149       MI->setDesc(get(PPC::BCC));
01150       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01151         .addImm(Pred[0].getImm())
01152         .addReg(Pred[1].getReg())
01153         .addMBB(MBB);
01154     }
01155 
01156     return true;
01157   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
01158              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
01159     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
01160       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
01161 
01162     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
01163     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
01164 
01165     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01166       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
01167                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
01168       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01169         .addReg(Pred[1].getReg());
01170       return true;
01171     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01172       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
01173                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
01174       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01175         .addReg(Pred[1].getReg());
01176       return true;
01177     }
01178 
01179     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
01180                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
01181     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01182       .addImm(Pred[0].getImm())
01183       .addReg(Pred[1].getReg());
01184     return true;
01185   }
01186 
01187   return false;
01188 }
01189 
01190 bool PPCInstrInfo::SubsumesPredicate(
01191                      const SmallVectorImpl<MachineOperand> &Pred1,
01192                      const SmallVectorImpl<MachineOperand> &Pred2) const {
01193   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
01194   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
01195 
01196   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
01197     return false;
01198   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
01199     return false;
01200 
01201   // P1 can only subsume P2 if they test the same condition register.
01202   if (Pred1[1].getReg() != Pred2[1].getReg())
01203     return false;
01204 
01205   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
01206   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
01207 
01208   if (P1 == P2)
01209     return true;
01210 
01211   // Does P1 subsume P2, e.g. GE subsumes GT.
01212   if (P1 == PPC::PRED_LE &&
01213       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
01214     return true;
01215   if (P1 == PPC::PRED_GE &&
01216       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
01217     return true;
01218 
01219   return false;
01220 }
01221 
01222 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
01223                                     std::vector<MachineOperand> &Pred) const {
01224   // Note: At the present time, the contents of Pred from this function is
01225   // unused by IfConversion. This implementation follows ARM by pushing the
01226   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
01227   // predicate, instructions defining CTR or CTR8 are also included as
01228   // predicate-defining instructions.
01229 
01230   const TargetRegisterClass *RCs[] =
01231     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
01232       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
01233 
01234   bool Found = false;
01235   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01236     const MachineOperand &MO = MI->getOperand(i);
01237     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
01238       const TargetRegisterClass *RC = RCs[c];
01239       if (MO.isReg()) {
01240         if (MO.isDef() && RC->contains(MO.getReg())) {
01241           Pred.push_back(MO);
01242           Found = true;
01243         }
01244       } else if (MO.isRegMask()) {
01245         for (TargetRegisterClass::iterator I = RC->begin(),
01246              IE = RC->end(); I != IE; ++I)
01247           if (MO.clobbersPhysReg(*I)) {
01248             Pred.push_back(MO);
01249             Found = true;
01250           }
01251       }
01252     }
01253   }
01254 
01255   return Found;
01256 }
01257 
01258 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
01259   unsigned OpC = MI->getOpcode();
01260   switch (OpC) {
01261   default:
01262     return false;
01263   case PPC::B:
01264   case PPC::BLR:
01265   case PPC::BCTR:
01266   case PPC::BCTR8:
01267   case PPC::BCTRL:
01268   case PPC::BCTRL8:
01269     return true;
01270   }
01271 }
01272 
01273 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
01274                                   unsigned &SrcReg, unsigned &SrcReg2,
01275                                   int &Mask, int &Value) const {
01276   unsigned Opc = MI->getOpcode();
01277 
01278   switch (Opc) {
01279   default: return false;
01280   case PPC::CMPWI:
01281   case PPC::CMPLWI:
01282   case PPC::CMPDI:
01283   case PPC::CMPLDI:
01284     SrcReg = MI->getOperand(1).getReg();
01285     SrcReg2 = 0;
01286     Value = MI->getOperand(2).getImm();
01287     Mask = 0xFFFF;
01288     return true;
01289   case PPC::CMPW:
01290   case PPC::CMPLW:
01291   case PPC::CMPD:
01292   case PPC::CMPLD:
01293   case PPC::FCMPUS:
01294   case PPC::FCMPUD:
01295     SrcReg = MI->getOperand(1).getReg();
01296     SrcReg2 = MI->getOperand(2).getReg();
01297     return true;
01298   }
01299 }
01300 
01301 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
01302                                         unsigned SrcReg, unsigned SrcReg2,
01303                                         int Mask, int Value,
01304                                         const MachineRegisterInfo *MRI) const {
01305   if (DisableCmpOpt)
01306     return false;
01307 
01308   int OpC = CmpInstr->getOpcode();
01309   unsigned CRReg = CmpInstr->getOperand(0).getReg();
01310 
01311   // FP record forms set CR1 based on the execption status bits, not a
01312   // comparison with zero.
01313   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
01314     return false;
01315 
01316   // The record forms set the condition register based on a signed comparison
01317   // with zero (so says the ISA manual). This is not as straightforward as it
01318   // seems, however, because this is always a 64-bit comparison on PPC64, even
01319   // for instructions that are 32-bit in nature (like slw for example).
01320   // So, on PPC32, for unsigned comparisons, we can use the record forms only
01321   // for equality checks (as those don't depend on the sign). On PPC64,
01322   // we are restricted to equality for unsigned 64-bit comparisons and for
01323   // signed 32-bit comparisons the applicability is more restricted.
01324   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
01325   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
01326   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
01327   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
01328 
01329   // Get the unique definition of SrcReg.
01330   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
01331   if (!MI) return false;
01332   int MIOpC = MI->getOpcode();
01333 
01334   bool equalityOnly = false;
01335   bool noSub = false;
01336   if (isPPC64) {
01337     if (is32BitSignedCompare) {
01338       // We can perform this optimization only if MI is sign-extending.
01339       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
01340           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
01341           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
01342           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
01343           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
01344         noSub = true;
01345       } else
01346         return false;
01347     } else if (is32BitUnsignedCompare) {
01348       // We can perform this optimization, equality only, if MI is
01349       // zero-extending.
01350       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
01351           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
01352           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
01353         noSub = true;
01354         equalityOnly = true;
01355       } else
01356         return false;
01357     } else
01358       equalityOnly = is64BitUnsignedCompare;
01359   } else
01360     equalityOnly = is32BitUnsignedCompare;
01361 
01362   if (equalityOnly) {
01363     // We need to check the uses of the condition register in order to reject
01364     // non-equality comparisons.
01365     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
01366          IE = MRI->use_instr_end(); I != IE; ++I) {
01367       MachineInstr *UseMI = &*I;
01368       if (UseMI->getOpcode() == PPC::BCC) {
01369         unsigned Pred = UseMI->getOperand(0).getImm();
01370         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
01371           return false;
01372       } else if (UseMI->getOpcode() == PPC::ISEL ||
01373                  UseMI->getOpcode() == PPC::ISEL8) {
01374         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
01375         if (SubIdx != PPC::sub_eq)
01376           return false;
01377       } else
01378         return false;
01379     }
01380   }
01381 
01382   MachineBasicBlock::iterator I = CmpInstr;
01383 
01384   // Scan forward to find the first use of the compare.
01385   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
01386        I != EL; ++I) {
01387     bool FoundUse = false;
01388     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
01389          JE = MRI->use_instr_end(); J != JE; ++J)
01390       if (&*J == &*I) {
01391         FoundUse = true;
01392         break;
01393       }
01394 
01395     if (FoundUse)
01396       break;
01397   }
01398 
01399   // There are two possible candidates which can be changed to set CR[01].
01400   // One is MI, the other is a SUB instruction.
01401   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
01402   MachineInstr *Sub = NULL;
01403   if (SrcReg2 != 0)
01404     // MI is not a candidate for CMPrr.
01405     MI = NULL;
01406   // FIXME: Conservatively refuse to convert an instruction which isn't in the
01407   // same BB as the comparison. This is to allow the check below to avoid calls
01408   // (and other explicit clobbers); instead we should really check for these
01409   // more explicitly (in at least a few predecessors).
01410   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
01411     // PPC does not have a record-form SUBri.
01412     return false;
01413   }
01414 
01415   // Search for Sub.
01416   const TargetRegisterInfo *TRI = &getRegisterInfo();
01417   --I;
01418 
01419   // Get ready to iterate backward from CmpInstr.
01420   MachineBasicBlock::iterator E = MI,
01421                               B = CmpInstr->getParent()->begin();
01422 
01423   for (; I != E && !noSub; --I) {
01424     const MachineInstr &Instr = *I;
01425     unsigned IOpC = Instr.getOpcode();
01426 
01427     if (&*I != CmpInstr && (
01428         Instr.modifiesRegister(PPC::CR0, TRI) ||
01429         Instr.readsRegister(PPC::CR0, TRI)))
01430       // This instruction modifies or uses the record condition register after
01431       // the one we want to change. While we could do this transformation, it
01432       // would likely not be profitable. This transformation removes one
01433       // instruction, and so even forcing RA to generate one move probably
01434       // makes it unprofitable.
01435       return false;
01436 
01437     // Check whether CmpInstr can be made redundant by the current instruction.
01438     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
01439          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
01440         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
01441         ((Instr.getOperand(1).getReg() == SrcReg &&
01442           Instr.getOperand(2).getReg() == SrcReg2) ||
01443         (Instr.getOperand(1).getReg() == SrcReg2 &&
01444          Instr.getOperand(2).getReg() == SrcReg))) {
01445       Sub = &*I;
01446       break;
01447     }
01448 
01449     if (I == B)
01450       // The 'and' is below the comparison instruction.
01451       return false;
01452   }
01453 
01454   // Return false if no candidates exist.
01455   if (!MI && !Sub)
01456     return false;
01457 
01458   // The single candidate is called MI.
01459   if (!MI) MI = Sub;
01460 
01461   int NewOpC = -1;
01462   MIOpC = MI->getOpcode();
01463   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
01464     NewOpC = MIOpC;
01465   else {
01466     NewOpC = PPC::getRecordFormOpcode(MIOpC);
01467     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
01468       NewOpC = MIOpC;
01469   }
01470 
01471   // FIXME: On the non-embedded POWER architectures, only some of the record
01472   // forms are fast, and we should use only the fast ones.
01473 
01474   // The defining instruction has a record form (or is already a record
01475   // form). It is possible, however, that we'll need to reverse the condition
01476   // code of the users.
01477   if (NewOpC == -1)
01478     return false;
01479 
01480   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
01481   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
01482 
01483   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
01484   // needs to be updated to be based on SUB.  Push the condition code
01485   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
01486   // condition code of these operands will be modified.
01487   bool ShouldSwap = false;
01488   if (Sub) {
01489     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
01490       Sub->getOperand(2).getReg() == SrcReg;
01491 
01492     // The operands to subf are the opposite of sub, so only in the fixed-point
01493     // case, invert the order.
01494     ShouldSwap = !ShouldSwap;
01495   }
01496 
01497   if (ShouldSwap)
01498     for (MachineRegisterInfo::use_instr_iterator
01499          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
01500          I != IE; ++I) {
01501       MachineInstr *UseMI = &*I;
01502       if (UseMI->getOpcode() == PPC::BCC) {
01503         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
01504         assert((!equalityOnly ||
01505                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
01506                "Invalid predicate for equality-only optimization");
01507         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
01508                                 PPC::getSwappedPredicate(Pred)));
01509       } else if (UseMI->getOpcode() == PPC::ISEL ||
01510                  UseMI->getOpcode() == PPC::ISEL8) {
01511         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
01512         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
01513                "Invalid CR bit for equality-only optimization");
01514 
01515         if (NewSubReg == PPC::sub_lt)
01516           NewSubReg = PPC::sub_gt;
01517         else if (NewSubReg == PPC::sub_gt)
01518           NewSubReg = PPC::sub_lt;
01519 
01520         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
01521                                                  NewSubReg));
01522       } else // We need to abort on a user we don't understand.
01523         return false;
01524     }
01525 
01526   // Create a new virtual register to hold the value of the CR set by the
01527   // record-form instruction. If the instruction was not previously in
01528   // record form, then set the kill flag on the CR.
01529   CmpInstr->eraseFromParent();
01530 
01531   MachineBasicBlock::iterator MII = MI;
01532   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
01533           get(TargetOpcode::COPY), CRReg)
01534     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
01535 
01536   if (MIOpC != NewOpC) {
01537     // We need to be careful here: we're replacing one instruction with
01538     // another, and we need to make sure that we get all of the right
01539     // implicit uses and defs. On the other hand, the caller may be holding
01540     // an iterator to this instruction, and so we can't delete it (this is
01541     // specifically the case if this is the instruction directly after the
01542     // compare).
01543 
01544     const MCInstrDesc &NewDesc = get(NewOpC);
01545     MI->setDesc(NewDesc);
01546 
01547     if (NewDesc.ImplicitDefs)
01548       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
01549            *ImpDefs; ++ImpDefs)
01550         if (!MI->definesRegister(*ImpDefs))
01551           MI->addOperand(*MI->getParent()->getParent(),
01552                          MachineOperand::CreateReg(*ImpDefs, true, true));
01553     if (NewDesc.ImplicitUses)
01554       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
01555            *ImpUses; ++ImpUses)
01556         if (!MI->readsRegister(*ImpUses))
01557           MI->addOperand(*MI->getParent()->getParent(),
01558                          MachineOperand::CreateReg(*ImpUses, false, true));
01559   }
01560 
01561   // Modify the condition code of operands in OperandsToUpdate.
01562   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
01563   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
01564   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
01565     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
01566 
01567   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
01568     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
01569 
01570   return true;
01571 }
01572 
01573 /// GetInstSize - Return the number of bytes of code the specified
01574 /// instruction may be.  This returns the maximum number of bytes.
01575 ///
01576 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
01577   unsigned Opcode = MI->getOpcode();
01578 
01579   if (Opcode == PPC::INLINEASM) {
01580     const MachineFunction *MF = MI->getParent()->getParent();
01581     const char *AsmStr = MI->getOperand(0).getSymbolName();
01582     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
01583   } else {
01584     const MCInstrDesc &Desc = get(Opcode);
01585     return Desc.getSize();
01586   }
01587 }
01588 
01589 #undef DEBUG_TYPE
01590 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
01591 
01592 namespace {
01593   // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
01594   // (Altivec and scalar floating-point registers), we need to transform the
01595   // copies into subregister copies with other restrictions.
01596   struct PPCVSXFMAMutate : public MachineFunctionPass {
01597     static char ID;
01598     PPCVSXFMAMutate() : MachineFunctionPass(ID) {
01599       initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
01600     }
01601 
01602     LiveIntervals *LIS;
01603 
01604     const PPCTargetMachine *TM;
01605     const PPCInstrInfo *TII;
01606 
01607 protected:
01608     bool processBlock(MachineBasicBlock &MBB) {
01609       bool Changed = false;
01610 
01611       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
01612       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01613            I != IE; ++I) {
01614         MachineInstr *MI = I;
01615 
01616         // The default (A-type) VSX FMA form kills the addend (it is taken from
01617         // the target register, which is then updated to reflect the result of
01618         // the FMA). If the instruction, however, kills one of the registers
01619         // used for the product, then we can use the M-form instruction (which
01620         // will take that value from the to-be-defined register).
01621 
01622         int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
01623         if (AltOpc == -1)
01624           continue;
01625 
01626         // This pass is run after register coalescing, and so we're looking for
01627         // a situation like this:
01628         //   ...
01629         //   %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
01630         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
01631         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
01632         //   ...
01633         //   %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
01634         //                         %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
01635         //   ...
01636         // Where we can eliminate the copy by changing from the A-type to the
01637         // M-type instruction. Specifically, for this example, this means:
01638         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
01639         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
01640         // is replaced by:
01641         //   %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
01642         //                         %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
01643         // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
01644 
01645         SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
01646 
01647         VNInfo *AddendValNo =
01648           LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
01649         MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
01650 
01651         // The addend and this instruction must be in the same block.
01652 
01653         if (!AddendMI || AddendMI->getParent() != MI->getParent())
01654           continue;
01655 
01656         // The addend must be a full copy within the same register class.
01657 
01658         if (!AddendMI->isFullCopy())
01659           continue;
01660 
01661         unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
01662         if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
01663           if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
01664               MRI.getRegClass(AddendSrcReg))
01665             continue;
01666         } else {
01667           // If AddendSrcReg is a physical register, make sure the destination
01668           // register class contains it.
01669           if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
01670                 ->contains(AddendSrcReg))
01671             continue;
01672         }
01673 
01674         // In theory, there could be other uses of the addend copy before this
01675         // fma.  We could deal with this, but that would require additional
01676         // logic below and I suspect it will not occur in any relevant
01677         // situations.
01678         bool OtherUsers = false;
01679         for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
01680              J != JE; --J)
01681           if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
01682             OtherUsers = true;
01683             break;
01684           }
01685 
01686         if (OtherUsers)
01687           continue;
01688 
01689         // Find one of the product operands that is killed by this instruction.
01690 
01691         unsigned KilledProdOp = 0, OtherProdOp = 0;
01692         if (LIS->getInterval(MI->getOperand(2).getReg())
01693                      .Query(FMAIdx).isKill()) {
01694           KilledProdOp = 2;
01695           OtherProdOp  = 3;
01696         } else if (LIS->getInterval(MI->getOperand(3).getReg())
01697                      .Query(FMAIdx).isKill()) {
01698           KilledProdOp = 3;
01699           OtherProdOp  = 2;
01700         }
01701 
01702         // If there are no killed product operands, then this transformation is
01703         // likely not profitable.
01704         if (!KilledProdOp)
01705           continue;
01706 
01707         // In order to replace the addend here with the source of the copy,
01708         // it must still be live here.
01709         if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
01710           continue;
01711 
01712         // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
01713 
01714         unsigned AddReg = AddendMI->getOperand(1).getReg();
01715         unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
01716         unsigned OtherProdReg  = MI->getOperand(OtherProdOp).getReg();
01717 
01718         unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
01719         unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
01720         unsigned OtherProdSubReg  = MI->getOperand(OtherProdOp).getSubReg();
01721 
01722         bool AddRegKill = AddendMI->getOperand(1).isKill();
01723         bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
01724         bool OtherProdRegKill  = MI->getOperand(OtherProdOp).isKill();
01725 
01726         bool AddRegUndef = AddendMI->getOperand(1).isUndef();
01727         bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
01728         bool OtherProdRegUndef  = MI->getOperand(OtherProdOp).isUndef();
01729 
01730         unsigned OldFMAReg = MI->getOperand(0).getReg();
01731 
01732         assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
01733                "Addend copy not tied to old FMA output!");
01734 
01735         DEBUG(dbgs() << "VSX FMA Mutation:\n    " << *MI;);
01736 
01737         MI->getOperand(0).setReg(KilledProdReg);
01738         MI->getOperand(1).setReg(KilledProdReg);
01739         MI->getOperand(3).setReg(AddReg);
01740         MI->getOperand(2).setReg(OtherProdReg);
01741 
01742         MI->getOperand(0).setSubReg(KilledProdSubReg);
01743         MI->getOperand(1).setSubReg(KilledProdSubReg);
01744         MI->getOperand(3).setSubReg(AddSubReg);
01745         MI->getOperand(2).setSubReg(OtherProdSubReg);
01746 
01747         MI->getOperand(1).setIsKill(KilledProdRegKill);
01748         MI->getOperand(3).setIsKill(AddRegKill);
01749         MI->getOperand(2).setIsKill(OtherProdRegKill);
01750 
01751         MI->getOperand(1).setIsUndef(KilledProdRegUndef);
01752         MI->getOperand(3).setIsUndef(AddRegUndef);
01753         MI->getOperand(2).setIsUndef(OtherProdRegUndef);
01754 
01755         MI->setDesc(TII->get(AltOpc));
01756 
01757         DEBUG(dbgs() << " -> " << *MI);
01758 
01759         // The killed product operand was killed here, so we can reuse it now
01760         // for the result of the fma.
01761 
01762         LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
01763         VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
01764         for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
01765              UI != UE;) {
01766           MachineOperand &UseMO = *UI;
01767           MachineInstr *UseMI = UseMO.getParent();
01768           ++UI;
01769 
01770           // Don't replace the result register of the copy we're about to erase.
01771           if (UseMI == AddendMI)
01772             continue;
01773 
01774           UseMO.setReg(KilledProdReg);
01775           UseMO.setSubReg(KilledProdSubReg);
01776         }
01777 
01778         // Extend the live intervals of the killed product operand to hold the
01779         // fma result.
01780 
01781         LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
01782         for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
01783              AI != AE; ++AI) {
01784           // Don't add the segment that corresponds to the original copy.
01785           if (AI->valno == AddendValNo)
01786             continue;
01787 
01788           VNInfo *NewFMAValNo =
01789             NewFMAInt.getNextValue(AI->start,
01790                                    LIS->getVNInfoAllocator());
01791 
01792           NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
01793                                                      NewFMAValNo));
01794         }
01795         DEBUG(dbgs() << "  extended: " << NewFMAInt << '\n');
01796 
01797         FMAInt.removeValNo(FMAValNo);
01798         DEBUG(dbgs() << "  trimmed:  " << FMAInt << '\n');
01799 
01800         // Remove the (now unused) copy.
01801 
01802         DEBUG(dbgs() << "  removing: " << *AddendMI << '\n');
01803         LIS->RemoveMachineInstrFromMaps(AddendMI);
01804         AddendMI->eraseFromParent();
01805 
01806         Changed = true;
01807       }
01808 
01809       return Changed;
01810     }
01811 
01812 public:
01813     virtual bool runOnMachineFunction(MachineFunction &MF) {
01814       LIS = &getAnalysis<LiveIntervals>();
01815 
01816       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
01817       TII = TM->getInstrInfo();
01818 
01819       bool Changed = false;
01820 
01821       if (DisableVSXFMAMutate)
01822         return Changed;
01823 
01824       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
01825         MachineBasicBlock &B = *I++;
01826         if (processBlock(B))
01827           Changed = true;
01828       }
01829 
01830       return Changed;
01831     }
01832 
01833     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
01834       AU.addRequired<LiveIntervals>();
01835       AU.addPreserved<LiveIntervals>();
01836       AU.addRequired<SlotIndexes>();
01837       AU.addPreserved<SlotIndexes>();
01838       MachineFunctionPass::getAnalysisUsage(AU);
01839     }
01840   };
01841 }
01842 
01843 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
01844                       "PowerPC VSX FMA Mutation", false, false)
01845 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
01846 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
01847 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
01848                     "PowerPC VSX FMA Mutation", false, false)
01849 
01850 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
01851 
01852 char PPCVSXFMAMutate::ID = 0;
01853 FunctionPass*
01854 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
01855 
01856 #undef DEBUG_TYPE
01857 #define DEBUG_TYPE "ppc-vsx-copy"
01858 
01859 namespace llvm {
01860   void initializePPCVSXCopyPass(PassRegistry&);
01861 }
01862 
01863 namespace {
01864   // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
01865   // (Altivec and scalar floating-point registers), we need to transform the
01866   // copies into subregister copies with other restrictions.
01867   struct PPCVSXCopy : public MachineFunctionPass {
01868     static char ID;
01869     PPCVSXCopy() : MachineFunctionPass(ID) {
01870       initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
01871     }
01872 
01873     const PPCTargetMachine *TM;
01874     const PPCInstrInfo *TII;
01875 
01876     bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
01877                       MachineRegisterInfo &MRI) {
01878       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
01879         return RC->hasSubClassEq(MRI.getRegClass(Reg));
01880       } else if (RC->contains(Reg)) {
01881         return true;
01882       }
01883 
01884       return false;
01885     }
01886 
01887     bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
01888       return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
01889     }
01890 
01891     bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
01892       return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
01893     }
01894 
01895     bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
01896       return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
01897     }
01898 
01899 protected:
01900     bool processBlock(MachineBasicBlock &MBB) {
01901       bool Changed = false;
01902 
01903       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
01904       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01905            I != IE; ++I) {
01906         MachineInstr *MI = I;
01907         if (!MI->isFullCopy())
01908           continue;
01909 
01910         MachineOperand &DstMO = MI->getOperand(0);
01911         MachineOperand &SrcMO = MI->getOperand(1);
01912 
01913         if ( IsVSReg(DstMO.getReg(), MRI) &&
01914             !IsVSReg(SrcMO.getReg(), MRI)) {
01915           // This is a copy *to* a VSX register from a non-VSX register.
01916           Changed = true;
01917 
01918           const TargetRegisterClass *SrcRC =
01919             IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
01920                                            &PPC::VSLRCRegClass;
01921           assert((IsF8Reg(SrcMO.getReg(), MRI) ||
01922                   IsVRReg(SrcMO.getReg(), MRI)) &&
01923                  "Unknown source for a VSX copy");
01924 
01925           unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
01926           BuildMI(MBB, MI, MI->getDebugLoc(),
01927                   TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
01928             .addImm(1) // add 1, not 0, because there is no implicit clearing
01929                        // of the high bits.
01930             .addOperand(SrcMO)
01931             .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
01932                                                    PPC::sub_64);
01933 
01934           // The source of the original copy is now the new virtual register.
01935           SrcMO.setReg(NewVReg);
01936         } else if (!IsVSReg(DstMO.getReg(), MRI) &&
01937                     IsVSReg(SrcMO.getReg(), MRI)) {
01938           // This is a copy *from* a VSX register to a non-VSX register.
01939           Changed = true;
01940 
01941           const TargetRegisterClass *DstRC =
01942             IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
01943                                            &PPC::VSLRCRegClass;
01944           assert((IsF8Reg(DstMO.getReg(), MRI) ||
01945                   IsVRReg(DstMO.getReg(), MRI)) &&
01946                  "Unknown destination for a VSX copy");
01947 
01948           // Copy the VSX value into a new VSX register of the correct subclass.
01949           unsigned NewVReg = MRI.createVirtualRegister(DstRC);
01950           BuildMI(MBB, MI, MI->getDebugLoc(),
01951                   TII->get(TargetOpcode::COPY), NewVReg)
01952             .addOperand(SrcMO);
01953 
01954           // Transform the original copy into a subregister extraction copy.
01955           SrcMO.setReg(NewVReg);
01956           SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
01957                                                          PPC::sub_64);
01958         }
01959       }
01960 
01961       return Changed;
01962     }
01963 
01964 public:
01965     virtual bool runOnMachineFunction(MachineFunction &MF) {
01966       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
01967       TII = TM->getInstrInfo();
01968 
01969       bool Changed = false;
01970 
01971       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
01972         MachineBasicBlock &B = *I++;
01973         if (processBlock(B))
01974           Changed = true;
01975       }
01976 
01977       return Changed;
01978     }
01979 
01980     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
01981       MachineFunctionPass::getAnalysisUsage(AU);
01982     }
01983   };
01984 }
01985 
01986 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
01987                 "PowerPC VSX Copy Legalization", false, false)
01988 
01989 char PPCVSXCopy::ID = 0;
01990 FunctionPass*
01991 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
01992 
01993 #undef DEBUG_TYPE
01994 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
01995 
01996 namespace llvm {
01997   void initializePPCVSXCopyCleanupPass(PassRegistry&);
01998 }
01999 
02000 namespace {
02001   // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
02002   // registers (mostly because the ABI code still places all values into the
02003   // "traditional" floating-point and vector registers). Remove them here.
02004   struct PPCVSXCopyCleanup : public MachineFunctionPass {
02005     static char ID;
02006     PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
02007       initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
02008     }
02009 
02010     const PPCTargetMachine *TM;
02011     const PPCInstrInfo *TII;
02012 
02013 protected:
02014     bool processBlock(MachineBasicBlock &MBB) {
02015       bool Changed = false;
02016 
02017       SmallVector<MachineInstr *, 4> ToDelete;
02018       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
02019            I != IE; ++I) {
02020         MachineInstr *MI = I;
02021         if (MI->getOpcode() == PPC::XXLOR &&
02022             MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
02023             MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
02024           ToDelete.push_back(MI);
02025       }
02026 
02027       if (!ToDelete.empty())
02028         Changed = true;
02029 
02030       for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
02031         DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
02032         ToDelete[i]->eraseFromParent();
02033       }
02034 
02035       return Changed;
02036     }
02037 
02038 public:
02039     virtual bool runOnMachineFunction(MachineFunction &MF) {
02040       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
02041       TII = TM->getInstrInfo();
02042 
02043       bool Changed = false;
02044 
02045       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
02046         MachineBasicBlock &B = *I++;
02047         if (processBlock(B))
02048           Changed = true;
02049       }
02050 
02051       return Changed;
02052     }
02053 
02054     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
02055       MachineFunctionPass::getAnalysisUsage(AU);
02056     }
02057   };
02058 }
02059 
02060 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
02061                 "PowerPC VSX Copy Cleanup", false, false)
02062 
02063 char PPCVSXCopyCleanup::ID = 0;
02064 FunctionPass*
02065 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
02066 
02067 #undef DEBUG_TYPE
02068 #define DEBUG_TYPE "ppc-early-ret"
02069 STATISTIC(NumBCLR, "Number of early conditional returns");
02070 STATISTIC(NumBLR,  "Number of early returns");
02071 
02072 namespace llvm {
02073   void initializePPCEarlyReturnPass(PassRegistry&);
02074 }
02075 
02076 namespace {
02077   // PPCEarlyReturn pass - For simple functions without epilogue code, move
02078   // returns up, and create conditional returns, to avoid unnecessary
02079   // branch-to-blr sequences.
02080   struct PPCEarlyReturn : public MachineFunctionPass {
02081     static char ID;
02082     PPCEarlyReturn() : MachineFunctionPass(ID) {
02083       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
02084     }
02085 
02086     const PPCTargetMachine *TM;
02087     const PPCInstrInfo *TII;
02088 
02089 protected:
02090     bool processBlock(MachineBasicBlock &ReturnMBB) {
02091       bool Changed = false;
02092 
02093       MachineBasicBlock::iterator I = ReturnMBB.begin();
02094       I = ReturnMBB.SkipPHIsAndLabels(I);
02095 
02096       // The block must be essentially empty except for the blr.
02097       if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
02098           I != ReturnMBB.getLastNonDebugInstr())
02099         return Changed;
02100 
02101       SmallVector<MachineBasicBlock*, 8> PredToRemove;
02102       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
02103            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
02104         bool OtherReference = false, BlockChanged = false;
02105         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
02106           if (J->getOpcode() == PPC::B) {
02107             if (J->getOperand(0).getMBB() == &ReturnMBB) {
02108               // This is an unconditional branch to the return. Replace the
02109               // branch with a blr.
02110               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
02111               MachineBasicBlock::iterator K = J--;
02112               K->eraseFromParent();
02113               BlockChanged = true;
02114               ++NumBLR;
02115               continue;
02116             }
02117           } else if (J->getOpcode() == PPC::BCC) {
02118             if (J->getOperand(2).getMBB() == &ReturnMBB) {
02119               // This is a conditional branch to the return. Replace the branch
02120               // with a bclr.
02121               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
02122                 .addImm(J->getOperand(0).getImm())
02123                 .addReg(J->getOperand(1).getReg());
02124               MachineBasicBlock::iterator K = J--;
02125               K->eraseFromParent();
02126               BlockChanged = true;
02127               ++NumBCLR;
02128               continue;
02129             }
02130           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
02131             if (J->getOperand(1).getMBB() == &ReturnMBB) {
02132               // This is a conditional branch to the return. Replace the branch
02133               // with a bclr.
02134               BuildMI(**PI, J, J->getDebugLoc(),
02135                       TII->get(J->getOpcode() == PPC::BC ?
02136                                PPC::BCLR : PPC::BCLRn))
02137                 .addReg(J->getOperand(0).getReg());
02138               MachineBasicBlock::iterator K = J--;
02139               K->eraseFromParent();
02140               BlockChanged = true;
02141               ++NumBCLR;
02142               continue;
02143             }
02144           } else if (J->isBranch()) {
02145             if (J->isIndirectBranch()) {
02146               if (ReturnMBB.hasAddressTaken())
02147                 OtherReference = true;
02148             } else
02149               for (unsigned i = 0; i < J->getNumOperands(); ++i)
02150                 if (J->getOperand(i).isMBB() &&
02151                     J->getOperand(i).getMBB() == &ReturnMBB)
02152                   OtherReference = true;
02153           } else if (!J->isTerminator() && !J->isDebugValue())
02154             break;
02155 
02156           if (J == (*PI)->begin())
02157             break;
02158 
02159           --J;
02160         }
02161 
02162         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
02163           OtherReference = true;
02164 
02165         // Predecessors are stored in a vector and can't be removed here.
02166         if (!OtherReference && BlockChanged) {
02167           PredToRemove.push_back(*PI);
02168         }
02169 
02170         if (BlockChanged)
02171           Changed = true;
02172       }
02173 
02174       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
02175         PredToRemove[i]->removeSuccessor(&ReturnMBB);
02176 
02177       if (Changed && !ReturnMBB.hasAddressTaken()) {
02178         // We now might be able to merge this blr-only block into its
02179         // by-layout predecessor.
02180         if (ReturnMBB.pred_size() == 1 &&
02181             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
02182           // Move the blr into the preceding block.
02183           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
02184           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
02185           PrevMBB.removeSuccessor(&ReturnMBB);
02186         }
02187 
02188         if (ReturnMBB.pred_empty())
02189           ReturnMBB.eraseFromParent();
02190       }
02191 
02192       return Changed;
02193     }
02194 
02195 public:
02196     virtual bool runOnMachineFunction(MachineFunction &MF) {
02197       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
02198       TII = TM->getInstrInfo();
02199 
02200       bool Changed = false;
02201 
02202       // If the function does not have at least two blocks, then there is
02203       // nothing to do.
02204       if (MF.size() < 2)
02205         return Changed;
02206 
02207       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
02208         MachineBasicBlock &B = *I++;
02209         if (processBlock(B))
02210           Changed = true;
02211       }
02212 
02213       return Changed;
02214     }
02215 
02216     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
02217       MachineFunctionPass::getAnalysisUsage(AU);
02218     }
02219   };
02220 }
02221 
02222 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
02223                 "PowerPC Early-Return Creation", false, false)
02224 
02225 char PPCEarlyReturn::ID = 0;
02226 FunctionPass*
02227 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }