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