LLVM API Documentation

PPCISelDAGToDAG.cpp
Go to the documentation of this file.
00001 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
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 defines a pattern matching instruction selector for PowerPC,
00011 // converting from a legalized dag to a PPC dag.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "PPC.h"
00016 #include "MCTargetDesc/PPCPredicates.h"
00017 #include "PPCMachineFunctionInfo.h"
00018 #include "PPCTargetMachine.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineRegisterInfo.h"
00022 #include "llvm/CodeGen/SelectionDAG.h"
00023 #include "llvm/CodeGen/SelectionDAGISel.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/Function.h"
00026 #include "llvm/IR/GlobalAlias.h"
00027 #include "llvm/IR/GlobalValue.h"
00028 #include "llvm/IR/GlobalVariable.h"
00029 #include "llvm/IR/Intrinsics.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Target/TargetOptions.h"
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "ppc-codegen"
00039 
00040 // FIXME: Remove this once the bug has been fixed!
00041 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
00042 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
00043 
00044 namespace llvm {
00045   void initializePPCDAGToDAGISelPass(PassRegistry&);
00046 }
00047 
00048 namespace {
00049   //===--------------------------------------------------------------------===//
00050   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
00051   /// instructions for SelectionDAG operations.
00052   ///
00053   class PPCDAGToDAGISel : public SelectionDAGISel {
00054     const PPCTargetMachine &TM;
00055     const PPCTargetLowering *PPCLowering;
00056     const PPCSubtarget *PPCSubTarget;
00057     unsigned GlobalBaseReg;
00058   public:
00059     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
00060         : SelectionDAGISel(tm), TM(tm),
00061           PPCLowering(TM.getSubtargetImpl()->getTargetLowering()),
00062           PPCSubTarget(TM.getSubtargetImpl()) {
00063       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
00064     }
00065 
00066     bool runOnMachineFunction(MachineFunction &MF) override {
00067       // Make sure we re-emit a set of the global base reg if necessary
00068       GlobalBaseReg = 0;
00069       PPCLowering = TM.getSubtargetImpl()->getTargetLowering();
00070       PPCSubTarget = TM.getSubtargetImpl();
00071       SelectionDAGISel::runOnMachineFunction(MF);
00072 
00073       if (!PPCSubTarget->isSVR4ABI())
00074         InsertVRSaveCode(MF);
00075 
00076       return true;
00077     }
00078 
00079     void PostprocessISelDAG() override;
00080 
00081     /// getI32Imm - Return a target constant with the specified value, of type
00082     /// i32.
00083     inline SDValue getI32Imm(unsigned Imm) {
00084       return CurDAG->getTargetConstant(Imm, MVT::i32);
00085     }
00086 
00087     /// getI64Imm - Return a target constant with the specified value, of type
00088     /// i64.
00089     inline SDValue getI64Imm(uint64_t Imm) {
00090       return CurDAG->getTargetConstant(Imm, MVT::i64);
00091     }
00092 
00093     /// getSmallIPtrImm - Return a target constant of pointer type.
00094     inline SDValue getSmallIPtrImm(unsigned Imm) {
00095       return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
00096     }
00097 
00098     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
00099     /// with any number of 0s on either side.  The 1s are allowed to wrap from
00100     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
00101     /// 0x0F0F0000 is not, since all 1s are not contiguous.
00102     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
00103 
00104 
00105     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
00106     /// rotate and mask opcode and mask operation.
00107     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
00108                                 unsigned &SH, unsigned &MB, unsigned &ME);
00109 
00110     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
00111     /// base register.  Return the virtual register that holds this value.
00112     SDNode *getGlobalBaseReg();
00113 
00114     // Select - Convert the specified operand from a target-independent to a
00115     // target-specific node if it hasn't already been changed.
00116     SDNode *Select(SDNode *N) override;
00117 
00118     SDNode *SelectBitfieldInsert(SDNode *N);
00119 
00120     /// SelectCC - Select a comparison of the specified values with the
00121     /// specified condition code, returning the CR# of the expression.
00122     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
00123 
00124     /// SelectAddrImm - Returns true if the address N can be represented by
00125     /// a base register plus a signed 16-bit displacement [r+imm].
00126     bool SelectAddrImm(SDValue N, SDValue &Disp,
00127                        SDValue &Base) {
00128       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
00129     }
00130 
00131     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
00132     /// immediate field.  Note that the operand at this point is already the
00133     /// result of a prior SelectAddressRegImm call.
00134     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
00135       if (N.getOpcode() == ISD::TargetConstant ||
00136           N.getOpcode() == ISD::TargetGlobalAddress) {
00137         Out = N;
00138         return true;
00139       }
00140 
00141       return false;
00142     }
00143 
00144     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
00145     /// represented as an indexed [r+r] operation.  Returns false if it can
00146     /// be represented by [r+imm], which are preferred.
00147     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
00148       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
00149     }
00150 
00151     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
00152     /// represented as an indexed [r+r] operation.
00153     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
00154       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
00155     }
00156 
00157     /// SelectAddrImmX4 - Returns true if the address N can be represented by
00158     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
00159     /// Suitable for use by STD and friends.
00160     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
00161       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
00162     }
00163 
00164     // Select an address into a single register.
00165     bool SelectAddr(SDValue N, SDValue &Base) {
00166       Base = N;
00167       return true;
00168     }
00169 
00170     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
00171     /// inline asm expressions.  It is always correct to compute the value into
00172     /// a register.  The case of adding a (possibly relocatable) constant to a
00173     /// register can be improved, but it is wrong to substitute Reg+Reg for
00174     /// Reg in an asm, because the load or store opcode would have to change.
00175    bool SelectInlineAsmMemoryOperand(const SDValue &Op,
00176                                       char ConstraintCode,
00177                                       std::vector<SDValue> &OutOps) override {
00178       OutOps.push_back(Op);
00179       return false;
00180     }
00181 
00182     void InsertVRSaveCode(MachineFunction &MF);
00183 
00184     const char *getPassName() const override {
00185       return "PowerPC DAG->DAG Pattern Instruction Selection";
00186     }
00187 
00188 // Include the pieces autogenerated from the target description.
00189 #include "PPCGenDAGISel.inc"
00190 
00191 private:
00192     SDNode *SelectSETCC(SDNode *N);
00193 
00194     void PeepholePPC64();
00195     void PeepholeCROps();
00196 
00197     bool AllUsersSelectZero(SDNode *N);
00198     void SwapAllSelectUsers(SDNode *N);
00199   };
00200 }
00201 
00202 /// InsertVRSaveCode - Once the entire function has been instruction selected,
00203 /// all virtual registers are created and all machine instructions are built,
00204 /// check to see if we need to save/restore VRSAVE.  If so, do it.
00205 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
00206   // Check to see if this function uses vector registers, which means we have to
00207   // save and restore the VRSAVE register and update it with the regs we use.
00208   //
00209   // In this case, there will be virtual registers of vector type created
00210   // by the scheduler.  Detect them now.
00211   bool HasVectorVReg = false;
00212   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
00213     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00214     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
00215       HasVectorVReg = true;
00216       break;
00217     }
00218   }
00219   if (!HasVectorVReg) return;  // nothing to do.
00220 
00221   // If we have a vector register, we want to emit code into the entry and exit
00222   // blocks to save and restore the VRSAVE register.  We do this here (instead
00223   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
00224   //
00225   // 1. This (trivially) reduces the load on the register allocator, by not
00226   //    having to represent the live range of the VRSAVE register.
00227   // 2. This (more significantly) allows us to create a temporary virtual
00228   //    register to hold the saved VRSAVE value, allowing this temporary to be
00229   //    register allocated, instead of forcing it to be spilled to the stack.
00230 
00231   // Create two vregs - one to hold the VRSAVE register that is live-in to the
00232   // function and one for the value after having bits or'd into it.
00233   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
00234   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
00235 
00236   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
00237   MachineBasicBlock &EntryBB = *Fn.begin();
00238   DebugLoc dl;
00239   // Emit the following code into the entry block:
00240   // InVRSAVE = MFVRSAVE
00241   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
00242   // MTVRSAVE UpdatedVRSAVE
00243   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
00244   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
00245   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
00246           UpdatedVRSAVE).addReg(InVRSAVE);
00247   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
00248 
00249   // Find all return blocks, outputting a restore in each epilog.
00250   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00251     if (!BB->empty() && BB->back().isReturn()) {
00252       IP = BB->end(); --IP;
00253 
00254       // Skip over all terminator instructions, which are part of the return
00255       // sequence.
00256       MachineBasicBlock::iterator I2 = IP;
00257       while (I2 != BB->begin() && (--I2)->isTerminator())
00258         IP = I2;
00259 
00260       // Emit: MTVRSAVE InVRSave
00261       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
00262     }
00263   }
00264 }
00265 
00266 
00267 /// getGlobalBaseReg - Output the instructions required to put the
00268 /// base address to use for accessing globals into a register.
00269 ///
00270 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
00271   if (!GlobalBaseReg) {
00272     const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
00273     // Insert the set of GlobalBaseReg into the first MBB of the function
00274     MachineBasicBlock &FirstMBB = MF->front();
00275     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
00276     DebugLoc dl;
00277 
00278     if (PPCLowering->getPointerTy() == MVT::i32) {
00279       if (PPCSubTarget->isTargetELF())
00280         GlobalBaseReg = PPC::R30;
00281       else
00282         GlobalBaseReg =
00283           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
00284       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
00285       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
00286       if (PPCSubTarget->isTargetELF()) {
00287         unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
00288         BuildMI(FirstMBB, MBBI, dl,
00289                 TII.get(PPC::GetGBRO), TempReg).addReg(GlobalBaseReg);
00290         BuildMI(FirstMBB, MBBI, dl,
00291                 TII.get(PPC::UpdateGBR)).addReg(GlobalBaseReg).addReg(TempReg);
00292         MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
00293       }
00294     } else {
00295       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
00296       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
00297       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
00298     }
00299   }
00300   return CurDAG->getRegister(GlobalBaseReg,
00301                              PPCLowering->getPointerTy()).getNode();
00302 }
00303 
00304 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
00305 /// or 64-bit immediate, and if the value can be accurately represented as a
00306 /// sign extension from a 16-bit value.  If so, this returns true and the
00307 /// immediate.
00308 static bool isIntS16Immediate(SDNode *N, short &Imm) {
00309   if (N->getOpcode() != ISD::Constant)
00310     return false;
00311 
00312   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
00313   if (N->getValueType(0) == MVT::i32)
00314     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
00315   else
00316     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
00317 }
00318 
00319 static bool isIntS16Immediate(SDValue Op, short &Imm) {
00320   return isIntS16Immediate(Op.getNode(), Imm);
00321 }
00322 
00323 
00324 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
00325 /// operand. If so Imm will receive the 32-bit value.
00326 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
00327   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
00328     Imm = cast<ConstantSDNode>(N)->getZExtValue();
00329     return true;
00330   }
00331   return false;
00332 }
00333 
00334 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
00335 /// operand.  If so Imm will receive the 64-bit value.
00336 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
00337   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
00338     Imm = cast<ConstantSDNode>(N)->getZExtValue();
00339     return true;
00340   }
00341   return false;
00342 }
00343 
00344 // isInt32Immediate - This method tests to see if a constant operand.
00345 // If so Imm will receive the 32 bit value.
00346 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
00347   return isInt32Immediate(N.getNode(), Imm);
00348 }
00349 
00350 
00351 // isOpcWithIntImmediate - This method tests to see if the node is a specific
00352 // opcode and that it has a immediate integer right operand.
00353 // If so Imm will receive the 32 bit value.
00354 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
00355   return N->getOpcode() == Opc
00356          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
00357 }
00358 
00359 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
00360   if (!Val)
00361     return false;
00362 
00363   if (isShiftedMask_32(Val)) {
00364     // look for the first non-zero bit
00365     MB = countLeadingZeros(Val);
00366     // look for the first zero bit after the run of ones
00367     ME = countLeadingZeros((Val - 1) ^ Val);
00368     return true;
00369   } else {
00370     Val = ~Val; // invert mask
00371     if (isShiftedMask_32(Val)) {
00372       // effectively look for the first zero bit
00373       ME = countLeadingZeros(Val) - 1;
00374       // effectively look for the first one bit after the run of zeros
00375       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
00376       return true;
00377     }
00378   }
00379   // no run present
00380   return false;
00381 }
00382 
00383 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
00384                                       bool isShiftMask, unsigned &SH,
00385                                       unsigned &MB, unsigned &ME) {
00386   // Don't even go down this path for i64, since different logic will be
00387   // necessary for rldicl/rldicr/rldimi.
00388   if (N->getValueType(0) != MVT::i32)
00389     return false;
00390 
00391   unsigned Shift  = 32;
00392   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
00393   unsigned Opcode = N->getOpcode();
00394   if (N->getNumOperands() != 2 ||
00395       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
00396     return false;
00397 
00398   if (Opcode == ISD::SHL) {
00399     // apply shift left to mask if it comes first
00400     if (isShiftMask) Mask = Mask << Shift;
00401     // determine which bits are made indeterminant by shift
00402     Indeterminant = ~(0xFFFFFFFFu << Shift);
00403   } else if (Opcode == ISD::SRL) {
00404     // apply shift right to mask if it comes first
00405     if (isShiftMask) Mask = Mask >> Shift;
00406     // determine which bits are made indeterminant by shift
00407     Indeterminant = ~(0xFFFFFFFFu >> Shift);
00408     // adjust for the left rotate
00409     Shift = 32 - Shift;
00410   } else if (Opcode == ISD::ROTL) {
00411     Indeterminant = 0;
00412   } else {
00413     return false;
00414   }
00415 
00416   // if the mask doesn't intersect any Indeterminant bits
00417   if (Mask && !(Mask & Indeterminant)) {
00418     SH = Shift & 31;
00419     // make sure the mask is still a mask (wrap arounds may not be)
00420     return isRunOfOnes(Mask, MB, ME);
00421   }
00422   return false;
00423 }
00424 
00425 /// SelectBitfieldInsert - turn an or of two masked values into
00426 /// the rotate left word immediate then mask insert (rlwimi) instruction.
00427 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
00428   SDValue Op0 = N->getOperand(0);
00429   SDValue Op1 = N->getOperand(1);
00430   SDLoc dl(N);
00431 
00432   APInt LKZ, LKO, RKZ, RKO;
00433   CurDAG->computeKnownBits(Op0, LKZ, LKO);
00434   CurDAG->computeKnownBits(Op1, RKZ, RKO);
00435 
00436   unsigned TargetMask = LKZ.getZExtValue();
00437   unsigned InsertMask = RKZ.getZExtValue();
00438 
00439   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
00440     unsigned Op0Opc = Op0.getOpcode();
00441     unsigned Op1Opc = Op1.getOpcode();
00442     unsigned Value, SH = 0;
00443     TargetMask = ~TargetMask;
00444     InsertMask = ~InsertMask;
00445 
00446     // If the LHS has a foldable shift and the RHS does not, then swap it to the
00447     // RHS so that we can fold the shift into the insert.
00448     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
00449       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
00450           Op0.getOperand(0).getOpcode() == ISD::SRL) {
00451         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
00452             Op1.getOperand(0).getOpcode() != ISD::SRL) {
00453           std::swap(Op0, Op1);
00454           std::swap(Op0Opc, Op1Opc);
00455           std::swap(TargetMask, InsertMask);
00456         }
00457       }
00458     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
00459       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
00460           Op1.getOperand(0).getOpcode() != ISD::SRL) {
00461         std::swap(Op0, Op1);
00462         std::swap(Op0Opc, Op1Opc);
00463         std::swap(TargetMask, InsertMask);
00464       }
00465     }
00466 
00467     unsigned MB, ME;
00468     if (isRunOfOnes(InsertMask, MB, ME)) {
00469       SDValue Tmp1, Tmp2;
00470 
00471       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
00472           isInt32Immediate(Op1.getOperand(1), Value)) {
00473         Op1 = Op1.getOperand(0);
00474         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
00475       }
00476       if (Op1Opc == ISD::AND) {
00477        // The AND mask might not be a constant, and we need to make sure that
00478        // if we're going to fold the masking with the insert, all bits not
00479        // know to be zero in the mask are known to be one.
00480         APInt MKZ, MKO;
00481         CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
00482         bool CanFoldMask = InsertMask == MKO.getZExtValue();
00483 
00484         unsigned SHOpc = Op1.getOperand(0).getOpcode();
00485         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
00486             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
00487           // Note that Value must be in range here (less than 32) because
00488           // otherwise there would not be any bits set in InsertMask.
00489           Op1 = Op1.getOperand(0).getOperand(0);
00490           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
00491         }
00492       }
00493 
00494       SH &= 31;
00495       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
00496                           getI32Imm(ME) };
00497       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
00498     }
00499   }
00500   return nullptr;
00501 }
00502 
00503 /// SelectCC - Select a comparison of the specified values with the specified
00504 /// condition code, returning the CR# of the expression.
00505 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
00506                                     ISD::CondCode CC, SDLoc dl) {
00507   // Always select the LHS.
00508   unsigned Opc;
00509 
00510   if (LHS.getValueType() == MVT::i32) {
00511     unsigned Imm;
00512     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
00513       if (isInt32Immediate(RHS, Imm)) {
00514         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
00515         if (isUInt<16>(Imm))
00516           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
00517                                                 getI32Imm(Imm & 0xFFFF)), 0);
00518         // If this is a 16-bit signed immediate, fold it.
00519         if (isInt<16>((int)Imm))
00520           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
00521                                                 getI32Imm(Imm & 0xFFFF)), 0);
00522 
00523         // For non-equality comparisons, the default code would materialize the
00524         // constant, then compare against it, like this:
00525         //   lis r2, 4660
00526         //   ori r2, r2, 22136
00527         //   cmpw cr0, r3, r2
00528         // Since we are just comparing for equality, we can emit this instead:
00529         //   xoris r0,r3,0x1234
00530         //   cmplwi cr0,r0,0x5678
00531         //   beq cr0,L6
00532         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
00533                                            getI32Imm(Imm >> 16)), 0);
00534         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
00535                                               getI32Imm(Imm & 0xFFFF)), 0);
00536       }
00537       Opc = PPC::CMPLW;
00538     } else if (ISD::isUnsignedIntSetCC(CC)) {
00539       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
00540         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
00541                                               getI32Imm(Imm & 0xFFFF)), 0);
00542       Opc = PPC::CMPLW;
00543     } else {
00544       short SImm;
00545       if (isIntS16Immediate(RHS, SImm))
00546         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
00547                                               getI32Imm((int)SImm & 0xFFFF)),
00548                          0);
00549       Opc = PPC::CMPW;
00550     }
00551   } else if (LHS.getValueType() == MVT::i64) {
00552     uint64_t Imm;
00553     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
00554       if (isInt64Immediate(RHS.getNode(), Imm)) {
00555         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
00556         if (isUInt<16>(Imm))
00557           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
00558                                                 getI32Imm(Imm & 0xFFFF)), 0);
00559         // If this is a 16-bit signed immediate, fold it.
00560         if (isInt<16>(Imm))
00561           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
00562                                                 getI32Imm(Imm & 0xFFFF)), 0);
00563 
00564         // For non-equality comparisons, the default code would materialize the
00565         // constant, then compare against it, like this:
00566         //   lis r2, 4660
00567         //   ori r2, r2, 22136
00568         //   cmpd cr0, r3, r2
00569         // Since we are just comparing for equality, we can emit this instead:
00570         //   xoris r0,r3,0x1234
00571         //   cmpldi cr0,r0,0x5678
00572         //   beq cr0,L6
00573         if (isUInt<32>(Imm)) {
00574           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
00575                                              getI64Imm(Imm >> 16)), 0);
00576           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
00577                                                 getI64Imm(Imm & 0xFFFF)), 0);
00578         }
00579       }
00580       Opc = PPC::CMPLD;
00581     } else if (ISD::isUnsignedIntSetCC(CC)) {
00582       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
00583         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
00584                                               getI64Imm(Imm & 0xFFFF)), 0);
00585       Opc = PPC::CMPLD;
00586     } else {
00587       short SImm;
00588       if (isIntS16Immediate(RHS, SImm))
00589         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
00590                                               getI64Imm(SImm & 0xFFFF)),
00591                          0);
00592       Opc = PPC::CMPD;
00593     }
00594   } else if (LHS.getValueType() == MVT::f32) {
00595     Opc = PPC::FCMPUS;
00596   } else {
00597     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
00598     Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
00599   }
00600   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
00601 }
00602 
00603 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
00604   switch (CC) {
00605   case ISD::SETUEQ:
00606   case ISD::SETONE:
00607   case ISD::SETOLE:
00608   case ISD::SETOGE:
00609     llvm_unreachable("Should be lowered by legalize!");
00610   default: llvm_unreachable("Unknown condition!");
00611   case ISD::SETOEQ:
00612   case ISD::SETEQ:  return PPC::PRED_EQ;
00613   case ISD::SETUNE:
00614   case ISD::SETNE:  return PPC::PRED_NE;
00615   case ISD::SETOLT:
00616   case ISD::SETLT:  return PPC::PRED_LT;
00617   case ISD::SETULE:
00618   case ISD::SETLE:  return PPC::PRED_LE;
00619   case ISD::SETOGT:
00620   case ISD::SETGT:  return PPC::PRED_GT;
00621   case ISD::SETUGE:
00622   case ISD::SETGE:  return PPC::PRED_GE;
00623   case ISD::SETO:   return PPC::PRED_NU;
00624   case ISD::SETUO:  return PPC::PRED_UN;
00625     // These two are invalid for floating point.  Assume we have int.
00626   case ISD::SETULT: return PPC::PRED_LT;
00627   case ISD::SETUGT: return PPC::PRED_GT;
00628   }
00629 }
00630 
00631 /// getCRIdxForSetCC - Return the index of the condition register field
00632 /// associated with the SetCC condition, and whether or not the field is
00633 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
00634 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
00635   Invert = false;
00636   switch (CC) {
00637   default: llvm_unreachable("Unknown condition!");
00638   case ISD::SETOLT:
00639   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
00640   case ISD::SETOGT:
00641   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
00642   case ISD::SETOEQ:
00643   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
00644   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
00645   case ISD::SETUGE:
00646   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
00647   case ISD::SETULE:
00648   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
00649   case ISD::SETUNE:
00650   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
00651   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
00652   case ISD::SETUEQ:
00653   case ISD::SETOGE:
00654   case ISD::SETOLE:
00655   case ISD::SETONE:
00656     llvm_unreachable("Invalid branch code: should be expanded by legalize");
00657   // These are invalid for floating point.  Assume integer.
00658   case ISD::SETULT: return 0;
00659   case ISD::SETUGT: return 1;
00660   }
00661 }
00662 
00663 // getVCmpInst: return the vector compare instruction for the specified
00664 // vector type and condition code. Since this is for altivec specific code,
00665 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
00666 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
00667                                 bool HasVSX, bool &Swap, bool &Negate) {
00668   Swap = false;
00669   Negate = false;
00670 
00671   if (VecVT.isFloatingPoint()) {
00672     /* Handle some cases by swapping input operands.  */
00673     switch (CC) {
00674       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
00675       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
00676       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
00677       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
00678       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
00679       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
00680       default: break;
00681     }
00682     /* Handle some cases by negating the result.  */
00683     switch (CC) {
00684       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
00685       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
00686       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
00687       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
00688       default: break;
00689     }
00690     /* We have instructions implementing the remaining cases.  */
00691     switch (CC) {
00692       case ISD::SETEQ:
00693       case ISD::SETOEQ:
00694         if (VecVT == MVT::v4f32)
00695           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
00696         else if (VecVT == MVT::v2f64)
00697           return PPC::XVCMPEQDP;
00698         break;
00699       case ISD::SETGT:
00700       case ISD::SETOGT:
00701         if (VecVT == MVT::v4f32)
00702           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
00703         else if (VecVT == MVT::v2f64)
00704           return PPC::XVCMPGTDP;
00705         break;
00706       case ISD::SETGE:
00707       case ISD::SETOGE:
00708         if (VecVT == MVT::v4f32)
00709           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
00710         else if (VecVT == MVT::v2f64)
00711           return PPC::XVCMPGEDP;
00712         break;
00713       default:
00714         break;
00715     }
00716     llvm_unreachable("Invalid floating-point vector compare condition");
00717   } else {
00718     /* Handle some cases by swapping input operands.  */
00719     switch (CC) {
00720       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
00721       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
00722       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
00723       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
00724       default: break;
00725     }
00726     /* Handle some cases by negating the result.  */
00727     switch (CC) {
00728       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
00729       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
00730       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
00731       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
00732       default: break;
00733     }
00734     /* We have instructions implementing the remaining cases.  */
00735     switch (CC) {
00736       case ISD::SETEQ:
00737       case ISD::SETUEQ:
00738         if (VecVT == MVT::v16i8)
00739           return PPC::VCMPEQUB;
00740         else if (VecVT == MVT::v8i16)
00741           return PPC::VCMPEQUH;
00742         else if (VecVT == MVT::v4i32)
00743           return PPC::VCMPEQUW;
00744         break;
00745       case ISD::SETGT:
00746         if (VecVT == MVT::v16i8)
00747           return PPC::VCMPGTSB;
00748         else if (VecVT == MVT::v8i16)
00749           return PPC::VCMPGTSH;
00750         else if (VecVT == MVT::v4i32)
00751           return PPC::VCMPGTSW;
00752         break;
00753       case ISD::SETUGT:
00754         if (VecVT == MVT::v16i8)
00755           return PPC::VCMPGTUB;
00756         else if (VecVT == MVT::v8i16)
00757           return PPC::VCMPGTUH;
00758         else if (VecVT == MVT::v4i32)
00759           return PPC::VCMPGTUW;
00760         break;
00761       default:
00762         break;
00763     }
00764     llvm_unreachable("Invalid integer vector compare condition");
00765   }
00766 }
00767 
00768 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
00769   SDLoc dl(N);
00770   unsigned Imm;
00771   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
00772   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
00773   bool isPPC64 = (PtrVT == MVT::i64);
00774 
00775   if (!PPCSubTarget->useCRBits() &&
00776       isInt32Immediate(N->getOperand(1), Imm)) {
00777     // We can codegen setcc op, imm very efficiently compared to a brcond.
00778     // Check for those cases here.
00779     // setcc op, 0
00780     if (Imm == 0) {
00781       SDValue Op = N->getOperand(0);
00782       switch (CC) {
00783       default: break;
00784       case ISD::SETEQ: {
00785         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
00786         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
00787         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
00788       }
00789       case ISD::SETNE: {
00790         if (isPPC64) break;
00791         SDValue AD =
00792           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
00793                                          Op, getI32Imm(~0U)), 0);
00794         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
00795                                     AD.getValue(1));
00796       }
00797       case ISD::SETLT: {
00798         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
00799         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
00800       }
00801       case ISD::SETGT: {
00802         SDValue T =
00803           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
00804         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
00805         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
00806         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
00807       }
00808       }
00809     } else if (Imm == ~0U) {        // setcc op, -1
00810       SDValue Op = N->getOperand(0);
00811       switch (CC) {
00812       default: break;
00813       case ISD::SETEQ:
00814         if (isPPC64) break;
00815         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
00816                                             Op, getI32Imm(1)), 0);
00817         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
00818                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
00819                                                              MVT::i32,
00820                                                              getI32Imm(0)), 0),
00821                                       Op.getValue(1));
00822       case ISD::SETNE: {
00823         if (isPPC64) break;
00824         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
00825         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
00826                                             Op, getI32Imm(~0U));
00827         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
00828                                     Op, SDValue(AD, 1));
00829       }
00830       case ISD::SETLT: {
00831         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
00832                                                     getI32Imm(1)), 0);
00833         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
00834                                                     Op), 0);
00835         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
00836         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
00837       }
00838       case ISD::SETGT: {
00839         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
00840         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
00841                      0);
00842         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
00843                                     getI32Imm(1));
00844       }
00845       }
00846     }
00847   }
00848 
00849   SDValue LHS = N->getOperand(0);
00850   SDValue RHS = N->getOperand(1);
00851 
00852   // Altivec Vector compare instructions do not set any CR register by default and
00853   // vector compare operations return the same type as the operands.
00854   if (LHS.getValueType().isVector()) {
00855     EVT VecVT = LHS.getValueType();
00856     bool Swap, Negate;
00857     unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
00858                                         PPCSubTarget->hasVSX(), Swap, Negate);
00859     if (Swap)
00860       std::swap(LHS, RHS);
00861 
00862     if (Negate) {
00863       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
00864       return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
00865                                                               PPC::VNOR,
00866                                   VecVT, VCmp, VCmp);
00867     }
00868 
00869     return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
00870   }
00871 
00872   if (PPCSubTarget->useCRBits())
00873     return nullptr;
00874 
00875   bool Inv;
00876   unsigned Idx = getCRIdxForSetCC(CC, Inv);
00877   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
00878   SDValue IntCR;
00879 
00880   // Force the ccreg into CR7.
00881   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
00882 
00883   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
00884   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
00885                                InFlag).getValue(1);
00886 
00887   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
00888                                          CCReg), 0);
00889 
00890   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
00891                       getI32Imm(31), getI32Imm(31) };
00892   if (!Inv)
00893     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
00894 
00895   // Get the specified bit.
00896   SDValue Tmp =
00897     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
00898   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
00899 }
00900 
00901 
00902 // Select - Convert the specified operand from a target-independent to a
00903 // target-specific node if it hasn't already been changed.
00904 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
00905   SDLoc dl(N);
00906   if (N->isMachineOpcode()) {
00907     N->setNodeId(-1);
00908     return nullptr;   // Already selected.
00909   }
00910 
00911   // In case any misguided DAG-level optimizations form an ADD with a
00912   // TargetConstant operand, crash here instead of miscompiling (by selecting
00913   // an r+r add instead of some kind of r+i add).
00914   if (N->getOpcode() == ISD::ADD &&
00915       N->getOperand(1).getOpcode() == ISD::TargetConstant)
00916     llvm_unreachable("Invalid ADD with TargetConstant operand");
00917 
00918   switch (N->getOpcode()) {
00919   default: break;
00920 
00921   case ISD::Constant: {
00922     if (N->getValueType(0) == MVT::i64) {
00923       // Get 64 bit value.
00924       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
00925       // Assume no remaining bits.
00926       unsigned Remainder = 0;
00927       // Assume no shift required.
00928       unsigned Shift = 0;
00929 
00930       // If it can't be represented as a 32 bit value.
00931       if (!isInt<32>(Imm)) {
00932         Shift = countTrailingZeros<uint64_t>(Imm);
00933         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
00934 
00935         // If the shifted value fits 32 bits.
00936         if (isInt<32>(ImmSh)) {
00937           // Go with the shifted value.
00938           Imm = ImmSh;
00939         } else {
00940           // Still stuck with a 64 bit value.
00941           Remainder = Imm;
00942           Shift = 32;
00943           Imm >>= 32;
00944         }
00945       }
00946 
00947       // Intermediate operand.
00948       SDNode *Result;
00949 
00950       // Handle first 32 bits.
00951       unsigned Lo = Imm & 0xFFFF;
00952       unsigned Hi = (Imm >> 16) & 0xFFFF;
00953 
00954       // Simple value.
00955       if (isInt<16>(Imm)) {
00956        // Just the Lo bits.
00957         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
00958       } else if (Lo) {
00959         // Handle the Hi bits.
00960         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
00961         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
00962         // And Lo bits.
00963         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
00964                                         SDValue(Result, 0), getI32Imm(Lo));
00965       } else {
00966        // Just the Hi bits.
00967         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
00968       }
00969 
00970       // If no shift, we're done.
00971       if (!Shift) return Result;
00972 
00973       // Shift for next step if the upper 32-bits were not zero.
00974       if (Imm) {
00975         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
00976                                         SDValue(Result, 0),
00977                                         getI32Imm(Shift),
00978                                         getI32Imm(63 - Shift));
00979       }
00980 
00981       // Add in the last bits as required.
00982       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
00983         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
00984                                         SDValue(Result, 0), getI32Imm(Hi));
00985       }
00986       if ((Lo = Remainder & 0xFFFF)) {
00987         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
00988                                         SDValue(Result, 0), getI32Imm(Lo));
00989       }
00990 
00991       return Result;
00992     }
00993     break;
00994   }
00995 
00996   case ISD::SETCC: {
00997     SDNode *SN = SelectSETCC(N);
00998     if (SN)
00999       return SN;
01000     break;
01001   }
01002   case PPCISD::GlobalBaseReg:
01003     return getGlobalBaseReg();
01004 
01005   case ISD::FrameIndex: {
01006     int FI = cast<FrameIndexSDNode>(N)->getIndex();
01007     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
01008     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
01009     if (N->hasOneUse())
01010       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
01011                                   getSmallIPtrImm(0));
01012     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
01013                                   getSmallIPtrImm(0));
01014   }
01015 
01016   case PPCISD::MFOCRF: {
01017     SDValue InFlag = N->getOperand(1);
01018     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
01019                                   N->getOperand(0), InFlag);
01020   }
01021 
01022   case ISD::SDIV: {
01023     // FIXME: since this depends on the setting of the carry flag from the srawi
01024     //        we should really be making notes about that for the scheduler.
01025     // FIXME: It sure would be nice if we could cheaply recognize the
01026     //        srl/add/sra pattern the dag combiner will generate for this as
01027     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
01028     unsigned Imm;
01029     if (isInt32Immediate(N->getOperand(1), Imm)) {
01030       SDValue N0 = N->getOperand(0);
01031       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
01032         SDNode *Op =
01033           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
01034                                  N0, getI32Imm(Log2_32(Imm)));
01035         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
01036                                     SDValue(Op, 0), SDValue(Op, 1));
01037       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
01038         SDNode *Op =
01039           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
01040                                  N0, getI32Imm(Log2_32(-Imm)));
01041         SDValue PT =
01042           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
01043                                          SDValue(Op, 0), SDValue(Op, 1)),
01044                     0);
01045         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
01046       }
01047     }
01048 
01049     // Other cases are autogenerated.
01050     break;
01051   }
01052 
01053   case ISD::LOAD: {
01054     // Handle preincrement loads.
01055     LoadSDNode *LD = cast<LoadSDNode>(N);
01056     EVT LoadedVT = LD->getMemoryVT();
01057 
01058     // Normal loads are handled by code generated from the .td file.
01059     if (LD->getAddressingMode() != ISD::PRE_INC)
01060       break;
01061 
01062     SDValue Offset = LD->getOffset();
01063     if (Offset.getOpcode() == ISD::TargetConstant ||
01064         Offset.getOpcode() == ISD::TargetGlobalAddress) {
01065 
01066       unsigned Opcode;
01067       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
01068       if (LD->getValueType(0) != MVT::i64) {
01069         // Handle PPC32 integer and normal FP loads.
01070         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
01071         switch (LoadedVT.getSimpleVT().SimpleTy) {
01072           default: llvm_unreachable("Invalid PPC load type!");
01073           case MVT::f64: Opcode = PPC::LFDU; break;
01074           case MVT::f32: Opcode = PPC::LFSU; break;
01075           case MVT::i32: Opcode = PPC::LWZU; break;
01076           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
01077           case MVT::i1:
01078           case MVT::i8:  Opcode = PPC::LBZU; break;
01079         }
01080       } else {
01081         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
01082         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
01083         switch (LoadedVT.getSimpleVT().SimpleTy) {
01084           default: llvm_unreachable("Invalid PPC load type!");
01085           case MVT::i64: Opcode = PPC::LDU; break;
01086           case MVT::i32: Opcode = PPC::LWZU8; break;
01087           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
01088           case MVT::i1:
01089           case MVT::i8:  Opcode = PPC::LBZU8; break;
01090         }
01091       }
01092 
01093       SDValue Chain = LD->getChain();
01094       SDValue Base = LD->getBasePtr();
01095       SDValue Ops[] = { Offset, Base, Chain };
01096       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
01097                                     PPCLowering->getPointerTy(),
01098                                     MVT::Other, Ops);
01099     } else {
01100       unsigned Opcode;
01101       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
01102       if (LD->getValueType(0) != MVT::i64) {
01103         // Handle PPC32 integer and normal FP loads.
01104         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
01105         switch (LoadedVT.getSimpleVT().SimpleTy) {
01106           default: llvm_unreachable("Invalid PPC load type!");
01107           case MVT::f64: Opcode = PPC::LFDUX; break;
01108           case MVT::f32: Opcode = PPC::LFSUX; break;
01109           case MVT::i32: Opcode = PPC::LWZUX; break;
01110           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
01111           case MVT::i1:
01112           case MVT::i8:  Opcode = PPC::LBZUX; break;
01113         }
01114       } else {
01115         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
01116         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
01117                "Invalid sext update load");
01118         switch (LoadedVT.getSimpleVT().SimpleTy) {
01119           default: llvm_unreachable("Invalid PPC load type!");
01120           case MVT::i64: Opcode = PPC::LDUX; break;
01121           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
01122           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
01123           case MVT::i1:
01124           case MVT::i8:  Opcode = PPC::LBZUX8; break;
01125         }
01126       }
01127 
01128       SDValue Chain = LD->getChain();
01129       SDValue Base = LD->getBasePtr();
01130       SDValue Ops[] = { Base, Offset, Chain };
01131       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
01132                                     PPCLowering->getPointerTy(),
01133                                     MVT::Other, Ops);
01134     }
01135   }
01136 
01137   case ISD::AND: {
01138     unsigned Imm, Imm2, SH, MB, ME;
01139     uint64_t Imm64;
01140 
01141     // If this is an and of a value rotated between 0 and 31 bits and then and'd
01142     // with a mask, emit rlwinm
01143     if (isInt32Immediate(N->getOperand(1), Imm) &&
01144         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
01145       SDValue Val = N->getOperand(0).getOperand(0);
01146       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
01147       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
01148     }
01149     // If this is just a masked value where the input is not handled above, and
01150     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
01151     if (isInt32Immediate(N->getOperand(1), Imm) &&
01152         isRunOfOnes(Imm, MB, ME) &&
01153         N->getOperand(0).getOpcode() != ISD::ROTL) {
01154       SDValue Val = N->getOperand(0);
01155       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
01156       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
01157     }
01158     // If this is a 64-bit zero-extension mask, emit rldicl.
01159     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
01160         isMask_64(Imm64)) {
01161       SDValue Val = N->getOperand(0);
01162       MB = 64 - CountTrailingOnes_64(Imm64);
01163       SH = 0;
01164 
01165       // If the operand is a logical right shift, we can fold it into this
01166       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
01167       // for n <= mb. The right shift is really a left rotate followed by a
01168       // mask, and this mask is a more-restrictive sub-mask of the mask implied
01169       // by the shift.
01170       if (Val.getOpcode() == ISD::SRL &&
01171           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
01172         assert(Imm < 64 && "Illegal shift amount");
01173         Val = Val.getOperand(0);
01174         SH = 64 - Imm;
01175       }
01176 
01177       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
01178       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
01179     }
01180     // AND X, 0 -> 0, not "rlwinm 32".
01181     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
01182       ReplaceUses(SDValue(N, 0), N->getOperand(1));
01183       return nullptr;
01184     }
01185     // ISD::OR doesn't get all the bitfield insertion fun.
01186     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
01187     if (isInt32Immediate(N->getOperand(1), Imm) &&
01188         N->getOperand(0).getOpcode() == ISD::OR &&
01189         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
01190       unsigned MB, ME;
01191       Imm = ~(Imm^Imm2);
01192       if (isRunOfOnes(Imm, MB, ME)) {
01193         SDValue Ops[] = { N->getOperand(0).getOperand(0),
01194                             N->getOperand(0).getOperand(1),
01195                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
01196         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
01197       }
01198     }
01199 
01200     // Other cases are autogenerated.
01201     break;
01202   }
01203   case ISD::OR:
01204     if (N->getValueType(0) == MVT::i32)
01205       if (SDNode *I = SelectBitfieldInsert(N))
01206         return I;
01207 
01208     // Other cases are autogenerated.
01209     break;
01210   case ISD::SHL: {
01211     unsigned Imm, SH, MB, ME;
01212     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
01213         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
01214       SDValue Ops[] = { N->getOperand(0).getOperand(0),
01215                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
01216       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
01217     }
01218 
01219     // Other cases are autogenerated.
01220     break;
01221   }
01222   case ISD::SRL: {
01223     unsigned Imm, SH, MB, ME;
01224     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
01225         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
01226       SDValue Ops[] = { N->getOperand(0).getOperand(0),
01227                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
01228       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
01229     }
01230 
01231     // Other cases are autogenerated.
01232     break;
01233   }
01234   // FIXME: Remove this once the ANDI glue bug is fixed:
01235   case PPCISD::ANDIo_1_EQ_BIT:
01236   case PPCISD::ANDIo_1_GT_BIT: {
01237     if (!ANDIGlueBug)
01238       break;
01239 
01240     EVT InVT = N->getOperand(0).getValueType();
01241     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
01242            "Invalid input type for ANDIo_1_EQ_BIT");
01243 
01244     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
01245     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
01246                                         N->getOperand(0),
01247                                         CurDAG->getTargetConstant(1, InVT)), 0);
01248     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
01249     SDValue SRIdxVal =
01250       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
01251                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
01252 
01253     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
01254                                 CR0Reg, SRIdxVal,
01255                                 SDValue(AndI.getNode(), 1) /* glue */);
01256   }
01257   case ISD::SELECT_CC: {
01258     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
01259     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
01260     bool isPPC64 = (PtrVT == MVT::i64);
01261 
01262     // If this is a select of i1 operands, we'll pattern match it.
01263     if (PPCSubTarget->useCRBits() &&
01264         N->getOperand(0).getValueType() == MVT::i1)
01265       break;
01266 
01267     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
01268     if (!isPPC64)
01269       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
01270         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
01271           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
01272             if (N1C->isNullValue() && N3C->isNullValue() &&
01273                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
01274                 // FIXME: Implement this optzn for PPC64.
01275                 N->getValueType(0) == MVT::i32) {
01276               SDNode *Tmp =
01277                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
01278                                        N->getOperand(0), getI32Imm(~0U));
01279               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
01280                                           SDValue(Tmp, 0), N->getOperand(0),
01281                                           SDValue(Tmp, 1));
01282             }
01283 
01284     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
01285 
01286     if (N->getValueType(0) == MVT::i1) {
01287       // An i1 select is: (c & t) | (!c & f).
01288       bool Inv;
01289       unsigned Idx = getCRIdxForSetCC(CC, Inv);
01290 
01291       unsigned SRI;
01292       switch (Idx) {
01293       default: llvm_unreachable("Invalid CC index");
01294       case 0: SRI = PPC::sub_lt; break;
01295       case 1: SRI = PPC::sub_gt; break;
01296       case 2: SRI = PPC::sub_eq; break;
01297       case 3: SRI = PPC::sub_un; break;
01298       }
01299 
01300       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
01301 
01302       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
01303                                               CCBit, CCBit), 0);
01304       SDValue C =    Inv ? NotCCBit : CCBit,
01305               NotC = Inv ? CCBit    : NotCCBit;
01306 
01307       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
01308                                            C, N->getOperand(2)), 0);
01309       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
01310                                               NotC, N->getOperand(3)), 0);
01311 
01312       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
01313     }
01314 
01315     unsigned BROpc = getPredicateForSetCC(CC);
01316 
01317     unsigned SelectCCOp;
01318     if (N->getValueType(0) == MVT::i32)
01319       SelectCCOp = PPC::SELECT_CC_I4;
01320     else if (N->getValueType(0) == MVT::i64)
01321       SelectCCOp = PPC::SELECT_CC_I8;
01322     else if (N->getValueType(0) == MVT::f32)
01323       SelectCCOp = PPC::SELECT_CC_F4;
01324     else if (N->getValueType(0) == MVT::f64)
01325       SelectCCOp = PPC::SELECT_CC_F8;
01326     else
01327       SelectCCOp = PPC::SELECT_CC_VRRC;
01328 
01329     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
01330                         getI32Imm(BROpc) };
01331     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
01332   }
01333   case ISD::VSELECT:
01334     if (PPCSubTarget->hasVSX()) {
01335       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
01336       return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
01337     }
01338 
01339     break;
01340   case ISD::VECTOR_SHUFFLE:
01341     if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
01342                                   N->getValueType(0) == MVT::v2i64)) {
01343       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
01344       
01345       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
01346               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
01347       unsigned DM[2];
01348 
01349       for (int i = 0; i < 2; ++i)
01350         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
01351           DM[i] = 0;
01352         else
01353           DM[i] = 1;
01354 
01355       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
01356 
01357       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
01358           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
01359           isa<LoadSDNode>(Op1.getOperand(0))) {
01360         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
01361         SDValue Base, Offset;
01362 
01363         if (LD->isUnindexed() &&
01364             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
01365           SDValue Chain = LD->getChain();
01366           SDValue Ops[] = { Base, Offset, Chain };
01367           return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
01368                                       N->getValueType(0), Ops);
01369         }
01370       }
01371 
01372       SDValue Ops[] = { Op1, Op2, DMV };
01373       return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
01374     }
01375 
01376     break;
01377   case PPCISD::BDNZ:
01378   case PPCISD::BDZ: {
01379     bool IsPPC64 = PPCSubTarget->isPPC64();
01380     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
01381     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
01382                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01383                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
01384                                 MVT::Other, Ops);
01385   }
01386   case PPCISD::COND_BRANCH: {
01387     // Op #0 is the Chain.
01388     // Op #1 is the PPC::PRED_* number.
01389     // Op #2 is the CR#
01390     // Op #3 is the Dest MBB
01391     // Op #4 is the Flag.
01392     // Prevent PPC::PRED_* from being selected into LI.
01393     SDValue Pred =
01394       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
01395     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
01396       N->getOperand(0), N->getOperand(4) };
01397     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
01398   }
01399   case ISD::BR_CC: {
01400     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
01401     unsigned PCC = getPredicateForSetCC(CC);
01402 
01403     if (N->getOperand(2).getValueType() == MVT::i1) {
01404       unsigned Opc;
01405       bool Swap;
01406       switch (PCC) {
01407       default: llvm_unreachable("Unexpected Boolean-operand predicate");
01408       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
01409       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
01410       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
01411       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
01412       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
01413       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
01414       }
01415 
01416       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
01417                                              N->getOperand(Swap ? 3 : 2),
01418                                              N->getOperand(Swap ? 2 : 3)), 0);
01419       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
01420                                   BitComp, N->getOperand(4), N->getOperand(0));
01421     }
01422 
01423     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
01424     SDValue Ops[] = { getI32Imm(PCC), CondCode,
01425                         N->getOperand(4), N->getOperand(0) };
01426     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
01427   }
01428   case ISD::BRIND: {
01429     // FIXME: Should custom lower this.
01430     SDValue Chain = N->getOperand(0);
01431     SDValue Target = N->getOperand(1);
01432     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
01433     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
01434     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
01435                                            Chain), 0);
01436     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
01437   }
01438   case PPCISD::TOC_ENTRY: {
01439     if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
01440       SDValue GA = N->getOperand(0);
01441       return CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
01442                                     N->getOperand(1));
01443     }
01444     assert (PPCSubTarget->isPPC64() &&
01445             "Only supported for 64-bit ABI and 32-bit SVR4");
01446 
01447     // For medium and large code model, we generate two instructions as
01448     // described below.  Otherwise we allow SelectCodeCommon to handle this,
01449     // selecting one of LDtoc, LDtocJTI, and LDtocCPT.
01450     CodeModel::Model CModel = TM.getCodeModel();
01451     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
01452       break;
01453 
01454     // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
01455     // If it is an externally defined symbol, a symbol with common linkage,
01456     // a non-local function address, or a jump table address, or if we are
01457     // generating code for large code model, we generate:
01458     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
01459     // Otherwise we generate:
01460     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
01461     SDValue GA = N->getOperand(0);
01462     SDValue TOCbase = N->getOperand(1);
01463     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
01464                                         TOCbase, GA);
01465 
01466     if (isa<JumpTableSDNode>(GA) || CModel == CodeModel::Large)
01467       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
01468                                     SDValue(Tmp, 0));
01469 
01470     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
01471       const GlobalValue *GValue = G->getGlobal();
01472       if ((GValue->getType()->getElementType()->isFunctionTy() &&
01473            (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
01474           GValue->isDeclaration() || GValue->hasCommonLinkage() ||
01475           GValue->hasAvailableExternallyLinkage())
01476         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
01477                                       SDValue(Tmp, 0));
01478     }
01479 
01480     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
01481                                   SDValue(Tmp, 0), GA);
01482   }
01483   case PPCISD::PPC32_PICGOT: {
01484     // Generate a PIC-safe GOT reference.
01485     assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
01486       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
01487     return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(),  MVT::i32);
01488   }
01489   case PPCISD::VADD_SPLAT: {
01490     // This expands into one of three sequences, depending on whether
01491     // the first operand is odd or even, positive or negative.
01492     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
01493            isa<ConstantSDNode>(N->getOperand(1)) &&
01494            "Invalid operand on VADD_SPLAT!");
01495 
01496     int Elt     = N->getConstantOperandVal(0);
01497     int EltSize = N->getConstantOperandVal(1);
01498     unsigned Opc1, Opc2, Opc3;
01499     EVT VT;
01500 
01501     if (EltSize == 1) {
01502       Opc1 = PPC::VSPLTISB;
01503       Opc2 = PPC::VADDUBM;
01504       Opc3 = PPC::VSUBUBM;
01505       VT = MVT::v16i8;
01506     } else if (EltSize == 2) {
01507       Opc1 = PPC::VSPLTISH;
01508       Opc2 = PPC::VADDUHM;
01509       Opc3 = PPC::VSUBUHM;
01510       VT = MVT::v8i16;
01511     } else {
01512       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
01513       Opc1 = PPC::VSPLTISW;
01514       Opc2 = PPC::VADDUWM;
01515       Opc3 = PPC::VSUBUWM;
01516       VT = MVT::v4i32;
01517     }
01518 
01519     if ((Elt & 1) == 0) {
01520       // Elt is even, in the range [-32,-18] + [16,30].
01521       //
01522       // Convert: VADD_SPLAT elt, size
01523       // Into:    tmp = VSPLTIS[BHW] elt
01524       //          VADDU[BHW]M tmp, tmp
01525       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
01526       SDValue EltVal = getI32Imm(Elt >> 1);
01527       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
01528       SDValue TmpVal = SDValue(Tmp, 0);
01529       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
01530 
01531     } else if (Elt > 0) {
01532       // Elt is odd and positive, in the range [17,31].
01533       //
01534       // Convert: VADD_SPLAT elt, size
01535       // Into:    tmp1 = VSPLTIS[BHW] elt-16
01536       //          tmp2 = VSPLTIS[BHW] -16
01537       //          VSUBU[BHW]M tmp1, tmp2
01538       SDValue EltVal = getI32Imm(Elt - 16);
01539       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
01540       EltVal = getI32Imm(-16);
01541       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
01542       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
01543                                     SDValue(Tmp2, 0));
01544 
01545     } else {
01546       // Elt is odd and negative, in the range [-31,-17].
01547       //
01548       // Convert: VADD_SPLAT elt, size
01549       // Into:    tmp1 = VSPLTIS[BHW] elt+16
01550       //          tmp2 = VSPLTIS[BHW] -16
01551       //          VADDU[BHW]M tmp1, tmp2
01552       SDValue EltVal = getI32Imm(Elt + 16);
01553       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
01554       EltVal = getI32Imm(-16);
01555       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
01556       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
01557                                     SDValue(Tmp2, 0));
01558     }
01559   }
01560   }
01561 
01562   return SelectCode(N);
01563 }
01564 
01565 /// PostprocessISelDAG - Perform some late peephole optimizations
01566 /// on the DAG representation.
01567 void PPCDAGToDAGISel::PostprocessISelDAG() {
01568 
01569   // Skip peepholes at -O0.
01570   if (TM.getOptLevel() == CodeGenOpt::None)
01571     return;
01572 
01573   PeepholePPC64();
01574   PeepholeCROps();
01575 }
01576 
01577 // Check if all users of this node will become isel where the second operand
01578 // is the constant zero. If this is so, and if we can negate the condition,
01579 // then we can flip the true and false operands. This will allow the zero to
01580 // be folded with the isel so that we don't need to materialize a register
01581 // containing zero.
01582 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
01583   // If we're not using isel, then this does not matter.
01584   if (!PPCSubTarget->hasISEL())
01585     return false;
01586 
01587   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
01588        UI != UE; ++UI) {
01589     SDNode *User = *UI;
01590     if (!User->isMachineOpcode())
01591       return false;
01592     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
01593         User->getMachineOpcode() != PPC::SELECT_I8)
01594       return false;
01595 
01596     SDNode *Op2 = User->getOperand(2).getNode();
01597     if (!Op2->isMachineOpcode())
01598       return false;
01599 
01600     if (Op2->getMachineOpcode() != PPC::LI &&
01601         Op2->getMachineOpcode() != PPC::LI8)
01602       return false;
01603 
01604     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
01605     if (!C)
01606       return false;
01607 
01608     if (!C->isNullValue())
01609       return false;
01610   }
01611 
01612   return true;
01613 }
01614 
01615 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
01616   SmallVector<SDNode *, 4> ToReplace;
01617   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
01618        UI != UE; ++UI) {
01619     SDNode *User = *UI;
01620     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
01621             User->getMachineOpcode() == PPC::SELECT_I8) &&
01622            "Must have all select users");
01623     ToReplace.push_back(User);
01624   }
01625 
01626   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
01627        UE = ToReplace.end(); UI != UE; ++UI) {
01628     SDNode *User = *UI;
01629     SDNode *ResNode =
01630       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
01631                              User->getValueType(0), User->getOperand(0),
01632                              User->getOperand(2),
01633                              User->getOperand(1));
01634 
01635       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
01636       DEBUG(User->dump(CurDAG));
01637       DEBUG(dbgs() << "\nNew: ");
01638       DEBUG(ResNode->dump(CurDAG));
01639       DEBUG(dbgs() << "\n");
01640 
01641       ReplaceUses(User, ResNode);
01642   }
01643 }
01644 
01645 void PPCDAGToDAGISel::PeepholeCROps() {
01646   bool IsModified;
01647   do {
01648     IsModified = false;
01649     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
01650          E = CurDAG->allnodes_end(); I != E; ++I) {
01651       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
01652       if (!MachineNode || MachineNode->use_empty())
01653         continue;
01654       SDNode *ResNode = MachineNode;
01655 
01656       bool Op1Set   = false, Op1Unset = false,
01657            Op1Not   = false,
01658            Op2Set   = false, Op2Unset = false,
01659            Op2Not   = false;
01660 
01661       unsigned Opcode = MachineNode->getMachineOpcode();
01662       switch (Opcode) {
01663       default: break;
01664       case PPC::CRAND:
01665       case PPC::CRNAND:
01666       case PPC::CROR:
01667       case PPC::CRXOR:
01668       case PPC::CRNOR:
01669       case PPC::CREQV:
01670       case PPC::CRANDC:
01671       case PPC::CRORC: {
01672         SDValue Op = MachineNode->getOperand(1);
01673         if (Op.isMachineOpcode()) {
01674           if (Op.getMachineOpcode() == PPC::CRSET)
01675             Op2Set = true;
01676           else if (Op.getMachineOpcode() == PPC::CRUNSET)
01677             Op2Unset = true;
01678           else if (Op.getMachineOpcode() == PPC::CRNOR &&
01679                    Op.getOperand(0) == Op.getOperand(1))
01680             Op2Not = true;
01681         }
01682         }  // fallthrough
01683       case PPC::BC:
01684       case PPC::BCn:
01685       case PPC::SELECT_I4:
01686       case PPC::SELECT_I8:
01687       case PPC::SELECT_F4:
01688       case PPC::SELECT_F8:
01689       case PPC::SELECT_VRRC: {
01690         SDValue Op = MachineNode->getOperand(0);
01691         if (Op.isMachineOpcode()) {
01692           if (Op.getMachineOpcode() == PPC::CRSET)
01693             Op1Set = true;
01694           else if (Op.getMachineOpcode() == PPC::CRUNSET)
01695             Op1Unset = true;
01696           else if (Op.getMachineOpcode() == PPC::CRNOR &&
01697                    Op.getOperand(0) == Op.getOperand(1))
01698             Op1Not = true;
01699         }
01700         }
01701         break;
01702       }
01703 
01704       bool SelectSwap = false;
01705       switch (Opcode) {
01706       default: break;
01707       case PPC::CRAND:
01708         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01709           // x & x = x
01710           ResNode = MachineNode->getOperand(0).getNode();
01711         else if (Op1Set)
01712           // 1 & y = y
01713           ResNode = MachineNode->getOperand(1).getNode();
01714         else if (Op2Set)
01715           // x & 1 = x
01716           ResNode = MachineNode->getOperand(0).getNode();
01717         else if (Op1Unset || Op2Unset)
01718           // x & 0 = 0 & y = 0
01719           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
01720                                            MVT::i1);
01721         else if (Op1Not)
01722           // ~x & y = andc(y, x)
01723           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
01724                                            MVT::i1, MachineNode->getOperand(1),
01725                                            MachineNode->getOperand(0).
01726                                              getOperand(0));
01727         else if (Op2Not)
01728           // x & ~y = andc(x, y)
01729           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
01730                                            MVT::i1, MachineNode->getOperand(0),
01731                                            MachineNode->getOperand(1).
01732                                              getOperand(0));
01733         else if (AllUsersSelectZero(MachineNode))
01734           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
01735                                            MVT::i1, MachineNode->getOperand(0),
01736                                            MachineNode->getOperand(1)),
01737           SelectSwap = true;
01738         break;
01739       case PPC::CRNAND:
01740         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01741           // nand(x, x) -> nor(x, x)
01742           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01743                                            MVT::i1, MachineNode->getOperand(0),
01744                                            MachineNode->getOperand(0));
01745         else if (Op1Set)
01746           // nand(1, y) -> nor(y, y)
01747           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01748                                            MVT::i1, MachineNode->getOperand(1),
01749                                            MachineNode->getOperand(1));
01750         else if (Op2Set)
01751           // nand(x, 1) -> nor(x, x)
01752           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01753                                            MVT::i1, MachineNode->getOperand(0),
01754                                            MachineNode->getOperand(0));
01755         else if (Op1Unset || Op2Unset)
01756           // nand(x, 0) = nand(0, y) = 1
01757           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
01758                                            MVT::i1);
01759         else if (Op1Not)
01760           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
01761           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
01762                                            MVT::i1, MachineNode->getOperand(0).
01763                                                       getOperand(0),
01764                                            MachineNode->getOperand(1));
01765         else if (Op2Not)
01766           // nand(x, ~y) = ~x | y = orc(y, x)
01767           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
01768                                            MVT::i1, MachineNode->getOperand(1).
01769                                                       getOperand(0),
01770                                            MachineNode->getOperand(0));
01771         else if (AllUsersSelectZero(MachineNode))
01772           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
01773                                            MVT::i1, MachineNode->getOperand(0),
01774                                            MachineNode->getOperand(1)),
01775           SelectSwap = true;
01776         break;
01777       case PPC::CROR:
01778         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01779           // x | x = x
01780           ResNode = MachineNode->getOperand(0).getNode();
01781         else if (Op1Set || Op2Set)
01782           // x | 1 = 1 | y = 1
01783           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
01784                                            MVT::i1);
01785         else if (Op1Unset)
01786           // 0 | y = y
01787           ResNode = MachineNode->getOperand(1).getNode();
01788         else if (Op2Unset)
01789           // x | 0 = x
01790           ResNode = MachineNode->getOperand(0).getNode();
01791         else if (Op1Not)
01792           // ~x | y = orc(y, x)
01793           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
01794                                            MVT::i1, MachineNode->getOperand(1),
01795                                            MachineNode->getOperand(0).
01796                                              getOperand(0));
01797         else if (Op2Not)
01798           // x | ~y = orc(x, y)
01799           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
01800                                            MVT::i1, MachineNode->getOperand(0),
01801                                            MachineNode->getOperand(1).
01802                                              getOperand(0));
01803         else if (AllUsersSelectZero(MachineNode))
01804           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01805                                            MVT::i1, MachineNode->getOperand(0),
01806                                            MachineNode->getOperand(1)),
01807           SelectSwap = true;
01808         break;
01809       case PPC::CRXOR:
01810         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01811           // xor(x, x) = 0
01812           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
01813                                            MVT::i1);
01814         else if (Op1Set)
01815           // xor(1, y) -> nor(y, y)
01816           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01817                                            MVT::i1, MachineNode->getOperand(1),
01818                                            MachineNode->getOperand(1));
01819         else if (Op2Set)
01820           // xor(x, 1) -> nor(x, x)
01821           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01822                                            MVT::i1, MachineNode->getOperand(0),
01823                                            MachineNode->getOperand(0));
01824         else if (Op1Unset)
01825           // xor(0, y) = y
01826           ResNode = MachineNode->getOperand(1).getNode();
01827         else if (Op2Unset)
01828           // xor(x, 0) = x
01829           ResNode = MachineNode->getOperand(0).getNode();
01830         else if (Op1Not)
01831           // xor(~x, y) = eqv(x, y)
01832           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
01833                                            MVT::i1, MachineNode->getOperand(0).
01834                                                       getOperand(0),
01835                                            MachineNode->getOperand(1));
01836         else if (Op2Not)
01837           // xor(x, ~y) = eqv(x, y)
01838           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
01839                                            MVT::i1, MachineNode->getOperand(0),
01840                                            MachineNode->getOperand(1).
01841                                              getOperand(0));
01842         else if (AllUsersSelectZero(MachineNode))
01843           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
01844                                            MVT::i1, MachineNode->getOperand(0),
01845                                            MachineNode->getOperand(1)),
01846           SelectSwap = true;
01847         break;
01848       case PPC::CRNOR:
01849         if (Op1Set || Op2Set)
01850           // nor(1, y) -> 0
01851           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
01852                                            MVT::i1);
01853         else if (Op1Unset)
01854           // nor(0, y) = ~y -> nor(y, y)
01855           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01856                                            MVT::i1, MachineNode->getOperand(1),
01857                                            MachineNode->getOperand(1));
01858         else if (Op2Unset)
01859           // nor(x, 0) = ~x
01860           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01861                                            MVT::i1, MachineNode->getOperand(0),
01862                                            MachineNode->getOperand(0));
01863         else if (Op1Not)
01864           // nor(~x, y) = andc(x, y)
01865           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
01866                                            MVT::i1, MachineNode->getOperand(0).
01867                                                       getOperand(0),
01868                                            MachineNode->getOperand(1));
01869         else if (Op2Not)
01870           // nor(x, ~y) = andc(y, x)
01871           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
01872                                            MVT::i1, MachineNode->getOperand(1).
01873                                                       getOperand(0),
01874                                            MachineNode->getOperand(0));
01875         else if (AllUsersSelectZero(MachineNode))
01876           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
01877                                            MVT::i1, MachineNode->getOperand(0),
01878                                            MachineNode->getOperand(1)),
01879           SelectSwap = true;
01880         break;
01881       case PPC::CREQV:
01882         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01883           // eqv(x, x) = 1
01884           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
01885                                            MVT::i1);
01886         else if (Op1Set)
01887           // eqv(1, y) = y
01888           ResNode = MachineNode->getOperand(1).getNode();
01889         else if (Op2Set)
01890           // eqv(x, 1) = x
01891           ResNode = MachineNode->getOperand(0).getNode();
01892         else if (Op1Unset)
01893           // eqv(0, y) = ~y -> nor(y, y)
01894           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01895                                            MVT::i1, MachineNode->getOperand(1),
01896                                            MachineNode->getOperand(1));
01897         else if (Op2Unset)
01898           // eqv(x, 0) = ~x
01899           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01900                                            MVT::i1, MachineNode->getOperand(0),
01901                                            MachineNode->getOperand(0));
01902         else if (Op1Not)
01903           // eqv(~x, y) = xor(x, y)
01904           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
01905                                            MVT::i1, MachineNode->getOperand(0).
01906                                                       getOperand(0),
01907                                            MachineNode->getOperand(1));
01908         else if (Op2Not)
01909           // eqv(x, ~y) = xor(x, y)
01910           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
01911                                            MVT::i1, MachineNode->getOperand(0),
01912                                            MachineNode->getOperand(1).
01913                                              getOperand(0));
01914         else if (AllUsersSelectZero(MachineNode))
01915           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
01916                                            MVT::i1, MachineNode->getOperand(0),
01917                                            MachineNode->getOperand(1)),
01918           SelectSwap = true;
01919         break;
01920       case PPC::CRANDC:
01921         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01922           // andc(x, x) = 0
01923           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
01924                                            MVT::i1);
01925         else if (Op1Set)
01926           // andc(1, y) = ~y
01927           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01928                                            MVT::i1, MachineNode->getOperand(1),
01929                                            MachineNode->getOperand(1));
01930         else if (Op1Unset || Op2Set)
01931           // andc(0, y) = andc(x, 1) = 0
01932           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
01933                                            MVT::i1);
01934         else if (Op2Unset)
01935           // andc(x, 0) = x
01936           ResNode = MachineNode->getOperand(0).getNode();
01937         else if (Op1Not)
01938           // andc(~x, y) = ~(x | y) = nor(x, y)
01939           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01940                                            MVT::i1, MachineNode->getOperand(0).
01941                                                       getOperand(0),
01942                                            MachineNode->getOperand(1));
01943         else if (Op2Not)
01944           // andc(x, ~y) = x & y
01945           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
01946                                            MVT::i1, MachineNode->getOperand(0),
01947                                            MachineNode->getOperand(1).
01948                                              getOperand(0));
01949         else if (AllUsersSelectZero(MachineNode))
01950           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
01951                                            MVT::i1, MachineNode->getOperand(1),
01952                                            MachineNode->getOperand(0)),
01953           SelectSwap = true;
01954         break;
01955       case PPC::CRORC:
01956         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
01957           // orc(x, x) = 1
01958           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
01959                                            MVT::i1);
01960         else if (Op1Set || Op2Unset)
01961           // orc(1, y) = orc(x, 0) = 1
01962           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
01963                                            MVT::i1);
01964         else if (Op2Set)
01965           // orc(x, 1) = x
01966           ResNode = MachineNode->getOperand(0).getNode();
01967         else if (Op1Unset)
01968           // orc(0, y) = ~y
01969           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
01970                                            MVT::i1, MachineNode->getOperand(1),
01971                                            MachineNode->getOperand(1));
01972         else if (Op1Not)
01973           // orc(~x, y) = ~(x & y) = nand(x, y)
01974           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
01975                                            MVT::i1, MachineNode->getOperand(0).
01976                                                       getOperand(0),
01977                                            MachineNode->getOperand(1));
01978         else if (Op2Not)
01979           // orc(x, ~y) = x | y
01980           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
01981                                            MVT::i1, MachineNode->getOperand(0),
01982                                            MachineNode->getOperand(1).
01983                                              getOperand(0));
01984         else if (AllUsersSelectZero(MachineNode))
01985           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
01986                                            MVT::i1, MachineNode->getOperand(1),
01987                                            MachineNode->getOperand(0)),
01988           SelectSwap = true;
01989         break;
01990       case PPC::SELECT_I4:
01991       case PPC::SELECT_I8:
01992       case PPC::SELECT_F4:
01993       case PPC::SELECT_F8:
01994       case PPC::SELECT_VRRC:
01995         if (Op1Set)
01996           ResNode = MachineNode->getOperand(1).getNode();
01997         else if (Op1Unset)
01998           ResNode = MachineNode->getOperand(2).getNode();
01999         else if (Op1Not)
02000           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
02001                                            SDLoc(MachineNode),
02002                                            MachineNode->getValueType(0),
02003                                            MachineNode->getOperand(0).
02004                                              getOperand(0),
02005                                            MachineNode->getOperand(2),
02006                                            MachineNode->getOperand(1));
02007         break;
02008       case PPC::BC:
02009       case PPC::BCn:
02010         if (Op1Not)
02011           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
02012                                                                PPC::BC,
02013                                            SDLoc(MachineNode),
02014                                            MVT::Other,
02015                                            MachineNode->getOperand(0).
02016                                              getOperand(0),
02017                                            MachineNode->getOperand(1),
02018                                            MachineNode->getOperand(2));
02019         // FIXME: Handle Op1Set, Op1Unset here too.
02020         break;
02021       }
02022 
02023       // If we're inverting this node because it is used only by selects that
02024       // we'd like to swap, then swap the selects before the node replacement.
02025       if (SelectSwap)
02026         SwapAllSelectUsers(MachineNode);
02027 
02028       if (ResNode != MachineNode) {
02029         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
02030         DEBUG(MachineNode->dump(CurDAG));
02031         DEBUG(dbgs() << "\nNew: ");
02032         DEBUG(ResNode->dump(CurDAG));
02033         DEBUG(dbgs() << "\n");
02034 
02035         ReplaceUses(MachineNode, ResNode);
02036         IsModified = true;
02037       }
02038     }
02039     if (IsModified)
02040       CurDAG->RemoveDeadNodes();
02041   } while (IsModified);
02042 }
02043 
02044 void PPCDAGToDAGISel::PeepholePPC64() {
02045   // These optimizations are currently supported only for 64-bit SVR4.
02046   if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
02047     return;
02048 
02049   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
02050   ++Position;
02051 
02052   while (Position != CurDAG->allnodes_begin()) {
02053     SDNode *N = --Position;
02054     // Skip dead nodes and any non-machine opcodes.
02055     if (N->use_empty() || !N->isMachineOpcode())
02056       continue;
02057 
02058     unsigned FirstOp;
02059     unsigned StorageOpcode = N->getMachineOpcode();
02060 
02061     switch (StorageOpcode) {
02062     default: continue;
02063 
02064     case PPC::LBZ:
02065     case PPC::LBZ8:
02066     case PPC::LD:
02067     case PPC::LFD:
02068     case PPC::LFS:
02069     case PPC::LHA:
02070     case PPC::LHA8:
02071     case PPC::LHZ:
02072     case PPC::LHZ8:
02073     case PPC::LWA:
02074     case PPC::LWZ:
02075     case PPC::LWZ8:
02076       FirstOp = 0;
02077       break;
02078 
02079     case PPC::STB:
02080     case PPC::STB8:
02081     case PPC::STD:
02082     case PPC::STFD:
02083     case PPC::STFS:
02084     case PPC::STH:
02085     case PPC::STH8:
02086     case PPC::STW:
02087     case PPC::STW8:
02088       FirstOp = 1;
02089       break;
02090     }
02091 
02092     // If this is a load or store with a zero offset, we may be able to
02093     // fold an add-immediate into the memory operation.
02094     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
02095         N->getConstantOperandVal(FirstOp) != 0)
02096       continue;
02097 
02098     SDValue Base = N->getOperand(FirstOp + 1);
02099     if (!Base.isMachineOpcode())
02100       continue;
02101 
02102     unsigned Flags = 0;
02103     bool ReplaceFlags = true;
02104 
02105     // When the feeding operation is an add-immediate of some sort,
02106     // determine whether we need to add relocation information to the
02107     // target flags on the immediate operand when we fold it into the
02108     // load instruction.
02109     //
02110     // For something like ADDItocL, the relocation information is
02111     // inferred from the opcode; when we process it in the AsmPrinter,
02112     // we add the necessary relocation there.  A load, though, can receive
02113     // relocation from various flavors of ADDIxxx, so we need to carry
02114     // the relocation information in the target flags.
02115     switch (Base.getMachineOpcode()) {
02116     default: continue;
02117 
02118     case PPC::ADDI8:
02119     case PPC::ADDI:
02120       // In some cases (such as TLS) the relocation information
02121       // is already in place on the operand, so copying the operand
02122       // is sufficient.
02123       ReplaceFlags = false;
02124       // For these cases, the immediate may not be divisible by 4, in
02125       // which case the fold is illegal for DS-form instructions.  (The
02126       // other cases provide aligned addresses and are always safe.)
02127       if ((StorageOpcode == PPC::LWA ||
02128            StorageOpcode == PPC::LD  ||
02129            StorageOpcode == PPC::STD) &&
02130           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
02131            Base.getConstantOperandVal(1) % 4 != 0))
02132         continue;
02133       break;
02134     case PPC::ADDIdtprelL:
02135       Flags = PPCII::MO_DTPREL_LO;
02136       break;
02137     case PPC::ADDItlsldL:
02138       Flags = PPCII::MO_TLSLD_LO;
02139       break;
02140     case PPC::ADDItocL:
02141       Flags = PPCII::MO_TOC_LO;
02142       break;
02143     }
02144 
02145     // We found an opportunity.  Reverse the operands from the add
02146     // immediate and substitute them into the load or store.  If
02147     // needed, update the target flags for the immediate operand to
02148     // reflect the necessary relocation information.
02149     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
02150     DEBUG(Base->dump(CurDAG));
02151     DEBUG(dbgs() << "\nN: ");
02152     DEBUG(N->dump(CurDAG));
02153     DEBUG(dbgs() << "\n");
02154 
02155     SDValue ImmOpnd = Base.getOperand(1);
02156 
02157     // If the relocation information isn't already present on the
02158     // immediate operand, add it now.
02159     if (ReplaceFlags) {
02160       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
02161         SDLoc dl(GA);
02162         const GlobalValue *GV = GA->getGlobal();
02163         // We can't perform this optimization for data whose alignment
02164         // is insufficient for the instruction encoding.
02165         if (GV->getAlignment() < 4 &&
02166             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
02167              StorageOpcode == PPC::LWA)) {
02168           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
02169           continue;
02170         }
02171         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
02172       } else if (ConstantPoolSDNode *CP =
02173                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
02174         const Constant *C = CP->getConstVal();
02175         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
02176                                                 CP->getAlignment(),
02177                                                 0, Flags);
02178       }
02179     }
02180 
02181     if (FirstOp == 1) // Store
02182       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
02183                                        Base.getOperand(0), N->getOperand(3));
02184     else // Load
02185       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
02186                                        N->getOperand(2));
02187 
02188     // The add-immediate may now be dead, in which case remove it.
02189     if (Base.getNode()->use_empty())
02190       CurDAG->RemoveDeadNode(Base.getNode());
02191   }
02192 }
02193 
02194 
02195 /// createPPCISelDag - This pass converts a legalized DAG into a
02196 /// PowerPC-specific DAG, ready for instruction scheduling.
02197 ///
02198 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
02199   return new PPCDAGToDAGISel(TM);
02200 }
02201 
02202 static void initializePassOnce(PassRegistry &Registry) {
02203   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
02204   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
02205                               nullptr, false, false);
02206   Registry.registerPass(*PI, true);
02207 }
02208 
02209 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
02210   CALL_ONCE_INITIALIZATION(initializePassOnce);
02211 }
02212