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