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