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