LLVM API Documentation

PPCISelLowering.cpp

Go to the documentation of this file.
00001 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
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 implements the PPCISelLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCISelLowering.h"
00015 #include "PPCMachineFunctionInfo.h"
00016 #include "PPCPredicates.h"
00017 #include "PPCTargetMachine.h"
00018 #include "PPCPerfectShuffle.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/VectorExtras.h"
00021 #include "llvm/CodeGen/CallingConvLower.h"
00022 #include "llvm/CodeGen/MachineFrameInfo.h"
00023 #include "llvm/CodeGen/MachineFunction.h"
00024 #include "llvm/CodeGen/MachineInstrBuilder.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/CodeGen/PseudoSourceValue.h"
00027 #include "llvm/CodeGen/SelectionDAG.h"
00028 #include "llvm/CallingConv.h"
00029 #include "llvm/Constants.h"
00030 #include "llvm/Function.h"
00031 #include "llvm/Intrinsics.h"
00032 #include "llvm/Support/MathExtras.h"
00033 #include "llvm/Target/TargetOptions.h"
00034 #include "llvm/Support/CommandLine.h"
00035 using namespace llvm;
00036 
00037 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc", 
00038 cl::desc("enable preincrement load/store generation on PPC (experimental)"),
00039                                      cl::Hidden);
00040 
00041 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
00042   : TargetLowering(TM), PPCSubTarget(*TM.getSubtargetImpl()) {
00043     
00044   setPow2DivIsCheap();
00045 
00046   // Use _setjmp/_longjmp instead of setjmp/longjmp.
00047   setUseUnderscoreSetJmp(true);
00048   setUseUnderscoreLongJmp(true);
00049     
00050   // Set up the register classes.
00051   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
00052   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
00053   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
00054   
00055   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
00056   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00057   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
00058 
00059   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00060     
00061   // PowerPC has pre-inc load and store's.
00062   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
00063   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
00064   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
00065   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
00066   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
00067   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
00068   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
00069   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
00070   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
00071   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
00072 
00073   // Shortening conversions involving ppcf128 get expanded (2 regs -> 1 reg)
00074   setConvertAction(MVT::ppcf128, MVT::f64, Expand);
00075   setConvertAction(MVT::ppcf128, MVT::f32, Expand);
00076   // This is used in the ppcf128->int sequence.  Note it has different semantics
00077   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
00078   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
00079 
00080   // PowerPC has no SREM/UREM instructions
00081   setOperationAction(ISD::SREM, MVT::i32, Expand);
00082   setOperationAction(ISD::UREM, MVT::i32, Expand);
00083   setOperationAction(ISD::SREM, MVT::i64, Expand);
00084   setOperationAction(ISD::UREM, MVT::i64, Expand);
00085 
00086   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
00087   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00088   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00089   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
00090   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
00091   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00092   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00093   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
00094   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
00095   
00096   // We don't support sin/cos/sqrt/fmod/pow
00097   setOperationAction(ISD::FSIN , MVT::f64, Expand);
00098   setOperationAction(ISD::FCOS , MVT::f64, Expand);
00099   setOperationAction(ISD::FREM , MVT::f64, Expand);
00100   setOperationAction(ISD::FPOW , MVT::f64, Expand);
00101   setOperationAction(ISD::FSIN , MVT::f32, Expand);
00102   setOperationAction(ISD::FCOS , MVT::f32, Expand);
00103   setOperationAction(ISD::FREM , MVT::f32, Expand);
00104   setOperationAction(ISD::FPOW , MVT::f32, Expand);
00105 
00106   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00107   
00108   // If we're enabling GP optimizations, use hardware square root
00109   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
00110     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
00111     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
00112   }
00113   
00114   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00115   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
00116   
00117   // PowerPC does not have BSWAP, CTPOP or CTTZ
00118   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
00119   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
00120   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
00121   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
00122   setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
00123   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
00124   
00125   // PowerPC does not have ROTR
00126   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
00127   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
00128   
00129   // PowerPC does not have Select
00130   setOperationAction(ISD::SELECT, MVT::i32, Expand);
00131   setOperationAction(ISD::SELECT, MVT::i64, Expand);
00132   setOperationAction(ISD::SELECT, MVT::f32, Expand);
00133   setOperationAction(ISD::SELECT, MVT::f64, Expand);
00134   
00135   // PowerPC wants to turn select_cc of FP into fsel when possible.
00136   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00137   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00138 
00139   // PowerPC wants to optimize integer setcc a bit
00140   setOperationAction(ISD::SETCC, MVT::i32, Custom);
00141   
00142   // PowerPC does not have BRCOND which requires SetCC
00143   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00144 
00145   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
00146   
00147   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
00148   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00149 
00150   // PowerPC does not have [U|S]INT_TO_FP
00151   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
00152   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
00153 
00154   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
00155   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
00156   setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
00157   setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
00158 
00159   // We cannot sextinreg(i1).  Expand to shifts.
00160   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00161 
00162   // Support label based line numbers.
00163   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
00164   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
00165   
00166   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
00167   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
00168   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
00169   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
00170   
00171   
00172   // We want to legalize GlobalAddress and ConstantPool nodes into the 
00173   // appropriate instructions to materialize the address.
00174   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
00175   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00176   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
00177   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
00178   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
00179   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
00180   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
00181   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
00182   
00183   // RET must be custom lowered, to meet ABI requirements.
00184   setOperationAction(ISD::RET               , MVT::Other, Custom);
00185 
00186   // TRAP is legal.
00187   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00188 
00189   // TRAMPOLINE is custom lowered.
00190   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
00191 
00192   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
00193   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
00194   
00195   // VAARG is custom lowered with ELF 32 ABI
00196   if (TM.getSubtarget<PPCSubtarget>().isELF32_ABI())
00197     setOperationAction(ISD::VAARG, MVT::Other, Custom);
00198   else
00199     setOperationAction(ISD::VAARG, MVT::Other, Expand);
00200   
00201   // Use the default implementation.
00202   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
00203   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
00204   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
00205   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
00206   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
00207   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
00208 
00209   // We want to custom lower some of our intrinsics.
00210   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00211   
00212   // Comparisons that require checking two conditions.
00213   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
00214   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
00215   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
00216   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
00217   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
00218   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
00219   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
00220   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
00221   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
00222   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
00223   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
00224   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
00225     
00226   if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
00227     // They also have instructions for converting between i64 and fp.
00228     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
00229     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
00230     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
00231     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
00232     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
00233  
00234     // FIXME: disable this lowered code.  This generates 64-bit register values,
00235     // and we don't model the fact that the top part is clobbered by calls.  We
00236     // need to flag these together so that the value isn't live across a call.
00237     //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00238     
00239     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
00240     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
00241   } else {
00242     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
00243     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
00244   }
00245 
00246   if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
00247     // 64-bit PowerPC implementations can support i64 types directly
00248     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
00249     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
00250     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
00251     // 64-bit PowerPC wants to expand i128 shifts itself.
00252     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
00253     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
00254     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
00255   } else {
00256     // 32-bit PowerPC wants to expand i64 shifts itself.
00257     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00258     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00259     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00260   }
00261 
00262   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
00263     // First set operation action for all vector types to expand. Then we
00264     // will selectively turn on ones that can be effectively codegen'd.
00265     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00266          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
00267       MVT VT = (MVT::SimpleValueType)i;
00268 
00269       // add/sub are legal for all supported vector VT's.
00270       setOperationAction(ISD::ADD , VT, Legal);
00271       setOperationAction(ISD::SUB , VT, Legal);
00272       
00273       // We promote all shuffles to v16i8.
00274       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
00275       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
00276 
00277       // We promote all non-typed operations to v4i32.
00278       setOperationAction(ISD::AND   , VT, Promote);
00279       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
00280       setOperationAction(ISD::OR    , VT, Promote);
00281       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
00282       setOperationAction(ISD::XOR   , VT, Promote);
00283       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
00284       setOperationAction(ISD::LOAD  , VT, Promote);
00285       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
00286       setOperationAction(ISD::SELECT, VT, Promote);
00287       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
00288       setOperationAction(ISD::STORE, VT, Promote);
00289       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
00290       
00291       // No other operations are legal.
00292       setOperationAction(ISD::MUL , VT, Expand);
00293       setOperationAction(ISD::SDIV, VT, Expand);
00294       setOperationAction(ISD::SREM, VT, Expand);
00295       setOperationAction(ISD::UDIV, VT, Expand);
00296       setOperationAction(ISD::UREM, VT, Expand);
00297       setOperationAction(ISD::FDIV, VT, Expand);
00298       setOperationAction(ISD::FNEG, VT, Expand);
00299       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
00300       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
00301       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
00302       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
00303       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
00304       setOperationAction(ISD::UDIVREM, VT, Expand);
00305       setOperationAction(ISD::SDIVREM, VT, Expand);
00306       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
00307       setOperationAction(ISD::FPOW, VT, Expand);
00308       setOperationAction(ISD::CTPOP, VT, Expand);
00309       setOperationAction(ISD::CTLZ, VT, Expand);
00310       setOperationAction(ISD::CTTZ, VT, Expand);
00311     }
00312 
00313     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
00314     // with merges, splats, etc.
00315     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
00316 
00317     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
00318     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
00319     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
00320     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
00321     setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
00322     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
00323     
00324     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
00325     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
00326     addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
00327     addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
00328     
00329     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
00330     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00331     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00332     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
00333 
00334     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
00335     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
00336     
00337     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
00338     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
00339     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
00340     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
00341   }
00342   
00343   setShiftAmountType(MVT::i32);
00344   setBooleanContents(ZeroOrOneBooleanContent);
00345   
00346   if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
00347     setStackPointerRegisterToSaveRestore(PPC::X1);
00348     setExceptionPointerRegister(PPC::X3);
00349     setExceptionSelectorRegister(PPC::X4);
00350   } else {
00351     setStackPointerRegisterToSaveRestore(PPC::R1);
00352     setExceptionPointerRegister(PPC::R3);
00353     setExceptionSelectorRegister(PPC::R4);
00354   }
00355   
00356   // We have target-specific dag combine patterns for the following nodes:
00357   setTargetDAGCombine(ISD::SINT_TO_FP);
00358   setTargetDAGCombine(ISD::STORE);
00359   setTargetDAGCombine(ISD::BR_CC);
00360   setTargetDAGCombine(ISD::BSWAP);
00361   
00362   // Darwin long double math library functions have $LDBL128 appended.
00363   if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
00364     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
00365     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
00366     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
00367     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
00368     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
00369     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
00370     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
00371     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
00372     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
00373     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
00374   }
00375 
00376   computeRegisterProperties();
00377 }
00378 
00379 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
00380 /// function arguments in the caller parameter area.
00381 unsigned PPCTargetLowering::getByValTypeAlignment(const Type *Ty) const {
00382   TargetMachine &TM = getTargetMachine();
00383   // Darwin passes everything on 4 byte boundary.
00384   if (TM.getSubtarget<PPCSubtarget>().isDarwin())
00385     return 4;
00386   // FIXME Elf TBD
00387   return 4;
00388 }
00389 
00390 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
00391   switch (Opcode) {
00392   default: return 0;
00393   case PPCISD::FSEL:            return "PPCISD::FSEL";
00394   case PPCISD::FCFID:           return "PPCISD::FCFID";
00395   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
00396   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
00397   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
00398   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
00399   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
00400   case PPCISD::VPERM:           return "PPCISD::VPERM";
00401   case PPCISD::Hi:              return "PPCISD::Hi";
00402   case PPCISD::Lo:              return "PPCISD::Lo";
00403   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
00404   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
00405   case PPCISD::SRL:             return "PPCISD::SRL";
00406   case PPCISD::SRA:             return "PPCISD::SRA";
00407   case PPCISD::SHL:             return "PPCISD::SHL";
00408   case PPCISD::EXTSW_32:        return "PPCISD::EXTSW_32";
00409   case PPCISD::STD_32:          return "PPCISD::STD_32";
00410   case PPCISD::CALL_ELF:        return "PPCISD::CALL_ELF";
00411   case PPCISD::CALL_Macho:      return "PPCISD::CALL_Macho";
00412   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
00413   case PPCISD::BCTRL_Macho:     return "PPCISD::BCTRL_Macho";
00414   case PPCISD::BCTRL_ELF:       return "PPCISD::BCTRL_ELF";
00415   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
00416   case PPCISD::MFCR:            return "PPCISD::MFCR";
00417   case PPCISD::VCMP:            return "PPCISD::VCMP";
00418   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
00419   case PPCISD::LBRX:            return "PPCISD::LBRX";
00420   case PPCISD::STBRX:           return "PPCISD::STBRX";
00421   case PPCISD::LARX:            return "PPCISD::LARX";
00422   case PPCISD::STCX:            return "PPCISD::STCX";
00423   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
00424   case PPCISD::MFFS:            return "PPCISD::MFFS";
00425   case PPCISD::MTFSB0:          return "PPCISD::MTFSB0";
00426   case PPCISD::MTFSB1:          return "PPCISD::MTFSB1";
00427   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
00428   case PPCISD::MTFSF:           return "PPCISD::MTFSF";
00429   case PPCISD::TAILCALL:        return "PPCISD::TAILCALL";
00430   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
00431   }
00432 }
00433 
00434 
00435 MVT PPCTargetLowering::getSetCCResultType(MVT VT) const {
00436   return MVT::i32;
00437 }
00438 
00439 
00440 //===----------------------------------------------------------------------===//
00441 // Node matching predicates, for use by the tblgen matching code.
00442 //===----------------------------------------------------------------------===//
00443 
00444 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
00445 static bool isFloatingPointZero(SDValue Op) {
00446   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
00447     return CFP->getValueAPF().isZero();
00448   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
00449     // Maybe this has already been legalized into the constant pool?
00450     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
00451       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
00452         return CFP->getValueAPF().isZero();
00453   }
00454   return false;
00455 }
00456 
00457 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
00458 /// true if Op is undef or if it matches the specified value.
00459 static bool isConstantOrUndef(SDValue Op, unsigned Val) {
00460   return Op.getOpcode() == ISD::UNDEF || 
00461          cast<ConstantSDNode>(Op)->getZExtValue() == Val;
00462 }
00463 
00464 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
00465 /// VPKUHUM instruction.
00466 bool PPC::isVPKUHUMShuffleMask(SDNode *N, bool isUnary) {
00467   if (!isUnary) {
00468     for (unsigned i = 0; i != 16; ++i)
00469       if (!isConstantOrUndef(N->getOperand(i),  i*2+1))
00470         return false;
00471   } else {
00472     for (unsigned i = 0; i != 8; ++i)
00473       if (!isConstantOrUndef(N->getOperand(i),  i*2+1) ||
00474           !isConstantOrUndef(N->getOperand(i+8),  i*2+1))
00475         return false;
00476   }
00477   return true;
00478 }
00479 
00480 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
00481 /// VPKUWUM instruction.
00482 bool PPC::isVPKUWUMShuffleMask(SDNode *N, bool isUnary) {
00483   if (!isUnary) {
00484     for (unsigned i = 0; i != 16; i += 2)
00485       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
00486           !isConstantOrUndef(N->getOperand(i+1),  i*2+3))
00487         return false;
00488   } else {
00489     for (unsigned i = 0; i != 8; i += 2)
00490       if (!isConstantOrUndef(N->getOperand(i  ),  i*2+2) ||
00491           !isConstantOrUndef(N->getOperand(i+1),  i*2+3) ||
00492           !isConstantOrUndef(N->getOperand(i+8),  i*2+2) ||
00493           !isConstantOrUndef(N->getOperand(i+9),  i*2+3))
00494         return false;
00495   }
00496   return true;
00497 }
00498 
00499 /// isVMerge - Common function, used to match vmrg* shuffles.
00500 ///
00501 static bool isVMerge(SDNode *N, unsigned UnitSize, 
00502                      unsigned LHSStart, unsigned RHSStart) {
00503   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
00504          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
00505   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
00506          "Unsupported merge size!");
00507   
00508   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
00509     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
00510       if (!isConstantOrUndef(N->getOperand(i*UnitSize*2+j),
00511                              LHSStart+j+i*UnitSize) ||
00512           !isConstantOrUndef(N->getOperand(i*UnitSize*2+UnitSize+j),
00513                              RHSStart+j+i*UnitSize))
00514         return false;
00515     }
00516       return true;
00517 }
00518 
00519 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
00520 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
00521 bool PPC::isVMRGLShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
00522   if (!isUnary)
00523     return isVMerge(N, UnitSize, 8, 24);
00524   return isVMerge(N, UnitSize, 8, 8);
00525 }
00526 
00527 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
00528 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
00529 bool PPC::isVMRGHShuffleMask(SDNode *N, unsigned UnitSize, bool isUnary) {
00530   if (!isUnary)
00531     return isVMerge(N, UnitSize, 0, 16);
00532   return isVMerge(N, UnitSize, 0, 0);
00533 }
00534 
00535 
00536 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
00537 /// amount, otherwise return -1.
00538 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
00539   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
00540          N->getNumOperands() == 16 && "PPC only supports shuffles by bytes!");
00541   // Find the first non-undef value in the shuffle mask.
00542   unsigned i;
00543   for (i = 0; i != 16 && N->getOperand(i).getOpcode() == ISD::UNDEF; ++i)
00544     /*search*/;
00545   
00546   if (i == 16) return -1;  // all undef.
00547   
00548   // Otherwise, check to see if the rest of the elements are consequtively
00549   // numbered from this value.
00550   unsigned ShiftAmt = cast<ConstantSDNode>(N->getOperand(i))->getZExtValue();
00551   if (ShiftAmt < i) return -1;
00552   ShiftAmt -= i;
00553 
00554   if (!isUnary) {
00555     // Check the rest of the elements to see if they are consequtive.
00556     for (++i; i != 16; ++i)
00557       if (!isConstantOrUndef(N->getOperand(i), ShiftAmt+i))
00558         return -1;
00559   } else {
00560     // Check the rest of the elements to see if they are consequtive.
00561     for (++i; i != 16; ++i)
00562       if (!isConstantOrUndef(N->getOperand(i), (ShiftAmt+i) & 15))
00563         return -1;
00564   }
00565   
00566   return ShiftAmt;
00567 }
00568 
00569 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
00570 /// specifies a splat of a single element that is suitable for input to
00571 /// VSPLTB/VSPLTH/VSPLTW.
00572 bool PPC::isSplatShuffleMask(SDNode *N, unsigned EltSize) {
00573   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
00574          N->getNumOperands() == 16 &&
00575          (EltSize == 1 || EltSize == 2 || EltSize == 4));
00576   
00577   // This is a splat operation if each element of the permute is the same, and
00578   // if the value doesn't reference the second vector.
00579   unsigned ElementBase = 0;
00580   SDValue Elt = N->getOperand(0);
00581   if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt))
00582     ElementBase = EltV->getZExtValue();
00583   else
00584     return false;   // FIXME: Handle UNDEF elements too!
00585 
00586   if (cast<ConstantSDNode>(Elt)->getZExtValue() >= 16)
00587     return false;
00588   
00589   // Check that they are consequtive.
00590   for (unsigned i = 1; i != EltSize; ++i) {
00591     if (!isa<ConstantSDNode>(N->getOperand(i)) ||
00592         cast<ConstantSDNode>(N->getOperand(i))->getZExtValue() != i+ElementBase)
00593       return false;
00594   }
00595   
00596   assert(isa<ConstantSDNode>(Elt) && "Invalid VECTOR_SHUFFLE mask!");
00597   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
00598     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
00599     assert(isa<ConstantSDNode>(N->getOperand(i)) &&
00600            "Invalid VECTOR_SHUFFLE mask!");
00601     for (unsigned j = 0; j != EltSize; ++j)
00602       if (N->getOperand(i+j) != N->getOperand(j))
00603         return false;
00604   }
00605 
00606   return true;
00607 }
00608 
00609 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
00610 /// are -0.0.
00611 bool PPC::isAllNegativeZeroVector(SDNode *N) {
00612   assert(N->getOpcode() == ISD::BUILD_VECTOR);
00613   if (PPC::isSplatShuffleMask(N, N->getNumOperands()))
00614     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N))
00615       return CFP->getValueAPF().isNegZero();
00616   return false;
00617 }
00618 
00619 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
00620 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
00621 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
00622   assert(isSplatShuffleMask(N, EltSize));
00623   return cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() / EltSize;
00624 }
00625 
00626 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
00627 /// by using a vspltis[bhw] instruction of the specified element size, return
00628 /// the constant being splatted.  The ByteSize field indicates the number of
00629 /// bytes of each element [124] -> [bhw].
00630 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
00631   SDValue OpVal(0, 0);
00632 
00633   // If ByteSize of the splat is bigger than the element size of the
00634   // build_vector, then we have a case where we are checking for a splat where
00635   // multiple elements of the buildvector are folded together into a single
00636   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
00637   unsigned EltSize = 16/N->getNumOperands();
00638   if (EltSize < ByteSize) {
00639     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
00640     SDValue UniquedVals[4];
00641     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
00642     
00643     // See if all of the elements in the buildvector agree across.
00644     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00645       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
00646       // If the element isn't a constant, bail fully out.
00647       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
00648 
00649           
00650       if (UniquedVals[i&(Multiple-1)].getNode() == 0)
00651         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
00652       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
00653         return SDValue();  // no match.
00654     }
00655     
00656     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
00657     // either constant or undef values that are identical for each chunk.  See
00658     // if these chunks can form into a larger vspltis*.
00659     
00660     // Check to see if all of the leading entries are either 0 or -1.  If
00661     // neither, then this won't fit into the immediate field.
00662     bool LeadingZero = true;
00663     bool LeadingOnes = true;
00664     for (unsigned i = 0; i != Multiple-1; ++i) {
00665       if (UniquedVals[i].getNode() == 0) continue;  // Must have been undefs.
00666       
00667       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
00668       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
00669     }
00670     // Finally, check the least significant entry.
00671     if (LeadingZero) {
00672       if (UniquedVals[Multiple-1].getNode() == 0)
00673         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
00674       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
00675       if (Val < 16)
00676         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
00677     }
00678     if (LeadingOnes) {
00679       if (UniquedVals[Multiple-1].getNode() == 0)
00680         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
00681       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
00682       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
00683         return DAG.getTargetConstant(Val, MVT::i32);
00684     }
00685     
00686     return SDValue();
00687   }
00688   
00689   // Check to see if this buildvec has a single non-undef value in its elements.
00690   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00691     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
00692     if (OpVal.getNode() == 0)
00693       OpVal = N->getOperand(i);
00694     else if (OpVal != N->getOperand(i))
00695       return SDValue();
00696   }
00697   
00698   if (OpVal.getNode() == 0) return SDValue();  // All UNDEF: use implicit def.
00699   
00700   unsigned ValSizeInBytes = 0;
00701   uint64_t Value = 0;
00702   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
00703     Value = CN->getZExtValue();
00704     ValSizeInBytes = CN->getValueType(0).getSizeInBits()/8;
00705   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
00706     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
00707     Value = FloatToBits(CN->getValueAPF().convertToFloat());
00708     ValSizeInBytes = 4;
00709   }
00710 
00711   // If the splat value is larger than the element value, then we can never do
00712   // this splat.  The only case that we could fit the replicated bits into our
00713   // immediate field for would be zero, and we prefer to use vxor for it.
00714   if (ValSizeInBytes < ByteSize) return SDValue();
00715   
00716   // If the element value is larger than the splat value, cut it in half and
00717   // check to see if the two halves are equal.  Continue doing this until we
00718   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
00719   while (ValSizeInBytes > ByteSize) {
00720     ValSizeInBytes >>= 1;
00721     
00722     // If the top half equals the bottom half, we're still ok.
00723     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
00724          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
00725       return SDValue();
00726   }
00727 
00728   // Properly sign extend the value.
00729   int ShAmt = (4-ByteSize)*8;
00730   int MaskVal = ((int)Value << ShAmt) >> ShAmt;
00731   
00732   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
00733   if (MaskVal == 0) return SDValue();
00734 
00735   // Finally, if this value fits in a 5 bit sext field, return it
00736   if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
00737     return DAG.getTargetConstant(MaskVal, MVT::i32);
00738   return SDValue();
00739 }
00740 
00741 //===----------------------------------------------------------------------===//
00742 //  Addressing Mode Selection
00743 //===----------------------------------------------------------------------===//
00744 
00745 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
00746 /// or 64-bit immediate, and if the value can be accurately represented as a
00747 /// sign extension from a 16-bit value.  If so, this returns true and the
00748 /// immediate.
00749 static bool isIntS16Immediate(SDNode *N, short &Imm) {
00750   if (N->getOpcode() != ISD::Constant)
00751     return false;
00752   
00753   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
00754   if (N->getValueType(0) == MVT::i32)
00755     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
00756   else
00757     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
00758 }
00759 static bool isIntS16Immediate(SDValue Op, short &Imm) {
00760   return isIntS16Immediate(Op.getNode(), Imm);
00761 }
00762 
00763 
00764 /// SelectAddressRegReg - Given the specified addressed, check to see if it
00765 /// can be represented as an indexed [r+r] operation.  Returns false if it
00766 /// can be more efficiently represented with [r+imm].
00767 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
00768                                             SDValue &Index,
00769                                             SelectionDAG &DAG) const {
00770   short imm = 0;
00771   if (N.getOpcode() == ISD::ADD) {
00772     if (isIntS16Immediate(N.getOperand(1), imm))
00773       return false;    // r+i
00774     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
00775       return false;    // r+i
00776     
00777     Base = N.getOperand(0);
00778     Index = N.getOperand(1);
00779     return true;
00780   } else if (N.getOpcode() == ISD::OR) {
00781     if (isIntS16Immediate(N.getOperand(1), imm))
00782       return false;    // r+i can fold it if we can.
00783     
00784     // If this is an or of disjoint bitfields, we can codegen this as an add
00785     // (for better address arithmetic) if the LHS and RHS of the OR are provably
00786     // disjoint.
00787     APInt LHSKnownZero, LHSKnownOne;
00788     APInt RHSKnownZero, RHSKnownOne;
00789     DAG.ComputeMaskedBits(N.getOperand(0),
00790                           APInt::getAllOnesValue(N.getOperand(0)
00791                             .getValueSizeInBits()),
00792                           LHSKnownZero, LHSKnownOne);
00793     
00794     if (LHSKnownZero.getBoolValue()) {
00795       DAG.ComputeMaskedBits(N.getOperand(1),
00796                             APInt::getAllOnesValue(N.getOperand(1)
00797                               .getValueSizeInBits()),
00798                             RHSKnownZero, RHSKnownOne);
00799       // If all of the bits are known zero on the LHS or RHS, the add won't
00800       // carry.
00801       if (~(LHSKnownZero | RHSKnownZero) == 0) {
00802         Base = N.getOperand(0);
00803         Index = N.getOperand(1);
00804         return true;
00805       }
00806     }
00807   }
00808   
00809   return false;
00810 }
00811 
00812 /// Returns true if the address N can be represented by a base register plus
00813 /// a signed 16-bit displacement [r+imm], and if it is not better
00814 /// represented as reg+reg.
00815 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
00816                                             SDValue &Base,
00817                                             SelectionDAG &DAG) const {
00818   // If this can be more profitably realized as r+r, fail.
00819   if (SelectAddressRegReg(N, Disp, Base, DAG))
00820     return false;
00821   
00822   if (N.getOpcode() == ISD::ADD) {
00823     short imm = 0;
00824     if (isIntS16Immediate(N.getOperand(1), imm)) {
00825       Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
00826       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
00827         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
00828       } else {
00829         Base = N.getOperand(0);
00830       }
00831       return true; // [r+i]
00832     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
00833       // Match LOAD (ADD (X, Lo(G))).
00834      assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
00835              && "Cannot handle constant offsets yet!");
00836       Disp = N.getOperand(1).getOperand(0);  // The global address.
00837       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
00838              Disp.getOpcode() == ISD::TargetConstantPool ||
00839              Disp.getOpcode() == ISD::TargetJumpTable);
00840       Base = N.getOperand(0);
00841       return true;  // [&g+r]
00842     }
00843   } else if (N.getOpcode() == ISD::OR) {
00844     short imm = 0;
00845     if (isIntS16Immediate(N.getOperand(1), imm)) {
00846       // If this is an or of disjoint bitfields, we can codegen this as an add
00847       // (for better address arithmetic) if the LHS and RHS of the OR are
00848       // provably disjoint.
00849       APInt LHSKnownZero, LHSKnownOne;
00850       DAG.ComputeMaskedBits(N.getOperand(0),
00851                             APInt::getAllOnesValue(N.getOperand(0)
00852                                                    .getValueSizeInBits()),
00853                             LHSKnownZero, LHSKnownOne);
00854 
00855       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
00856         // If all of the bits are known zero on the LHS or RHS, the add won't
00857         // carry.
00858         Base = N.getOperand(0);
00859         Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
00860         return true;
00861       }
00862     }
00863   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
00864     // Loading from a constant address.
00865     
00866     // If this address fits entirely in a 16-bit sext immediate field, codegen
00867     // this as "d, 0"
00868     short Imm;
00869     if (isIntS16Immediate(CN, Imm)) {
00870       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
00871       Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
00872       return true;
00873     }
00874 
00875     // Handle 32-bit sext immediates with LIS + addr mode.
00876     if (CN->getValueType(0) == MVT::i32 ||
00877         (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
00878       int Addr = (int)CN->getZExtValue();
00879       
00880       // Otherwise, break this down into an LIS + disp.
00881       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
00882       
00883       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
00884       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
00885       Base = SDValue(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
00886       return true;
00887     }
00888   }
00889   
00890   Disp = DAG.getTargetConstant(0, getPointerTy());
00891   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
00892     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
00893   else
00894     Base = N;
00895   return true;      // [r+0]
00896 }
00897 
00898 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
00899 /// represented as an indexed [r+r] operation.
00900 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
00901                                                 SDValue &Index,
00902                                                 SelectionDAG &DAG) const {
00903   // Check to see if we can easily represent this as an [r+r] address.  This
00904   // will fail if it thinks that the address is more profitably represented as
00905   // reg+imm, e.g. where imm = 0.
00906   if (SelectAddressRegReg(N, Base, Index, DAG))
00907     return true;
00908   
00909   // If the operand is an addition, always emit this as [r+r], since this is
00910   // better (for code size, and execution, as the memop does the add for free)
00911   // than emitting an explicit add.
00912   if (N.getOpcode() == ISD::ADD) {
00913     Base = N.getOperand(0);
00914     Index = N.getOperand(1);
00915     return true;
00916   }
00917   
00918   // Otherwise, do it the hard way, using R0 as the base register.
00919   Base = DAG.getRegister(PPC::R0, N.getValueType());
00920   Index = N;
00921   return true;
00922 }
00923 
00924 /// SelectAddressRegImmShift - Returns true if the address N can be
00925 /// represented by a base register plus a signed 14-bit displacement
00926 /// [r+imm*4].  Suitable for use by STD and friends.
00927 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
00928                                                  SDValue &Base,
00929                                                  SelectionDAG &DAG) const {
00930   // If this can be more profitably realized as r+r, fail.
00931   if (SelectAddressRegReg(N, Disp, Base, DAG))
00932     return false;
00933   
00934   if (N.getOpcode() == ISD::ADD) {
00935     short imm = 0;
00936     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
00937       Disp =  DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
00938       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
00939         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
00940       } else {
00941         Base = N.getOperand(0);
00942       }
00943       return true; // [r+i]
00944     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
00945       // Match LOAD (ADD (X, Lo(G))).
00946      assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
00947              && "Cannot handle constant offsets yet!");
00948       Disp = N.getOperand(1).getOperand(0);  // The global address.
00949       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
00950              Disp.getOpcode() == ISD::TargetConstantPool ||
00951              Disp.getOpcode() == ISD::TargetJumpTable);
00952       Base = N.getOperand(0);
00953       return true;  // [&g+r]
00954     }
00955   } else if (N.getOpcode() == ISD::OR) {
00956     short imm = 0;
00957     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
00958       // If this is an or of disjoint bitfields, we can codegen this as an add
00959       // (for better address arithmetic) if the LHS and RHS of the OR are
00960       // provably disjoint.
00961       APInt LHSKnownZero, LHSKnownOne;
00962       DAG.ComputeMaskedBits(N.getOperand(0),
00963                             APInt::getAllOnesValue(N.getOperand(0)
00964                                                    .getValueSizeInBits()),
00965                             LHSKnownZero, LHSKnownOne);
00966       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
00967         // If all of the bits are known zero on the LHS or RHS, the add won't
00968         // carry.
00969         Base = N.getOperand(0);
00970         Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
00971         return true;
00972       }
00973     }
00974   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
00975     // Loading from a constant address.  Verify low two bits are clear.
00976     if ((CN->getZExtValue() & 3) == 0) {
00977       // If this address fits entirely in a 14-bit sext immediate field, codegen
00978       // this as "d, 0"
00979       short Imm;
00980       if (isIntS16Immediate(CN, Imm)) {
00981         Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
00982         Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
00983         return true;
00984       }
00985     
00986       // Fold the low-part of 32-bit absolute addresses into addr mode.
00987       if (CN->getValueType(0) == MVT::i32 ||
00988           (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
00989         int Addr = (int)CN->getZExtValue();
00990       
00991         // Otherwise, break this down into an LIS + disp.
00992         Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
00993         
00994         Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
00995         unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
00996         Base = SDValue(DAG.getTargetNode(Opc, CN->getValueType(0), Base), 0);
00997         return true;
00998       }
00999     }
01000   }
01001   
01002   Disp = DAG.getTargetConstant(0, getPointerTy());
01003   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
01004     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
01005   else
01006     Base = N;
01007   return true;      // [r+0]
01008 }
01009 
01010 
01011 /// getPreIndexedAddressParts - returns true by value, base pointer and
01012 /// offset pointer and addressing mode by reference if the node's address
01013 /// can be legally represented as pre-indexed load / store address.
01014 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
01015                                                   SDValue &Offset,
01016                                                   ISD::MemIndexedMode &AM,
01017                                                   SelectionDAG &DAG) const {
01018   // Disabled by default for now.
01019   if (!EnablePPCPreinc) return false;
01020   
01021   SDValue Ptr;
01022   MVT VT;
01023   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01024     Ptr = LD->getBasePtr();
01025     VT = LD->getMemoryVT();
01026     
01027   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
01028     ST = ST;
01029     Ptr = ST->getBasePtr();
01030     VT  = ST->getMemoryVT();
01031   } else
01032     return false;
01033 
01034   // PowerPC doesn't have preinc load/store instructions for vectors.
01035   if (VT.isVector())
01036     return false;
01037   
01038   // TODO: Check reg+reg first.
01039   
01040   // LDU/STU use reg+imm*4, others use reg+imm.
01041   if (VT != MVT::i64) {
01042     // reg + imm
01043     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
01044       return false;
01045   } else {
01046     // reg + imm * 4.
01047     if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
01048       return false;
01049   }
01050 
01051   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
01052     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
01053     // sext i32 to i64 when addr mode is r+i.
01054     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
01055         LD->getExtensionType() == ISD::SEXTLOAD &&
01056         isa<ConstantSDNode>(Offset))
01057       return false;
01058   }    
01059   
01060   AM = ISD::PRE_INC;
01061   return true;
01062 }
01063 
01064 //===----------------------------------------------------------------------===//
01065 //  LowerOperation implementation
01066 //===----------------------------------------------------------------------===//
01067 
01068 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 
01069                                              SelectionDAG &DAG) {
01070   MVT PtrVT = Op.getValueType();
01071   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
01072   Constant *C = CP->getConstVal();
01073   SDValue CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
01074   SDValue Zero = DAG.getConstant(0, PtrVT);
01075 
01076   const TargetMachine &TM = DAG.getTarget();
01077   
01078   SDValue Hi = DAG.getNode(PPCISD::Hi, PtrVT, CPI, Zero);
01079   SDValue Lo = DAG.getNode(PPCISD::Lo, PtrVT, CPI, Zero);
01080 
01081   // If this is a non-darwin platform, we don't support non-static relo models
01082   // yet.
01083   if (TM.getRelocationModel() == Reloc::Static ||
01084       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
01085     // Generate non-pic code that has direct accesses to the constant pool.
01086     // The address of the global is just (hi(&g)+lo(&g)).
01087     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01088   }
01089   
01090   if (TM.getRelocationModel() == Reloc::PIC_) {
01091     // With PIC, the first instruction is actually "GR+hi(&G)".
01092     Hi = DAG.getNode(ISD::ADD, PtrVT,
01093                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
01094   }
01095   
01096   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01097   return Lo;
01098 }
01099 
01100 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
01101   MVT PtrVT = Op.getValueType();
01102   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
01103   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
01104   SDValue Zero = DAG.getConstant(0, PtrVT);
01105   
01106   const TargetMachine &TM = DAG.getTarget();
01107 
01108   SDValue Hi = DAG.getNode(PPCISD::Hi, PtrVT, JTI, Zero);
01109   SDValue Lo = DAG.getNode(PPCISD::Lo, PtrVT, JTI, Zero);
01110 
01111   // If this is a non-darwin platform, we don't support non-static relo models
01112   // yet.
01113   if (TM.getRelocationModel() == Reloc::Static ||
01114       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
01115     // Generate non-pic code that has direct accesses to the constant pool.
01116     // The address of the global is just (hi(&g)+lo(&g)).
01117     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01118   }
01119   
01120   if (TM.getRelocationModel() == Reloc::PIC_) {
01121     // With PIC, the first instruction is actually "GR+hi(&G)".
01122     Hi = DAG.getNode(ISD::ADD, PtrVT,
01123                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
01124   }
01125   
01126   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01127   return Lo;
01128 }
01129 
01130 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 
01131                                                    SelectionDAG &DAG) {
01132   assert(0 && "TLS not implemented for PPC.");
01133   return SDValue(); // Not reached
01134 }
01135 
01136 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 
01137                                               SelectionDAG &DAG) {
01138   MVT PtrVT = Op.getValueType();
01139   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
01140   GlobalValue *GV = GSDN->getGlobal();
01141   SDValue GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
01142   SDValue Zero = DAG.getConstant(0, PtrVT);
01143   
01144   const TargetMachine &TM = DAG.getTarget();
01145 
01146   SDValue Hi = DAG.getNode(PPCISD::Hi, PtrVT, GA, Zero);
01147   SDValue Lo = DAG.getNode(PPCISD::Lo, PtrVT, GA, Zero);
01148 
01149   // If this is a non-darwin platform, we don't support non-static relo models
01150   // yet.
01151   if (TM.getRelocationModel() == Reloc::Static ||
01152       !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
01153     // Generate non-pic code that has direct accesses to globals.
01154     // The address of the global is just (hi(&g)+lo(&g)).
01155     return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01156   }
01157   
01158   if (TM.getRelocationModel() == Reloc::PIC_) {
01159     // With PIC, the first instruction is actually "GR+hi(&G)".
01160     Hi = DAG.getNode(ISD::ADD, PtrVT,
01161                      DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
01162   }
01163   
01164   Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
01165   
01166   if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
01167     return Lo;
01168   
01169   // If the global is weak or external, we have to go through the lazy
01170   // resolution stub.
01171   return DAG.getLoad(PtrVT, DAG.getEntryNode(), Lo, NULL, 0);
01172 }
01173 
01174 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
01175   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
01176   
01177   // If we're comparing for equality to zero, expose the fact that this is
01178   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
01179   // fold the new nodes.
01180   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01181     if (C->isNullValue() && CC == ISD::SETEQ) {
01182       MVT VT = Op.getOperand(0).getValueType();
01183       SDValue Zext = Op.getOperand(0);
01184       if (VT.bitsLT(MVT::i32)) {
01185         VT = MVT::i32;
01186         Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
01187       } 
01188       unsigned Log2b = Log2_32(VT.getSizeInBits());
01189       SDValue Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
01190       SDValue Scc = DAG.getNode(ISD::SRL, VT, Clz,
01191                                 DAG.getConstant(Log2b, MVT::i32));
01192       return DAG.getNode(ISD::TRUNCATE, MVT::i32, Scc);
01193     }
01194     // Leave comparisons against 0 and -1 alone for now, since they're usually 
01195     // optimized.  FIXME: revisit this when we can custom lower all setcc
01196     // optimizations.
01197     if (C->isAllOnesValue() || C->isNullValue())
01198       return SDValue();
01199   }
01200   
01201   // If we have an integer seteq/setne, turn it into a compare against zero
01202   // by xor'ing the rhs with the lhs, which is faster than setting a
01203   // condition register, reading it back out, and masking the correct bit.  The
01204   // normal approach here uses sub to do this instead of xor.  Using xor exposes
01205   // the result to other bit-twiddling opportunities.
01206   MVT LHSVT = Op.getOperand(0).getValueType();
01207   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
01208     MVT VT = Op.getValueType();
01209     SDValue Sub = DAG.getNode(ISD::XOR, LHSVT, Op.getOperand(0), 
01210                                 Op.getOperand(1));
01211     return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
01212   }
01213   return SDValue();
01214 }
01215 
01216 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
01217                               int VarArgsFrameIndex,
01218                               int VarArgsStackOffset,
01219                               unsigned VarArgsNumGPR,
01220                               unsigned VarArgsNumFPR,
01221                               const PPCSubtarget &Subtarget) {
01222   
01223   assert(0 && "VAARG in ELF32 ABI not implemented yet!");
01224   return SDValue(); // Not reached
01225 }
01226 
01227 SDValue PPCTargetLowering::LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
01228   SDValue Chain = Op.getOperand(0);
01229   SDValue Trmp = Op.getOperand(1); // trampoline
01230   SDValue FPtr = Op.getOperand(2); // nested function
01231   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
01232   DebugLoc dl = Op.getNode()->getDebugLoc();
01233 
01234   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01235   bool isPPC64 = (PtrVT == MVT::i64);
01236   const Type *IntPtrTy =
01237     DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType();
01238 
01239   TargetLowering::ArgListTy Args; 
01240   TargetLowering::ArgListEntry Entry;
01241 
01242   Entry.Ty = IntPtrTy;
01243   Entry.Node = Trmp; Args.push_back(Entry);
01244 
01245   // TrampSize == (isPPC64 ? 48 : 40);
01246   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
01247                                isPPC64 ? MVT::i64 : MVT::i32);
01248   Args.push_back(Entry);
01249 
01250   Entry.Node = FPtr; Args.push_back(Entry);
01251   Entry.Node = Nest; Args.push_back(Entry);
01252   
01253   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
01254   std::pair<SDValue, SDValue> CallResult =
01255     LowerCallTo(Chain, Op.getValueType().getTypeForMVT(), false, false,
01256                 false, false, CallingConv::C, false,
01257                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
01258                 Args, DAG, dl);
01259 
01260   SDValue Ops[] =
01261     { CallResult.first, CallResult.second };
01262 
01263   return DAG.getMergeValues(Ops, 2);
01264 }
01265 
01266 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
01267                                         int VarArgsFrameIndex,
01268                                         int VarArgsStackOffset,
01269                                         unsigned VarArgsNumGPR,
01270                                         unsigned VarArgsNumFPR,
01271                                         const PPCSubtarget &Subtarget) {
01272 
01273   if (Subtarget.isMachoABI()) {
01274     // vastart just stores the address of the VarArgsFrameIndex slot into the
01275     // memory location argument.
01276     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01277     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
01278     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01279     return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), SV, 0);
01280   }
01281 
01282   // For ELF 32 ABI we follow the layout of the va_list struct.
01283   // We suppose the given va_list is already allocated.
01284   //
01285   // typedef struct {
01286   //  char gpr;     /* index into the array of 8 GPRs
01287   //                 * stored in the register save area
01288   //                 * gpr=0 corresponds to r3,
01289   //                 * gpr=1 to r4, etc.
01290   //                 */
01291   //  char fpr;     /* index into the array of 8 FPRs
01292   //                 * stored in the register save area
01293   //                 * fpr=0 corresponds to f1,
01294   //                 * fpr=1 to f2, etc.
01295   //                 */
01296   //  char *overflow_arg_area;
01297   //                /* location on stack that holds
01298   //                 * the next overflow argument
01299   //                 */
01300   //  char *reg_save_area;
01301   //               /* where r3:r10 and f1:f8 (if saved)
01302   //                * are stored
01303   //                */
01304   // } va_list[1];
01305 
01306 
01307   SDValue ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i8);
01308   SDValue ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i8);
01309   
01310 
01311   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01312   
01313   SDValue StackOffsetFI = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
01314   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
01315   
01316   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
01317   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
01318 
01319   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
01320   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
01321 
01322   uint64_t FPROffset = 1;
01323   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
01324   
01325   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01326   
01327   // Store first byte : number of int regs
01328   SDValue firstStore = DAG.getStore(Op.getOperand(0), ArgGPR,
01329                                       Op.getOperand(1), SV, 0);
01330   uint64_t nextOffset = FPROffset;
01331   SDValue nextPtr = DAG.getNode(ISD::ADD, PtrVT, Op.getOperand(1),
01332                                   ConstFPROffset);
01333   
01334   // Store second byte : number of float regs
01335   SDValue secondStore =
01336     DAG.getStore(firstStore, ArgFPR, nextPtr, SV, nextOffset);
01337   nextOffset += StackOffset;
01338   nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstStackOffset);
01339   
01340   // Store second word : arguments given on stack
01341   SDValue thirdStore =
01342     DAG.getStore(secondStore, StackOffsetFI, nextPtr, SV, nextOffset);
01343   nextOffset += FrameOffset;
01344   nextPtr = DAG.getNode(ISD::ADD, PtrVT, nextPtr, ConstFrameOffset);
01345 
01346   // Store third word : arguments given in registers
01347   return DAG.getStore(thirdStore, FR, nextPtr, SV, nextOffset);
01348 
01349 }
01350 
01351 #include "PPCGenCallingConv.inc"
01352 
01353 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
01354 /// depending on which subtarget is selected.
01355 static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
01356   if (Subtarget.isMachoABI()) {
01357     static const unsigned FPR[] = {
01358       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
01359       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
01360     };
01361     return FPR;
01362   }
01363   
01364   
01365   static const unsigned FPR[] = {
01366     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
01367     PPC::F8
01368   };
01369   return FPR;
01370 }
01371 
01372 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
01373 /// the stack.
01374 static unsigned CalculateStackSlotSize(SDValue Arg, ISD::ArgFlagsTy Flags,
01375                                        bool isVarArg, unsigned PtrByteSize) {
01376   MVT ArgVT = Arg.getValueType();
01377   unsigned ArgSize =ArgVT.getSizeInBits()/8;
01378   if (Flags.isByVal())
01379     ArgSize = Flags.getByValSize();
01380   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
01381 
01382   return ArgSize;
01383 }
01384 
01385 SDValue
01386 PPCTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, 
01387                                          SelectionDAG &DAG,
01388                                          int &VarArgsFrameIndex,
01389                                          int &VarArgsStackOffset,
01390                                          unsigned &VarArgsNumGPR,
01391                                          unsigned &VarArgsNumFPR,
01392                                          const PPCSubtarget &Subtarget) {
01393   // TODO: add description of PPC stack frame format, or at least some docs.
01394   //
01395   MachineFunction &MF = DAG.getMachineFunction();
01396   MachineFrameInfo *MFI = MF.getFrameInfo();
01397   MachineRegisterInfo &RegInfo = MF.getRegInfo();
01398   SmallVector<SDValue, 8> ArgValues;
01399   SDValue Root = Op.getOperand(0);
01400   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
01401   
01402   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01403   bool isPPC64 = PtrVT == MVT::i64;
01404   bool isMachoABI = Subtarget.isMachoABI();
01405   bool isELF32_ABI = Subtarget.isELF32_ABI();
01406   // Potential tail calls could cause overwriting of argument stack slots.
01407   unsigned CC = MF.getFunction()->getCallingConv();
01408   bool isImmutable = !(PerformTailCallOpt && (CC==CallingConv::Fast));
01409   unsigned PtrByteSize = isPPC64 ? 8 : 4;
01410 
01411   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
01412   // Area that is at least reserved in caller of this function.
01413   unsigned MinReservedArea = ArgOffset;
01414 
01415   static const unsigned GPR_32[] = {           // 32-bit registers.
01416     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
01417     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
01418   };
01419   static const unsigned GPR_64[] = {           // 64-bit registers.
01420     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
01421     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
01422   };
01423   
01424   static const unsigned *FPR = GetFPR(Subtarget);
01425   
01426   static const unsigned VR[] = {
01427     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
01428     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
01429   };
01430 
01431   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
01432   const unsigned Num_FPR_Regs = isMachoABI ? 13 : 8;
01433   const unsigned Num_VR_Regs  = array_lengthof( VR);
01434 
01435   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
01436   
01437   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
01438   
01439   // In 32-bit non-varargs functions, the stack space for vectors is after the
01440   // stack space for non-vectors.  We do not use this space unless we have
01441   // too many vectors to fit in registers, something that only occurs in
01442   // constructed examples:), but we have to walk the arglist to figure 
01443   // that out...for the pathological case, compute VecArgOffset as the
01444   // start of the vector parameter area.  Computing VecArgOffset is the
01445   // entire point of the following loop.
01446   // Altivec is not mentioned in the ppc32 Elf Supplement, so I'm not trying
01447   // to handle Elf here.
01448   unsigned VecArgOffset = ArgOffset;
01449   if (!isVarArg && !isPPC64) {
01450     for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues()-1; ArgNo != e; 
01451          ++ArgNo) {
01452       MVT ObjectVT = Op.getValue(ArgNo).getValueType();
01453       unsigned ObjSize = ObjectVT.getSizeInBits()/8;
01454       ISD::ArgFlagsTy Flags =
01455         cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
01456 
01457       if (Flags.isByVal()) {
01458         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
01459         ObjSize = Flags.getByValSize();
01460         unsigned ArgSize = 
01461                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
01462         VecArgOffset += ArgSize;
01463         continue;
01464       }
01465 
01466       switch(ObjectVT.getSimpleVT()) {
01467       default: assert(0 && "Unhandled argument type!");
01468       case MVT::i32:
01469       case MVT::f32:
01470         VecArgOffset += isPPC64 ? 8 : 4;
01471         break;
01472       case MVT::i64:  // PPC64
01473       case MVT::f64:
01474         VecArgOffset += 8;
01475         break;
01476       case MVT::v4f32:
01477       case MVT::v4i32:
01478       case MVT::v8i16:
01479       case MVT::v16i8:
01480         // Nothing to do, we're only looking at Nonvector args here.
01481         break;
01482       }
01483     }
01484   }
01485   // We've found where the vector parameter area in memory is.  Skip the
01486   // first 12 parameters; these don't use that memory.
01487   VecArgOffset = ((VecArgOffset+15)/16)*16;
01488   VecArgOffset += 12*16;
01489 
01490   // Add DAG nodes to load the arguments or copy them out of registers.  On
01491   // entry to a function on PPC, the arguments start after the linkage area,
01492   // although the first ones are often in registers.
01493   // 
01494   // In the ELF 32 ABI, GPRs and stack are double word align: an argument
01495   // represented with two words (long long or double) must be copied to an
01496   // even GPR_idx value or to an even ArgOffset value.
01497 
01498   SmallVector<SDValue, 8> MemOps;
01499   unsigned nAltivecParamsAtEnd = 0;
01500   for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues() - 1;
01501        ArgNo != e; ++ArgNo) {
01502     SDValue ArgVal;
01503     bool needsLoad = false;
01504     MVT ObjectVT = Op.getValue(ArgNo).getValueType();
01505     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
01506     unsigned ArgSize = ObjSize;
01507     ISD::ArgFlagsTy Flags =
01508       cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
01509     // See if next argument requires stack alignment in ELF
01510     bool Align = Flags.isSplit(); 
01511 
01512     unsigned CurArgOffset = ArgOffset;
01513 
01514     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
01515     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
01516         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
01517       if (isVarArg || isPPC64) {
01518         MinReservedArea = ((MinReservedArea+15)/16)*16;
01519         MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
01520                                                   Flags,
01521                                                   isVarArg,
01522                                                   PtrByteSize);
01523       } else  nAltivecParamsAtEnd++;
01524     } else
01525       // Calculate min reserved area.
01526       MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
01527                                                 Flags,
01528                                                 isVarArg,
01529                                                 PtrByteSize);
01530 
01531     // FIXME alignment for ELF may not be right
01532     // FIXME the codegen can be much improved in some cases.
01533     // We do not have to keep everything in memory.
01534     if (Flags.isByVal()) {
01535       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
01536       ObjSize = Flags.getByValSize();
01537       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
01538       // Double word align in ELF
01539       if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
01540       // Objects of size 1 and 2 are right justified, everything else is
01541       // left justified.  This means the memory address is adjusted forwards.
01542       if (ObjSize==1 || ObjSize==2) {
01543         CurArgOffset = CurArgOffset + (4 - ObjSize);
01544       }
01545       // The value of the object is its address.
01546       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset);
01547       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
01548       ArgValues.push_back(FIN);
01549       if (ObjSize==1 || ObjSize==2) {
01550         if (GPR_idx != Num_GPR_Regs) {
01551           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
01552           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
01553           SDValue Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
01554           SDValue Store = DAG.getTruncStore(Val.getValue(1), Val, FIN, 
01555                                NULL, 0, ObjSize==1 ? MVT::i8 : MVT::i16 );
01556           MemOps.push_back(Store);
01557           ++GPR_idx;
01558           if (isMachoABI) ArgOffset += PtrByteSize;
01559         } else {
01560           ArgOffset += PtrByteSize;
01561         }
01562         continue;
01563       }
01564       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
01565         // Store whatever pieces of the object are in registers
01566         // to memory.  ArgVal will be address of the beginning of
01567         // the object.
01568         if (GPR_idx != Num_GPR_Regs) {
01569           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
01570           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
01571           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset);
01572           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
01573           SDValue Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
01574           SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
01575           MemOps.push_back(Store);
01576           ++GPR_idx;
01577           if (isMachoABI) ArgOffset += PtrByteSize;
01578         } else {
01579           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
01580           break;
01581         }
01582       }
01583       continue;
01584     }
01585 
01586     switch (ObjectVT.getSimpleVT()) {
01587     default: assert(0 && "Unhandled argument type!");
01588     case MVT::i32:
01589       if (!isPPC64) {
01590         // Double word align in ELF
01591         if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
01592 
01593         if (GPR_idx != Num_GPR_Regs) {
01594           unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
01595           RegInfo.addLiveIn(GPR[GPR_idx], VReg);
01596           ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i32);
01597           ++GPR_idx;
01598         } else {
01599           needsLoad = true;
01600           ArgSize = PtrByteSize;
01601         }
01602         // Stack align in ELF
01603         if (needsLoad && Align && isELF32_ABI) 
01604           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
01605         // All int arguments reserve stack space in Macho ABI.
01606         if (isMachoABI || needsLoad) ArgOffset += PtrByteSize;
01607         break;
01608       }
01609       // FALLTHROUGH
01610     case MVT::i64:  // PPC64
01611       if (GPR_idx != Num_GPR_Regs) {
01612         unsigned VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
01613         RegInfo.addLiveIn(GPR[GPR_idx], VReg);
01614         ArgVal = DAG.getCopyFromReg(Root, VReg, MVT::i64);
01615 
01616         if (ObjectVT == MVT::i32) {
01617           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
01618           // value to MVT::i64 and then truncate to the correct register size.
01619           if (Flags.isSExt())
01620             ArgVal = DAG.getNode(ISD::AssertSext, MVT::i64, ArgVal,
01621                                  DAG.getValueType(ObjectVT));
01622           else if (Flags.isZExt())
01623             ArgVal = DAG.getNode(ISD::AssertZext, MVT::i64, ArgVal,
01624                                  DAG.getValueType(ObjectVT));
01625 
01626           ArgVal = DAG.getNode(ISD::TRUNCATE, MVT::i32, ArgVal);
01627         }
01628 
01629         ++GPR_idx;
01630       } else {
01631         needsLoad = true;
01632         ArgSize = PtrByteSize;
01633       }
01634       // All int arguments reserve stack space in Macho ABI.
01635       if (isMachoABI || needsLoad) ArgOffset += 8;
01636       break;
01637       
01638     case MVT::f32:
01639     case MVT::f64:
01640       // Every 4 bytes of argument space consumes one of the GPRs available for
01641       // argument passing.
01642       if (GPR_idx != Num_GPR_Regs && isMachoABI) {
01643         ++GPR_idx;
01644         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
01645           ++GPR_idx;
01646       }
01647       if (FPR_idx != Num_FPR_Regs) {
01648         unsigned VReg;
01649         if (ObjectVT == MVT::f32)
01650           VReg = RegInfo.createVirtualRegister(&PPC::F4RCRegClass);
01651         else
01652           VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
01653         RegInfo.addLiveIn(FPR[FPR_idx], VReg);
01654         ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
01655         ++FPR_idx;
01656       } else {
01657         needsLoad = true;
01658       }
01659       
01660       // Stack align in ELF
01661       if (needsLoad && Align && isELF32_ABI)
01662         ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
01663       // All FP arguments reserve stack space in Macho ABI.
01664       if (isMachoABI || needsLoad) ArgOffset += isPPC64 ? 8 : ObjSize;
01665       break;
01666     case MVT::v4f32:
01667     case MVT::v4i32:
01668     case MVT::v8i16:
01669     case MVT::v16i8:
01670       // Note that vector arguments in registers don't reserve stack space,
01671       // except in varargs functions.
01672       if (VR_idx != Num_VR_Regs) {
01673         unsigned VReg = RegInfo.createVirtualRegister(&PPC::VRRCRegClass);
01674         RegInfo.addLiveIn(VR[VR_idx], VReg);
01675         ArgVal = DAG.getCopyFromReg(Root, VReg, ObjectVT);
01676         if (isVarArg) {
01677           while ((ArgOffset % 16) != 0) {
01678             ArgOffset += PtrByteSize;
01679             if (GPR_idx != Num_GPR_Regs)
01680               GPR_idx++;
01681           }
01682           ArgOffset += 16;
01683           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs);
01684         }
01685         ++VR_idx;
01686       } else {
01687         if (!isVarArg && !isPPC64) {
01688           // Vectors go after all the nonvectors.
01689           CurArgOffset = VecArgOffset;
01690           VecArgOffset += 16;
01691         } else {
01692           // Vectors are aligned.
01693           ArgOffset = ((ArgOffset+15)/16)*16;
01694           CurArgOffset = ArgOffset;
01695           ArgOffset += 16;
01696         }
01697         needsLoad = true;
01698       }
01699       break;
01700     }
01701     
01702     // We need to load the argument to a virtual register if we determined above
01703     // that we ran out of physical registers of the appropriate type.
01704     if (needsLoad) {
01705       int FI = MFI->CreateFixedObject(ObjSize,
01706                                       CurArgOffset + (ArgSize - ObjSize),
01707                                       isImmutable);
01708       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
01709       ArgVal = DAG.getLoad(ObjectVT, Root, FIN, NULL, 0);
01710     }
01711     
01712     ArgValues.push_back(ArgVal);
01713   }
01714 
01715   // Set the size that is at least reserved in caller of this function.  Tail
01716   // call optimized function's reserved stack space needs to be aligned so that
01717   // taking the difference between two stack areas will result in an aligned
01718   // stack.
01719   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01720   // Add the Altivec parameters at the end, if needed.
01721   if (nAltivecParamsAtEnd) {
01722     MinReservedArea = ((MinReservedArea+15)/16)*16;
01723     MinReservedArea += 16*nAltivecParamsAtEnd;
01724   }
01725   MinReservedArea =
01726     std::max(MinReservedArea,
01727              PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
01728   unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
01729     getStackAlignment();
01730   unsigned AlignMask = TargetAlign-1;
01731   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
01732   FI->setMinReservedArea(MinReservedArea);
01733 
01734   // If the function takes variable number of arguments, make a frame index for
01735   // the start of the first vararg value... for expansion of llvm.va_start.
01736   if (isVarArg) {
01737     
01738     int depth;
01739     if (isELF32_ABI) {
01740       VarArgsNumGPR = GPR_idx;
01741       VarArgsNumFPR = FPR_idx;
01742    
01743       // Make room for Num_GPR_Regs, Num_FPR_Regs and for a possible frame
01744       // pointer.
01745       depth = -(Num_GPR_Regs * PtrVT.getSizeInBits()/8 +
01746                 Num_FPR_Regs * MVT(MVT::f64).getSizeInBits()/8 +
01747                 PtrVT.getSizeInBits()/8);
01748       
01749       VarArgsStackOffset = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
01750                                                   ArgOffset);
01751 
01752     }
01753     else
01754       depth = ArgOffset;
01755     
01756     VarArgsFrameIndex = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
01757                                                depth);
01758     SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
01759     
01760     // In ELF 32 ABI, the fixed integer arguments of a variadic function are
01761     // stored to the VarArgsFrameIndex on the stack.
01762     if (isELF32_ABI) {
01763       for (GPR_idx = 0; GPR_idx != VarArgsNumGPR; ++GPR_idx) {
01764         SDValue Val = DAG.getRegister(GPR[GPR_idx], PtrVT);
01765         SDValue Store = DAG.getStore(Root, Val, FIN, NULL, 0);
01766         MemOps.push_back(Store);
01767         // Increment the address by four for the next argument to store
01768         SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
01769         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
01770       }
01771     }
01772 
01773     // If this function is vararg, store any remaining integer argument regs
01774     // to their spots on the stack so that they may be loaded by deferencing the
01775     // result of va_next.
01776     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
01777       unsigned VReg;
01778       if (isPPC64)
01779         VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
01780       else
01781         VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
01782 
01783       RegInfo.addLiveIn(GPR[GPR_idx], VReg);
01784       SDValue Val = DAG.getCopyFromReg(Root, VReg, PtrVT);
01785       SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
01786       MemOps.push_back(Store);
01787       // Increment the address by four for the next argument to store
01788       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
01789       FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
01790     }
01791 
01792     // In ELF 32 ABI, the double arguments are stored to the VarArgsFrameIndex
01793     // on the stack.
01794     if (isELF32_ABI) {
01795       for (FPR_idx = 0; FPR_idx != VarArgsNumFPR; ++FPR_idx) {
01796         SDValue Val = DAG.getRegister(FPR[FPR_idx], MVT::f64);
01797         SDValue Store = DAG.getStore(Root, Val, FIN, NULL, 0);
01798         MemOps.push_back(Store);
01799         // Increment the address by eight for the next argument to store
01800         SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
01801                                            PtrVT);
01802         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
01803       }
01804 
01805       for (; FPR_idx != Num_FPR_Regs; ++FPR_idx) {
01806         unsigned VReg;
01807         VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
01808 
01809         RegInfo.addLiveIn(FPR[FPR_idx], VReg);
01810         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::f64);
01811         SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
01812         MemOps.push_back(Store);
01813         // Increment the address by eight for the next argument to store
01814         SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
01815                                            PtrVT);
01816         FIN = DAG.getNode(ISD::ADD, PtrOff.getValueType(), FIN, PtrOff);
01817       }
01818     }
01819   }
01820   
01821   if (!MemOps.empty())
01822     Root = DAG.getNode(ISD::TokenFactor, MVT::Other,&MemOps[0],MemOps.size());
01823 
01824   ArgValues.push_back(Root);
01825  
01826   // Return the new list of results.
01827   return DAG.getNode(ISD::MERGE_VALUES, Op.getNode()->getVTList(),
01828                      &ArgValues[0], ArgValues.size());
01829 }
01830 
01831 /// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus
01832 /// linkage area.
01833 static unsigned
01834 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
01835                                      bool isPPC64,
01836                                      bool isMachoABI,
01837                                      bool isVarArg,
01838                                      unsigned CC,
01839                                      CallSDNode *TheCall,
01840                                      unsigned &nAltivecParamsAtEnd) {
01841   // Count how many bytes are to be pushed on the stack, including the linkage
01842   // area, and parameter passing area.  We start with 24/48 bytes, which is
01843   // prereserved space for [SP][CR][LR][3 x unused].
01844   unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
01845   unsigned NumOps = TheCall->getNumArgs();
01846   unsigned PtrByteSize = isPPC64 ? 8 : 4;
01847 
01848   // Add up all the space actually used.
01849   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
01850   // they all go in registers, but we must reserve stack space for them for
01851   // possible use by the caller.  In varargs or 64-bit calls, parameters are
01852   // assigned stack space in order, with padding so Altivec parameters are
01853   // 16-byte aligned.
01854   nAltivecParamsAtEnd = 0;
01855   for (unsigned i = 0; i != NumOps; ++i) {
01856     SDValue Arg = TheCall->getArg(i);
01857     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
01858     MVT ArgVT = Arg.getValueType();
01859     // Varargs Altivec parameters are padded to a 16 byte boundary.
01860     if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
01861         ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
01862       if (!isVarArg && !isPPC64) {
01863         // Non-varargs Altivec parameters go after all the non-Altivec
01864         // parameters; handle those later so we know how much padding we need.
01865         nAltivecParamsAtEnd++;
01866         continue;
01867       }
01868       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
01869       NumBytes = ((NumBytes+15)/16)*16;
01870     }
01871     NumBytes += CalculateStackSlotSize(Arg, Flags, isVarArg, PtrByteSize);
01872   }
01873 
01874    // Allow for Altivec parameters at the end, if needed.
01875   if (nAltivecParamsAtEnd) {
01876     NumBytes = ((NumBytes+15)/16)*16;
01877     NumBytes += 16*nAltivecParamsAtEnd;
01878   }
01879 
01880   // The prolog code of the callee may store up to 8 GPR argument registers to
01881   // the stack, allowing va_start to index over them in memory if its varargs.
01882   // Because we cannot tell if this is needed on the caller side, we have to
01883   // conservatively assume that it is needed.  As such, make sure we have at
01884   // least enough stack space for the caller to store the 8 GPRs.
01885   NumBytes = std::max(NumBytes,
01886                       PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
01887 
01888   // Tail call needs the stack to be aligned.
01889   if (CC==CallingConv::Fast && PerformTailCallOpt) {
01890     unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
01891       getStackAlignment();
01892     unsigned AlignMask = TargetAlign-1;
01893     NumBytes = (NumBytes + AlignMask) & ~AlignMask;
01894   }
01895 
01896   return NumBytes;
01897 }
01898 
01899 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
01900 /// adjusted to accomodate the arguments for the tailcall.
01901 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool IsTailCall,
01902                                    unsigned ParamSize) {
01903 
01904   if (!IsTailCall) return 0;
01905 
01906   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
01907   unsigned CallerMinReservedArea = FI->getMinReservedArea();
01908   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
01909   // Remember only if the new adjustement is bigger.
01910   if (SPDiff < FI->getTailCallSPDelta())
01911     FI->setTailCallSPDelta(SPDiff);
01912 
01913   return SPDiff;
01914 }
01915 
01916 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
01917 /// following the call is a return. A function is eligible if caller/callee
01918 /// calling conventions match, currently only fastcc supports tail calls, and
01919 /// the function CALL is immediatly followed by a RET.
01920 bool
01921 PPCTargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
01922                                                      SDValue Ret,
01923                                                      SelectionDAG& DAG) const {
01924   // Variable argument functions are not supported.
01925   if (!PerformTailCallOpt || TheCall->isVarArg())
01926     return false;
01927 
01928   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
01929     MachineFunction &MF = DAG.getMachineFunction();
01930     unsigned CallerCC = MF.getFunction()->getCallingConv();
01931     unsigned CalleeCC = TheCall->getCallingConv();
01932     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
01933       // Functions containing by val parameters are not supported.
01934       for (unsigned i = 0; i != TheCall->getNumArgs(); i++) {
01935          ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
01936          if (Flags.isByVal()) return false;
01937       }
01938 
01939       SDValue Callee = TheCall->getCallee();
01940       // Non PIC/GOT  tail calls are supported.
01941       if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
01942         return true;
01943 
01944       // At the moment we can only do local tail calls (in same module, hidden
01945       // or protected) if we are generating PIC.
01946       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
01947         return G->getGlobal()->hasHiddenVisibility()
01948             || G->getGlobal()->hasProtectedVisibility();
01949     }
01950   }
01951 
01952   return false;
01953 }
01954 
01955 /// isCallCompatibleAddress - Return the immediate to use if the specified
01956 /// 32-bit value is representable in the immediate field of a BxA instruction.
01957 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
01958   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
01959   if (!C) return 0;
01960   
01961   int Addr = C->getZExtValue();
01962   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
01963       (Addr << 6 >> 6) != Addr)
01964     return 0;  // Top 6 bits have to be sext of immediate.
01965   
01966   return DAG.getConstant((int)C->getZExtValue() >> 2,
01967                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
01968 }
01969 
01970 namespace {
01971 
01972 struct TailCallArgumentInfo {
01973   SDValue Arg;
01974   SDValue FrameIdxOp;
01975   int       FrameIdx;
01976 
01977   TailCallArgumentInfo() : FrameIdx(0) {}
01978 };
01979 
01980 }
01981 
01982 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
01983 static void
01984 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
01985                                            SDValue Chain,
01986                    const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
01987                    SmallVector<SDValue, 8> &MemOpChains) {
01988   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
01989     SDValue Arg = TailCallArgs[i].Arg;
01990     SDValue FIN = TailCallArgs[i].FrameIdxOp;
01991     int FI = TailCallArgs[i].FrameIdx;
01992     // Store relative to framepointer.
01993     MemOpChains.push_back(DAG.getStore(Chain, Arg, FIN,
01994                                        PseudoSourceValue::getFixedStack(FI),
01995                                        0));
01996   }
01997 }
01998 
01999 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
02000 /// the appropriate stack slot for the tail call optimized function call.
02001 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
02002                                                MachineFunction &MF,
02003                                                SDValue Chain,
02004                                                SDValue OldRetAddr,
02005                                                SDValue OldFP,
02006                                                int SPDiff,
02007                                                bool isPPC64,
02008                                                bool isMachoABI) {
02009   if (SPDiff) {
02010     // Calculate the new stack slot for the return address.
02011     int SlotSize = isPPC64 ? 8 : 4;
02012     int NewRetAddrLoc = SPDiff + PPCFrameInfo::getReturnSaveOffset(isPPC64,
02013                                                                    isMachoABI);
02014     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
02015                                                           NewRetAddrLoc);
02016     int NewFPLoc = SPDiff + PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
02017                                                                     isMachoABI);
02018     int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc);
02019 
02020     MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
02021     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
02022     Chain = DAG.getStore(Chain, OldRetAddr, NewRetAddrFrIdx,
02023                          PseudoSourceValue::getFixedStack(NewRetAddr), 0);
02024     SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
02025     Chain = DAG.getStore(Chain, OldFP, NewFramePtrIdx,
02026                          PseudoSourceValue::getFixedStack(NewFPIdx), 0);
02027   }
02028   return Chain;
02029 }
02030 
02031 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
02032 /// the position of the argument.
02033 static void
02034 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
02035                          SDValue Arg, int SPDiff, unsigned ArgOffset,
02036                       SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
02037   int Offset = ArgOffset + SPDiff;
02038   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
02039   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
02040   MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
02041   SDValue FIN = DAG.getFrameIndex(FI, VT);
02042   TailCallArgumentInfo Info;
02043   Info.Arg = Arg;
02044   Info.FrameIdxOp = FIN;
02045   Info.FrameIdx = FI;
02046   TailCallArguments.push_back(Info);
02047 }
02048 
02049 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
02050 /// stack slot. Returns the chain as result and the loaded frame pointers in
02051 /// LROpOut/FPOpout. Used when tail calling.
02052 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
02053                                                           int SPDiff,
02054                                                           SDValue Chain,
02055                                                           SDValue &LROpOut,
02056                                                           SDValue &FPOpOut) {
02057   if (SPDiff) {
02058     // Load the LR and FP stack slot for later adjusting.
02059     MVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
02060     LROpOut = getReturnAddrFrameIndex(DAG);
02061     LROpOut = DAG.getLoad(VT, Chain, LROpOut, NULL, 0);
02062     Chain = SDValue(LROpOut.getNode(), 1);
02063     FPOpOut = getFramePointerFrameIndex(DAG);
02064     FPOpOut = DAG.getLoad(VT, Chain, FPOpOut, NULL, 0);
02065     Chain = SDValue(FPOpOut.getNode(), 1);
02066   }
02067   return Chain;
02068 }
02069 
02070 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
02071 /// by "Src" to address "Dst" of size "Size".  Alignment information is 
02072 /// specified by the specific parameter attribute. The copy will be passed as
02073 /// a byval function parameter.
02074 /// Sometimes what we are copying is the end of a larger object, the part that
02075 /// does not fit in registers.
02076 static SDValue 
02077 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
02078                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
02079                           unsigned Size) {
02080   SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
02081   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(), false,
02082                        NULL, 0, NULL, 0);
02083 }
02084 
02085 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
02086 /// tail calls.
02087 static void
02088 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
02089                  SDValue Arg, SDValue PtrOff, int SPDiff,
02090                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
02091                  bool isVector, SmallVector<SDValue, 8> &MemOpChains,
02092                  SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
02093   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02094   if (!isTailCall) {
02095     if (isVector) {
02096       SDValue StackPtr;
02097       if (isPPC64)
02098         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
02099       else
02100         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
02101       PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr,
02102                            DAG.getConstant(ArgOffset, PtrVT));
02103     }
02104     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
02105   // Calculate and remember argument location.
02106   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
02107                                   TailCallArguments);
02108 }
02109 
02110 SDValue PPCTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG,
02111                                        const PPCSubtarget &Subtarget,
02112                                        TargetMachine &TM) {
02113   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
02114   SDValue Chain  = TheCall->getChain();
02115   bool isVarArg   = TheCall->isVarArg();
02116   unsigned CC     = TheCall->getCallingConv();
02117   bool isTailCall = TheCall->isTailCall()
02118                  && CC == CallingConv::Fast && PerformTailCallOpt;
02119   SDValue Callee = TheCall->getCallee();
02120   unsigned NumOps  = TheCall->getNumArgs();
02121   
02122   bool isMachoABI = Subtarget.isMachoABI();
02123   bool isELF32_ABI  = Subtarget.isELF32_ABI();
02124 
02125   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02126   bool isPPC64 = PtrVT == MVT::i64;
02127   unsigned PtrByteSize = isPPC64 ? 8 : 4;
02128   
02129   MachineFunction &MF = DAG.getMachineFunction();
02130 
02131   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
02132   // SelectExpr to use to put the arguments in the appropriate registers.
02133   std::vector<SDValue> args_to_use;
02134   
02135   // Mark this function as potentially containing a function that contains a
02136   // tail call. As a consequence the frame pointer will be used for dynamicalloc
02137   // and restoring the callers stack pointer in this functions epilog. This is
02138   // done because by tail calling the called function might overwrite the value
02139   // in this function's (MF) stack pointer stack slot 0(SP).
02140   if (PerformTailCallOpt && CC==CallingConv::Fast)
02141     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
02142 
02143   unsigned nAltivecParamsAtEnd = 0;
02144 
02145   // Count how many bytes are to be pushed on the stack, including the linkage
02146   // area, and parameter passing area.  We start with 24/48 bytes, which is
02147   // prereserved space for [SP][CR][LR][3 x unused].
02148   unsigned NumBytes =
02149     CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isMachoABI, isVarArg, CC,
02150                                          TheCall, nAltivecParamsAtEnd);
02151 
02152   // Calculate by how many bytes the stack has to be adjusted in case of tail
02153   // call optimization.
02154   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
02155   
02156   // Adjust the stack pointer for the new arguments...
02157   // These operations are automatically eliminated by the prolog/epilog pass
02158   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
02159   SDValue CallSeqStart = Chain;
02160   
02161   // Load the return address and frame pointer so it can be move somewhere else
02162   // later.
02163   SDValue LROp, FPOp;
02164   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp);
02165 
02166   // Set up a copy of the stack pointer for use loading and storing any
02167   // arguments that may not fit in the registers available for argument
02168   // passing.
02169   SDValue StackPtr;
02170   if (isPPC64)
02171     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
02172   else
02173     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
02174   
02175   // Figure out which arguments are going to go in registers, and which in
02176   // memory.  Also, if this is a vararg function, floating point operations
02177   // must be stored to our stack, and loaded into integer regs as well, if
02178   // any integer regs are available for argument passing.
02179   unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
02180   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
02181   
02182   static const unsigned GPR_32[] = {           // 32-bit registers.
02183     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
02184     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
02185   };
02186   static const unsigned GPR_64[] = {           // 64-bit registers.
02187     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
02188     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
02189   };
02190   static const unsigned *FPR = GetFPR(Subtarget);
02191   
02192   static const unsigned VR[] = {
02193     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
02194     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
02195   };
02196   const unsigned NumGPRs = array_lengthof(GPR_32);
02197   const unsigned NumFPRs = isMachoABI ? 13 : 8;
02198   const unsigned NumVRs  = array_lengthof( VR);
02199   
02200   const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
02201 
02202   std::vector<std::pair<unsigned, SDValue> > RegsToPass;
02203   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
02204 
02205   SmallVector<SDValue, 8> MemOpChains;
02206   for (unsigned i = 0; i != NumOps; ++i) {
02207     bool inMem = false;
02208     SDValue Arg = TheCall->getArg(i);
02209     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
02210     // See if next argument requires stack alignment in ELF
02211     bool Align = Flags.isSplit();
02212 
02213     // PtrOff will be used to store the current argument to the stack if a
02214     // register cannot be found for it.
02215     SDValue PtrOff;
02216     
02217     // Stack align in ELF 32
02218     if (isELF32_ABI && Align)
02219       PtrOff = DAG.getConstant(ArgOffset + ((ArgOffset/4) % 2) * PtrByteSize,
02220                                StackPtr.getValueType());
02221     else
02222       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
02223 
02224     PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr, PtrOff);
02225 
02226     // On PPC64, promote integers to 64-bit values.
02227     if (isPPC64 && Arg.getValueType() == MVT::i32) {
02228       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
02229       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
02230       Arg = DAG.getNode(ExtOp, MVT::i64, Arg);
02231     }
02232 
02233     // FIXME Elf untested, what are alignment rules?
02234     // FIXME memcpy is used way more than necessary.  Correctness first.
02235     if (Flags.isByVal()) {
02236       unsigned Size = Flags.getByValSize();
02237       if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
02238       if (Size==1 || Size==2) {
02239         // Very small objects are passed right-justified.
02240         // Everything else is passed left-justified.
02241         MVT VT = (Size==1) ? MVT::i8 : MVT::i16;
02242         if (GPR_idx != NumGPRs) {
02243           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, PtrVT, Chain, Arg, 
02244                                           NULL, 0, VT);
02245           MemOpChains.push_back(Load.getValue(1));
02246           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
02247           if (isMachoABI)
02248             ArgOffset += PtrByteSize;
02249         } else {
02250           SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
02251           SDValue AddPtr = DAG.getNode(ISD::ADD, PtrVT, PtrOff, Const);
02252           SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
02253                                 CallSeqStart.getNode()->getOperand(0), 
02254                                 Flags, DAG, Size);
02255           // This must go outside the CALLSEQ_START..END.
02256           SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
02257                                CallSeqStart.getNode()->getOperand(1));
02258           DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
02259                                  NewCallSeqStart.getNode());
02260           Chain = CallSeqStart = NewCallSeqStart;
02261           ArgOffset += PtrByteSize;
02262         }
02263         continue;
02264       }
02265       // Copy entire object into memory.  There are cases where gcc-generated
02266       // code assumes it is there, even if it could be put entirely into
02267       // registers.  (This is not what the doc says.)
02268       SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
02269                             CallSeqStart.getNode()->getOperand(0), 
02270                             Flags, DAG, Size);
02271       // This must go outside the CALLSEQ_START..END.
02272       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
02273                            CallSeqStart.getNode()->getOperand(1));
02274       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode());
02275       Chain = CallSeqStart = NewCallSeqStart;
02276       // And copy the pieces of it that fit into registers.
02277       for (unsigned j=0; j<Size; j+=PtrByteSize) {
02278         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
02279         SDValue AddArg = DAG.getNode(ISD::ADD, PtrVT, Arg, Const);
02280         if (GPR_idx != NumGPRs) {
02281           SDValue Load = DAG.getLoad(PtrVT, Chain, AddArg, NULL, 0);
02282           MemOpChains.push_back(Load.getValue(1));
02283           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
02284           if (isMachoABI)
02285             ArgOffset += PtrByteSize;
02286         } else {
02287           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
02288           break;
02289         }
02290       }
02291       continue;
02292     }
02293 
02294     switch (Arg.getValueType().getSimpleVT()) {
02295     default: assert(0 && "Unexpected ValueType for argument!");
02296     case MVT::i32:
02297     case MVT::i64:
02298       // Double word align in ELF
02299       if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
02300       if (GPR_idx != NumGPRs) {
02301         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
02302       } else {
02303         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
02304                          isPPC64, isTailCall, false, MemOpChains,
02305                          TailCallArguments);
02306         inMem = true;
02307       }
02308       if (inMem || isMachoABI) {
02309         // Stack align in ELF
02310         if (isELF32_ABI && Align)
02311           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
02312 
02313         ArgOffset += PtrByteSize;
02314       }
02315       break;
02316     case MVT::f32:
02317     case MVT::f64:
02318       if (FPR_idx != NumFPRs) {
02319         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
02320 
02321         if (isVarArg) {
02322           SDValue Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
02323           MemOpChains.push_back(Store);
02324 
02325           // Float varargs are always shadowed in available integer registers
02326           if (GPR_idx != NumGPRs) {
02327             SDValue Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
02328             MemOpChains.push_back(Load.getValue(1));
02329             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
02330                                                                 Load));
02331           }
02332           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
02333             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
02334             PtrOff = DAG.getNode(ISD::ADD, PtrVT, PtrOff, ConstFour);
02335             SDValue Load = DAG.getLoad(PtrVT, Store, PtrOff, NULL, 0);
02336             MemOpChains.push_back(Load.getValue(1));
02337             if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
02338                                                                 Load));
02339           }
02340         } else {
02341           // If we have any FPRs remaining, we may also have GPRs remaining.
02342           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
02343           // GPRs.
02344           if (isMachoABI) {
02345             if (GPR_idx != NumGPRs)
02346               ++GPR_idx;
02347             if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
02348                 !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
02349               ++GPR_idx;
02350           }
02351         }
02352       } else {
02353         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
02354                          isPPC64, isTailCall, false, MemOpChains,
02355                          TailCallArguments);
02356         inMem = true;
02357       }
02358       if (inMem || isMachoABI) {
02359         // Stack align in ELF
02360         if (isELF32_ABI && Align)
02361           ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
02362         if (isPPC64)
02363           ArgOffset += 8;
02364         else
02365           ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
02366       }
02367       break;
02368     case MVT::v4f32:
02369     case MVT::v4i32:
02370     case MVT::v8i16:
02371     case MVT::v16i8:
02372       if (isVarArg) {
02373         // These go aligned on the stack, or in the corresponding R registers
02374         // when within range.  The Darwin PPC ABI doc claims they also go in 
02375         // V registers; in fact gcc does this only for arguments that are
02376         // prototyped, not for those that match the ...  We do it for all
02377         // arguments, seems to work.
02378         while (ArgOffset % 16 !=0) {
02379           ArgOffset += PtrByteSize;
02380           if (GPR_idx != NumGPRs)
02381             GPR_idx++;
02382         }
02383         // We could elide this store in the case where the object fits
02384         // entirely in R registers.  Maybe later.
02385         PtrOff = DAG.getNode(ISD::ADD, PtrVT, StackPtr, 
02386                             DAG.getConstant(ArgOffset, PtrVT));
02387         SDValue Store = DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
02388         MemOpChains.push_back(Store);
02389         if (VR_idx != NumVRs) {
02390           SDValue Load = DAG.getLoad(MVT::v4f32, Store, PtrOff, NULL, 0);
02391           MemOpChains.push_back(Load.getValue(1));
02392           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
02393         }
02394         ArgOffset += 16;
02395         for (unsigned i=0; i<16; i+=PtrByteSize) {
02396           if (GPR_idx == NumGPRs)
02397             break;
02398           SDValue Ix = DAG.getNode(ISD::ADD, PtrVT, PtrOff,
02399                                   DAG.getConstant(i, PtrVT));
02400           SDValue Load = DAG.getLoad(PtrVT, Store, Ix, NULL, 0);
02401           MemOpChains.push_back(Load.getValue(1));
02402           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
02403         }
02404         break;
02405       }
02406 
02407       // Non-varargs Altivec params generally go in registers, but have
02408       // stack space allocated at the end.
02409       if (VR_idx != NumVRs) {
02410         // Doesn't have GPR space allocated.
02411         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
02412       } else if (nAltivecParamsAtEnd==0) {
02413         // We are emitting Altivec params in order.
02414         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
02415                          isPPC64, isTailCall, true, MemOpChains,
02416                          TailCallArguments);
02417         ArgOffset += 16;
02418       }
02419       break;
02420     }
02421   }
02422   // If all Altivec parameters fit in registers, as they usually do,
02423   // they get stack space following the non-Altivec parameters.  We
02424   // don't track this here because nobody below needs it.
02425   // If there are more Altivec parameters than fit in registers emit
02426   // the stores here.
02427   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
02428     unsigned j = 0;
02429     // Offset is aligned; skip 1st 12 params which go in V registers.
02430     ArgOffset = ((ArgOffset+15)/16)*16;
02431     ArgOffset += 12*16;
02432     for (unsigned i = 0; i != NumOps; ++i) {
02433       SDValue Arg = TheCall->getArg(i);
02434       MVT ArgType = Arg.getValueType();
02435       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
02436           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
02437         if (++j > NumVRs) {
02438           SDValue PtrOff;
02439           // We are emitting Altivec params in order.
02440           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
02441                            isPPC64, isTailCall, true, MemOpChains,
02442                            TailCallArguments);
02443           ArgOffset += 16;
02444         }
02445       }
02446     }
02447   }
02448 
02449   if (!MemOpChains.empty())
02450     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
02451                         &MemOpChains[0], MemOpChains.size());
02452   
02453   // Build a sequence of copy-to-reg nodes chained together with token chain
02454   // and flag operands which copy the outgoing args into the appropriate regs.
02455   SDValue InFlag;
02456   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
02457     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
02458                              InFlag);
02459     InFlag = Chain.getValue(1);
02460   }
02461  
02462   // With the ELF 32 ABI, set CR6 to true if this is a vararg call.
02463   if (isVarArg && isELF32_ABI) {
02464     SDValue SetCR(DAG.getTargetNode(PPC::CRSET, MVT::i32), 0);
02465     Chain = DAG.getCopyToReg(Chain, PPC::CR1EQ, SetCR, InFlag);
02466     InFlag = Chain.getValue(1);
02467   }
02468 
02469   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
02470   // might overwrite each other in case of tail call optimization.
02471   if (isTailCall) {
02472     SmallVector<SDValue, 8> MemOpChains2;
02473     // Do not flag preceeding copytoreg stuff together with the following stuff.
02474     InFlag = SDValue();
02475     StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
02476                                       MemOpChains2);
02477     if (!MemOpChains2.empty())
02478       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
02479                           &MemOpChains2[0], MemOpChains2.size());
02480 
02481     // Store the return address to the appropriate stack slot.
02482     Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
02483                                           isPPC64, isMachoABI);
02484   }
02485 
02486   // Emit callseq_end just before tailcall node.
02487   if (isTailCall) {
02488     SmallVector<SDValue, 8> CallSeqOps;
02489     SDVTList CallSeqNodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
02490     CallSeqOps.push_back(Chain);
02491     CallSeqOps.push_back(DAG.getIntPtrConstant(NumBytes, true));
02492     CallSeqOps.push_back(DAG.getIntPtrConstant(0, true));
02493     if (InFlag.getNode())
02494       CallSeqOps.push_back(InFlag);
02495     Chain = DAG.getNode(ISD::CALLSEQ_END, CallSeqNodeTys, &CallSeqOps[0],
02496                         CallSeqOps.size());
02497     InFlag = Chain.getValue(1);
02498   }
02499 
02500   std::vector<MVT> NodeTys;
02501   NodeTys.push_back(MVT::Other);   // Returns a chain
02502   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
02503 
02504   SmallVector<SDValue, 8> Ops;
02505   unsigned CallOpc = isMachoABI? PPCISD::CALL_Macho : PPCISD::CALL_ELF;
02506   
02507   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
02508   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
02509   // node so that legalize doesn't hack it.
02510   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
02511     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
02512   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
02513     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
02514   else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
02515     // If this is an absolute destination address, use the munged value.
02516     Callee = SDValue(Dest, 0);
02517   else {
02518     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
02519     // to do the call, we can't use PPCISD::CALL.
02520     SDValue MTCTROps[] = {Chain, Callee, InFlag};
02521     Chain = DAG.getNode(PPCISD::MTCTR, NodeTys, MTCTROps,
02522                         2 + (InFlag.getNode() != 0));
02523     InFlag = Chain.getValue(1);
02524     
02525     // Copy the callee address into R12/X12 on darwin.
02526     if (isMachoABI) {
02527       unsigned Reg = Callee.getValueType() == MVT::i32 ? PPC::R12 : PPC::X12;
02528       Chain = DAG.getCopyToReg(Chain, Reg, Callee, InFlag);
02529       InFlag = Chain.getValue(1);
02530     }
02531 
02532     NodeTys.clear();
02533     NodeTys.push_back(MVT::Other);
02534     NodeTys.push_back(MVT::Flag);
02535     Ops.push_back(Chain);
02536     CallOpc = isMachoABI ? PPCISD::BCTRL_Macho : PPCISD::BCTRL_ELF;
02537     Callee.setNode(0);
02538     // Add CTR register as callee so a bctr can be emitted later.
02539     if (isTailCall)
02540       Ops.push_back(DAG.getRegister(PPC::CTR, getPointerTy()));
02541   }
02542 
02543   // If this is a direct call, pass the chain and the callee.
02544   if (Callee.getNode()) {
02545     Ops.push_back(Chain);
02546     Ops.push_back(Callee);
02547   }
02548   // If this is a tail call add stack pointer delta.
02549   if (isTailCall)
02550     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
02551 
02552   // Add argument registers to the end of the list so that they are known live
02553   // into the call.
02554   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
02555     Ops.push_back(DAG.getRegister(RegsToPass[i].first, 
02556                                   RegsToPass[i].second.getValueType()));
02557 
02558   // When performing tail call optimization the callee pops its arguments off
02559   // the stack. Account for this here so these bytes can be pushed back on in
02560   // PPCRegisterInfo::eliminateCallFramePseudoInstr.
02561   int BytesCalleePops =
02562     (CC==CallingConv::Fast && PerformTailCallOpt) ? NumBytes : 0;
02563 
02564   if (InFlag.getNode())
02565     Ops.push_back(InFlag);
02566 
02567   // Emit tail call.
02568   if (isTailCall) {
02569     assert(InFlag.getNode() &&
02570            "Flag must be set. Depend on flag being set in LowerRET");
02571     Chain = DAG.getNode(PPCISD::TAILCALL,
02572                         TheCall->getVTList(), &Ops[0], Ops.size());
02573     return SDValue(Chain.getNode(), Op.getResNo());
02574   }
02575 
02576   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
02577   InFlag = Chain.getValue(1);
02578 
02579   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
02580                              DAG.getIntPtrConstant(BytesCalleePops, true),
02581                              InFlag);
02582   if (TheCall->getValueType(0) != MVT::Other)
02583     InFlag = Chain.getValue(1);
02584 
02585   SmallVector<SDValue, 16> ResultVals;
02586   SmallVector<CCValAssign, 16> RVLocs;
02587   unsigned CallerCC = DAG.getMachineFunction().getFunction()->getCallingConv();
02588   CCState CCInfo(CallerCC, isVarArg, TM, RVLocs);
02589   CCInfo.AnalyzeCallResult(TheCall, RetCC_PPC);
02590   
02591   // Copy all of the result registers out of their specified physreg.
02592   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
02593     CCValAssign &VA = RVLocs[i];
02594     MVT VT = VA.getValVT();
02595     assert(VA.isRegLoc() && "Can only return in registers!");
02596     Chain = DAG.getCopyFromReg(Chain, VA.getLocReg(), VT, InFlag).getValue(1);
02597     ResultVals.push_back(Chain.getValue(0));
02598     InFlag = Chain.getValue(2);
02599   }
02600 
02601   // If the function returns void, just return the chain.
02602   if (RVLocs.empty())
02603     return Chain;
02604   
02605   // Otherwise, merge everything together with a MERGE_VALUES node.
02606   ResultVals.push_back(Chain);
02607   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
02608                             &ResultVals[0], ResultVals.size());
02609   return Res.getValue(Op.getResNo());
02610 }
02611 
02612 SDValue PPCTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG, 
02613                                       TargetMachine &TM) {
02614   SmallVector<CCValAssign, 16> RVLocs;
02615   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
02616   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
02617   CCState CCInfo(CC, isVarArg, TM, RVLocs);
02618   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_PPC);
02619   
02620   // If this is the first return lowered for this function, add the regs to the
02621   // liveout set for the function.
02622   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
02623     for (unsigned i = 0; i != RVLocs.size(); ++i)
02624       DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
02625   }
02626 
02627   SDValue Chain = Op.getOperand(0);
02628 
02629   Chain = GetPossiblePreceedingTailCall(Chain, PPCISD::TAILCALL);
02630   if (Chain.getOpcode() == PPCISD::TAILCALL) {
02631     SDValue TailCall = Chain;
02632     SDValue TargetAddress = TailCall.getOperand(1);
02633     SDValue StackAdjustment = TailCall.getOperand(2);
02634 
02635     assert(((TargetAddress.getOpcode() == ISD::Register &&
02636              cast<RegisterSDNode>(TargetAddress)->getReg() == PPC::CTR) ||
02637             TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
02638             TargetAddress.getOpcode() == ISD::TargetGlobalAddress ||
02639             isa<ConstantSDNode>(TargetAddress)) &&
02640     "Expecting an global address, external symbol, absolute value or register");
02641 
02642     assert(StackAdjustment.getOpcode() == ISD::Constant &&
02643            "Expecting a const value");
02644 
02645     SmallVector<SDValue,8> Operands;
02646     Operands.push_back(Chain.getOperand(0));
02647     Operands.push_back(TargetAddress);
02648     Operands.push_back(StackAdjustment);
02649     // Copy registers used by the call. Last operand is a flag so it is not
02650     // copied.
02651     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
02652       Operands.push_back(Chain.getOperand(i));
02653     }
02654     return DAG.getNode(PPCISD::TC_RETURN, MVT::Other, &Operands[0],
02655                        Operands.size());
02656   }
02657 
02658   SDValue Flag;
02659   
02660   // Copy the result values into the output registers.
02661   for (unsigned i = 0; i != RVLocs.size(); ++i) {
02662     CCValAssign &VA = RVLocs[i];
02663     assert(VA.isRegLoc() && "Can only return in registers!");
02664     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
02665     Flag = Chain.getValue(1);
02666   }
02667 
02668   if (Flag.getNode())
02669     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain, Flag);
02670   else
02671     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Chain);
02672 }
02673 
02674 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
02675                                    const PPCSubtarget &Subtarget) {
02676   // When we pop the dynamic allocation we need to restore the SP link.
02677   
02678   // Get the corect type for pointers.
02679   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02680 
02681   // Construct the stack pointer operand.
02682   bool IsPPC64 = Subtarget.isPPC64();
02683   unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
02684   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
02685 
02686   // Get the operands for the STACKRESTORE.
02687   SDValue Chain = Op.getOperand(0);
02688   SDValue SaveSP = Op.getOperand(1);
02689   
02690   // Load the old link SP.
02691   SDValue LoadLinkSP = DAG.getLoad(PtrVT, Chain, StackPtr, NULL, 0);
02692   
02693   // Restore the stack pointer.
02694   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), SP, SaveSP);
02695   
02696   // Store the old link SP.
02697   return DAG.getStore(Chain, LoadLinkSP, StackPtr, NULL, 0);
02698 }
02699 
02700 
02701 
02702 SDValue
02703 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
02704   MachineFunction &MF = DAG.getMachineFunction();
02705   bool IsPPC64 = PPCSubTarget.isPPC64();
02706   bool isMachoABI = PPCSubTarget.isMachoABI();
02707   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02708 
02709   // Get current frame pointer save index.  The users of this index will be
02710   // primarily DYNALLOC instructions.
02711   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
02712   int RASI = FI->getReturnAddrSaveIndex();
02713 
02714   // If the frame pointer save index hasn't been defined yet.
02715   if (!RASI) {
02716     // Find out what the fix offset of the frame pointer save area.
02717     int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isMachoABI);
02718     // Allocate the frame index for frame pointer save area.
02719     RASI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, LROffset);
02720     // Save the result.
02721     FI->setReturnAddrSaveIndex(RASI);
02722   }
02723   return DAG.getFrameIndex(RASI, PtrVT);
02724 }
02725 
02726 SDValue
02727 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
02728   MachineFunction &MF = DAG.getMachineFunction();
02729   bool IsPPC64 = PPCSubTarget.isPPC64();
02730   bool isMachoABI = PPCSubTarget.isMachoABI();
02731   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02732 
02733   // Get current frame pointer save index.  The users of this index will be
02734   // primarily DYNALLOC instructions.
02735   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
02736   int FPSI = FI->getFramePointerSaveIndex();
02737 
02738   // If the frame pointer save index hasn't been defined yet.
02739   if (!FPSI) {
02740     // Find out what the fix offset of the frame pointer save area.
02741     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isMachoABI);
02742     
02743     // Allocate the frame index for frame pointer save area.
02744     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset); 
02745     // Save the result.
02746     FI->setFramePointerSaveIndex(FPSI);                      
02747   }
02748   return DAG.getFrameIndex(FPSI, PtrVT);
02749 }
02750 
02751 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
02752                                          SelectionDAG &DAG,
02753                                          const PPCSubtarget &Subtarget) {
02754   // Get the inputs.
02755   SDValue Chain = Op.getOperand(0);
02756   SDValue Size  = Op.getOperand(1);
02757   
02758   // Get the corect type for pointers.
02759   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02760   // Negate the size.
02761   SDValue NegSize = DAG.getNode(ISD::SUB, PtrVT,
02762                                   DAG.getConstant(0, PtrVT), Size);
02763   // Construct a node for the frame pointer save index.
02764   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
02765   // Build a DYNALLOC node.
02766   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
02767   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
02768   return DAG.getNode(PPCISD::DYNALLOC, VTs, Ops, 3);
02769 }
02770 
02771 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
02772 /// possible.
02773 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
02774   // Not FP? Not a fsel.
02775   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
02776       !Op.getOperand(2).getValueType().isFloatingPoint())
02777     return SDValue();
02778   
02779   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
02780   
02781   // Cannot handle SETEQ/SETNE.
02782   if (CC == ISD::SETEQ || CC == ISD::SETNE) return SDValue();
02783   
02784   MVT ResVT = Op.getValueType();
02785   MVT CmpVT = Op.getOperand(0).getValueType();
02786   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
02787   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
02788   
02789   // If the RHS of the comparison is a 0.0, we don't need to do the
02790   // subtraction at all.
02791   if (isFloatingPointZero(RHS))
02792     switch (CC) {
02793     default: break;       // SETUO etc aren't handled by fsel.
02794     case ISD::SETULT:
02795     case ISD::SETLT:
02796       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
02797     case ISD::SETOGE:
02798     case ISD::SETGE:
02799       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
02800         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
02801       return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
02802     case ISD::SETUGT:
02803     case ISD::SETGT:
02804       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
02805     case ISD::SETOLE:
02806     case ISD::SETLE:
02807       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
02808         LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
02809       return DAG.getNode(PPCISD::FSEL, ResVT,
02810                          DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
02811     }
02812       
02813   SDValue Cmp;
02814   switch (CC) {
02815   default: break;       // SETUO etc aren't handled by fsel.
02816   case ISD::SETULT:
02817   case ISD::SETLT:
02818     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
02819     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
02820       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
02821       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
02822   case ISD::SETOGE:
02823   case ISD::SETGE:
02824     Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
02825     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
02826       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
02827       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
02828   case ISD::SETUGT:
02829   case ISD::SETGT:
02830     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
02831     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
02832       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
02833       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
02834   case ISD::SETOLE:
02835   case ISD::SETLE:
02836     Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
02837     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
02838       Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
02839       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
02840   }
02841   return SDValue();
02842 }
02843 
02844 // FIXME: Split this code up when LegalizeDAGTypes lands.
02845 SDValue PPCTargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
02846   assert(Op.getOperand(0).getValueType().isFloatingPoint());
02847   SDValue Src = Op.getOperand(0);
02848   if (Src.getValueType() == MVT::f32)
02849     Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
02850 
02851   SDValue Tmp;
02852   switch (Op.getValueType().getSimpleVT()) {
02853   default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
02854   case MVT::i32:
02855     Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
02856     break;
02857   case MVT::i64:
02858     Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
02859     break;
02860   }
02861 
02862   // Convert the FP value to an int value through memory.
02863   SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
02864 
02865   // Emit a store to the stack slot.
02866   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Tmp, FIPtr, NULL, 0);
02867 
02868   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
02869   // add in a bias.
02870   if (Op.getValueType() == MVT::i32)
02871     FIPtr = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr,
02872                         DAG.getConstant(4, FIPtr.getValueType()));
02873   return DAG.getLoad(Op.getValueType(), Chain, FIPtr, NULL, 0);
02874 }
02875 
02876 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
02877   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
02878   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
02879     return SDValue();
02880 
02881   if (Op.getOperand(0).getValueType() == MVT::i64) {
02882     SDValue Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
02883     SDValue FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
02884     if (Op.getValueType() == MVT::f32)
02885       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP, DAG.getIntPtrConstant(0));
02886     return FP;
02887   }
02888   
02889   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
02890          "Unhandled SINT_TO_FP type in custom expander!");
02891   // Since we only generate this in 64-bit mode, we can take advantage of
02892   // 64-bit registers.  In particular, sign extend the input value into the
02893   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
02894   // then lfd it and fcfid it.
02895   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
02896   int FrameIdx = FrameInfo->CreateStackObject(8, 8);
02897   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02898   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
02899   
02900   SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, MVT::i32,
02901                                 Op.getOperand(0));
02902   
02903   // STD the extended value into the stack slot.
02904   MachineMemOperand MO(PseudoSourceValue::getFixedStack(FrameIdx),
02905                        MachineMemOperand::MOStore, 0, 8, 8);
02906   SDValue Store = DAG.getNode(PPCISD::STD_32, MVT::Other,
02907                                 DAG.getEntryNode(), Ext64, FIdx,
02908                                 DAG.getMemOperand(MO));
02909   // Load the value as a double.
02910   SDValue Ld = DAG.getLoad(MVT::f64, Store, FIdx, NULL, 0);
02911   
02912   // FCFID it and return it.
02913   SDValue FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Ld);
02914   if (Op.getValueType() == MVT::f32)
02915     FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP, DAG.getIntPtrConstant(0));
02916   return FP;
02917 }
02918 
02919 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
02920   /*
02921    The rounding mode is in bits 30:31 of FPSR, and has the following
02922    settings:
02923      00 Round to nearest
02924      01 Round to 0
02925      10 Round to +inf
02926      11 Round to -inf
02927 
02928   FLT_ROUNDS, on the other hand, expects the following:
02929     -1 Undefined
02930      0 Round to 0
02931      1 Round to nearest
02932      2 Round to +inf
02933      3 Round to -inf
02934 
02935   To perform the conversion, we do:
02936     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
02937   */
02938 
02939   MachineFunction &MF = DAG.getMachineFunction();
02940   MVT VT = Op.getValueType();
02941   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02942   std::vector<MVT> NodeTys;
02943   SDValue MFFSreg, InFlag;
02944 
02945   // Save FP Control Word to register
02946   NodeTys.push_back(MVT::f64);    // return register
02947   NodeTys.push_back(MVT::Flag);   // unused in this context
02948   SDValue Chain = DAG.getNode(PPCISD::MFFS, NodeTys, &InFlag, 0);
02949 
02950   // Save FP register to stack slot
02951   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
02952   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
02953   SDValue Store = DAG.getStore(DAG.getEntryNode(), Chain,
02954                                  StackSlot, NULL, 0);
02955 
02956   // Load FP Control Word from low 32 bits of stack slot.
02957   SDValue Four = DAG.getConstant(4, PtrVT);
02958   SDValue Addr = DAG.getNode(ISD::ADD, PtrVT, StackSlot, Four);
02959   SDValue CWD = DAG.getLoad(MVT::i32, Store, Addr, NULL, 0);
02960 
02961   // Transform as necessary
02962   SDValue CWD1 =
02963     DAG.getNode(ISD::AND, MVT::i32,
02964                 CWD, DAG.getConstant(3, MVT::i32));
02965   SDValue CWD2 =
02966     DAG.getNode(ISD::SRL, MVT::i32,
02967                 DAG.getNode(ISD::AND, MVT::i32,
02968                             DAG.getNode(ISD::XOR, MVT::i32,
02969                                         CWD, DAG.getConstant(3, MVT::i32)),
02970                             DAG.getConstant(3, MVT::i32)),
02971                 DAG.getConstant(1, MVT::i32));
02972 
02973   SDValue RetVal =
02974     DAG.getNode(ISD::XOR, MVT::i32, CWD1, CWD2);
02975 
02976   return DAG.getNode((VT.getSizeInBits() < 16 ?
02977                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
02978 }
02979 
02980 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) {
02981   MVT VT = Op.getValueType();
02982   unsigned BitWidth = VT.getSizeInBits();
02983   assert(Op.getNumOperands() == 3 &&
02984          VT == Op.getOperand(1).getValueType() &&
02985          "Unexpected SHL!");
02986   
02987   // Expand into a bunch of logical ops.  Note that these ops
02988   // depend on the PPC behavior for oversized shift amounts.
02989   SDValue Lo = Op.getOperand(0);
02990   SDValue Hi = Op.getOperand(1);
02991   SDValue Amt = Op.getOperand(2);
02992   MVT AmtVT = Amt.getValueType();
02993   
02994   SDValue Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
02995                              DAG.getConstant(BitWidth, AmtVT), Amt);
02996   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, VT, Hi, Amt);
02997   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, VT, Lo, Tmp1);
02998   SDValue Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
02999   SDValue Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
03000                              DAG.getConstant(-BitWidth, AmtVT));
03001   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, VT, Lo, Tmp5);
03002   SDValue OutHi = DAG.getNode(ISD::OR, VT, Tmp4, Tmp6);
03003   SDValue OutLo = DAG.getNode(PPCISD::SHL, VT, Lo, Amt);
03004   SDValue OutOps[] = { OutLo, OutHi };
03005   return DAG.getMergeValues(OutOps, 2);
03006 }
03007 
03008 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) {
03009   MVT VT = Op.getValueType();
03010   unsigned BitWidth = VT.getSizeInBits();
03011   assert(Op.getNumOperands() == 3 &&
03012          VT == Op.getOperand(1).getValueType() &&
03013          "Unexpected SRL!");
03014   
03015   // Expand into a bunch of logical ops.  Note that these ops
03016   // depend on the PPC behavior for oversized shift amounts.
03017   SDValue Lo = Op.getOperand(0);
03018   SDValue Hi = Op.getOperand(1);
03019   SDValue Amt = Op.getOperand(2);
03020   MVT AmtVT = Amt.getValueType();
03021   
03022   SDValue Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
03023                              DAG.getConstant(BitWidth, AmtVT), Amt);
03024   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, VT, Lo, Amt);
03025   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, VT, Hi, Tmp1);
03026   SDValue Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
03027   SDValue Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
03028                              DAG.getConstant(-BitWidth, AmtVT));
03029   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, VT, Hi, Tmp5);
03030   SDValue OutLo = DAG.getNode(ISD::OR, VT, Tmp4, Tmp6);
03031   SDValue OutHi = DAG.getNode(PPCISD::SRL, VT, Hi, Amt);
03032   SDValue OutOps[] = { OutLo, OutHi };
03033   return DAG.getMergeValues(OutOps, 2);
03034 }
03035 
03036 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) {
03037   MVT VT = Op.getValueType();
03038   unsigned BitWidth = VT.getSizeInBits();
03039   assert(Op.getNumOperands() == 3 &&
03040          VT == Op.getOperand(1).getValueType() &&
03041          "Unexpected SRA!");
03042   
03043   // Expand into a bunch of logical ops, followed by a select_cc.
03044   SDValue Lo = Op.getOperand(0);
03045   SDValue Hi = Op.getOperand(1);
03046   SDValue Amt = Op.getOperand(2);
03047   MVT AmtVT = Amt.getValueType();
03048   
03049   SDValue Tmp1 = DAG.getNode(ISD::SUB, AmtVT,
03050                              DAG.getConstant(BitWidth, AmtVT), Amt);
03051   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, VT, Lo, Amt);
03052   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, VT, Hi, Tmp1);
03053   SDValue Tmp4 = DAG.getNode(ISD::OR , VT, Tmp2, Tmp3);
03054   SDValue Tmp5 = DAG.getNode(ISD::ADD, AmtVT, Amt,
03055                              DAG.getConstant(-BitWidth, AmtVT));
03056   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, VT, Hi, Tmp5);
03057   SDValue OutHi = DAG.getNode(PPCISD::SRA, VT, Hi, Amt);
03058   SDValue OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, AmtVT),
03059                                   Tmp4, Tmp6, ISD::SETLE);
03060   SDValue OutOps[] = { OutLo, OutHi };
03061   return DAG.getMergeValues(OutOps, 2);
03062 }
03063 
03064 //===----------------------------------------------------------------------===//
03065 // Vector related lowering.
03066 //
03067 
03068 // If this is a vector of constants or undefs, get the bits.  A bit in
03069 // UndefBits is set if the corresponding element of the vector is an 
03070 // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
03071 // zero.   Return true if this is not an array of constants, false if it is.
03072 //
03073 static bool GetConstantBuildVectorBits(SDNode *BV, uint64_t VectorBits[2],
03074                                        uint64_t UndefBits[2]) {
03075   // Start with zero'd results.
03076   VectorBits[0] = VectorBits[1] = UndefBits[0] = UndefBits[1] = 0;
03077   
03078   unsigned EltBitSize = BV->getOperand(0).getValueType().getSizeInBits();
03079   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
03080     SDValue OpVal = BV->getOperand(i);
03081     
03082     unsigned PartNo = i >= e/2;     // In the upper 128 bits?
03083     unsigned SlotNo = e/2 - (i & (e/2-1))-1;  // Which subpiece of the uint64_t.
03084 
03085     uint64_t EltBits = 0;
03086     if (OpVal.getOpcode() == ISD::UNDEF) {
03087       uint64_t EltUndefBits = ~0U >> (32-EltBitSize);
03088       UndefBits[PartNo] |= EltUndefBits << (SlotNo*EltBitSize);
03089       continue;
03090     } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
03091       EltBits = CN->getZExtValue() & (~0U >> (32-EltBitSize));
03092     } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
03093       assert(CN->getValueType(0) == MVT::f32 &&
03094              "Only one legal FP vector type!");
03095       EltBits = FloatToBits(CN->getValueAPF().convertToFloat());
03096     } else {
03097       // Nonconstant element.
03098       return true;
03099     }
03100     
03101     VectorBits[PartNo] |= EltBits << (SlotNo*EltBitSize);
03102   }
03103   
03104   //printf("%llx %llx  %llx %llx\n", 
03105   //       VectorBits[0], VectorBits[1], UndefBits[0], UndefBits[1]);
03106   return false;
03107 }
03108 
03109 // If this is a splat (repetition) of a value across the whole vector, return
03110 // the smallest size that splats it.  For example, "0x01010101010101..." is a
03111 // splat of 0x01, 0x0101, and 0x01010101.  We return SplatBits = 0x01 and 
03112 // SplatSize = 1 byte.
03113 static bool isConstantSplat(const uint64_t Bits128[2], 
03114                             const uint64_t Undef128[2],
03115                             unsigned &SplatBits, unsigned &SplatUndef,
03116                             unsigned &SplatSize) {
03117   
03118   // Don't let undefs prevent splats from matching.  See if the top 64-bits are
03119   // the same as the lower 64-bits, ignoring undefs.
03120   if ((Bits128[0] & ~Undef128[1]) != (Bits128[1] & ~Undef128[0]))
03121     return false;  // Can't be a splat if two pieces don't match.
03122   
03123   uint64_t Bits64  = Bits128[0] | Bits128[1];
03124   uint64_t Undef64 = Undef128[0] & Undef128[1];
03125   
03126   // Check that the top 32-bits are the same as the lower 32-bits, ignoring
03127   // undefs.
03128   if ((Bits64 & (~Undef64 >> 32)) != ((Bits64 >> 32) & ~Undef64))
03129     return false;  // Can't be a splat if two pieces don't match.
03130 
03131   uint32_t Bits32  = uint32_t(Bits64) | uint32_t(Bits64 >> 32);
03132   uint32_t Undef32 = uint32_t(Undef64) & uint32_t(Undef64 >> 32);
03133 
03134   // If the top 16-bits are different than the lower 16-bits, ignoring
03135   // undefs, we have an i32 splat.
03136   if ((Bits32 & (~Undef32 >> 16)) != ((Bits32 >> 16) & ~Undef32)) {
03137     SplatBits = Bits32;
03138     SplatUndef = Undef32;
03139     SplatSize = 4;
03140     return true;
03141   }
03142   
03143   uint16_t Bits16  = uint16_t(Bits32)  | uint16_t(Bits32 >> 16);
03144   uint16_t Undef16 = uint16_t(Undef32) & uint16_t(Undef32 >> 16);
03145 
03146   // If the top 8-bits are different than the lower 8-bits, ignoring
03147   // undefs, we have an i16 splat.
03148   if ((Bits16 & (uint16_t(~Undef16) >> 8)) != ((Bits16 >> 8) & ~Undef16)) {
03149     SplatBits = Bits16;
03150     SplatUndef = Undef16;
03151     SplatSize = 2;
03152     return true;
03153   }
03154   
03155   // Otherwise, we have an 8-bit splat.
03156   SplatBits  = uint8_t(Bits16)  | uint8_t(Bits16 >> 8);
03157   SplatUndef = uint8_t(Undef16) & uint8_t(Undef16 >> 8);
03158   SplatSize = 1;
03159   return true;
03160 }
03161 
03162 /// BuildSplatI - Build a canonical splati of Val with an element size of
03163 /// SplatSize.  Cast the result to VT.
03164 static SDValue BuildSplatI(int Val, unsigned SplatSize, MVT VT,
03165                              SelectionDAG &DAG) {
03166   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
03167 
03168   static const MVT VTys[] = { // canonical VT to use for each size.
03169     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
03170   };
03171 
03172   MVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
03173   
03174   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
03175   if (Val == -1)
03176     SplatSize = 1;
03177   
03178   MVT CanonicalVT = VTys[SplatSize-1];
03179   
03180   // Build a canonical splat for this value.
03181   SDValue Elt = DAG.getConstant(Val, CanonicalVT.getVectorElementType());
03182   SmallVector<SDValue, 8> Ops;
03183   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
03184   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, CanonicalVT,
03185                               &Ops[0], Ops.size());
03186   return DAG.getNode(ISD::BIT_CONVERT, ReqVT, Res);
03187 }
03188 
03189 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
03190 /// specified intrinsic ID.
03191 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
03192                                   SelectionDAG &DAG, 
03193                                   MVT DestVT = MVT::Other) {
03194   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
03195   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
03196                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
03197 }
03198 
03199 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
03200 /// specified intrinsic ID.
03201 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
03202                                   SDValue Op2, SelectionDAG &DAG, 
03203                                   MVT DestVT = MVT::Other) {
03204   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
03205   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DestVT,
03206                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
03207 }
03208 
03209 
03210 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
03211 /// amount.  The result has the specified value type.
03212 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
03213                              MVT VT, SelectionDAG &DAG) {
03214   // Force LHS/RHS to be the right type.
03215   LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, LHS);
03216   RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, RHS);
03217 
03218   SDValue Ops[16];
03219   for (unsigned i = 0; i != 16; ++i)
03220     Ops[i] = DAG.getConstant(i+Amt, MVT::i8);
03221   SDValue T = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, LHS, RHS,
03222                             DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops,16));
03223   return DAG.getNode(ISD::BIT_CONVERT, VT, T);
03224 }
03225 
03226 // If this is a case we can't handle, return null and let the default
03227 // expansion code take care of it.  If we CAN select this case, and if it
03228 // selects to a single instruction, return Op.  Otherwise, if we can codegen
03229 // this case more efficiently than a constant pool load, lower it to the
03230 // sequence of ops that should be used.
03231 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 
03232                                                SelectionDAG &DAG) {
03233   // If this is a vector of constants or undefs, get the bits.  A bit in
03234   // UndefBits is set if the corresponding element of the vector is an 
03235   // ISD::UNDEF value.  For undefs, the corresponding VectorBits values are
03236   // zero. 
03237   uint64_t VectorBits[2];
03238   uint64_t UndefBits[2];
03239   if (GetConstantBuildVectorBits(Op.getNode(), VectorBits, UndefBits))
03240     return SDValue();   // Not a constant vector.
03241   
03242   // If this is a splat (repetition) of a value across the whole vector, return
03243   // the smallest size that splats it.  For example, "0x01010101010101..." is a
03244   // splat of 0x01, 0x0101, and 0x01010101.  We return SplatBits = 0x01 and 
03245   // SplatSize = 1 byte.
03246   unsigned SplatBits, SplatUndef, SplatSize;
03247   if (isConstantSplat(VectorBits, UndefBits, SplatBits, SplatUndef, SplatSize)){
03248     bool HasAnyUndefs = (UndefBits[0] | UndefBits[1]) != 0;
03249     
03250     // First, handle single instruction cases.
03251     
03252     // All zeros?
03253     if (SplatBits == 0) {
03254       // Canonicalize all zero vectors to be v4i32.
03255       if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
03256         SDValue Z = DAG.getConstant(0, MVT::i32);
03257         Z = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Z, Z, Z, Z);
03258         Op = DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Z);
03259       }
03260       return Op;
03261     }
03262 
03263     // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
03264     int32_t SextVal= int32_t(SplatBits << (32-8*SplatSize)) >> (32-8*SplatSize);
03265     if (SextVal >= -16 && SextVal <= 15)
03266       return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG);
03267     
03268     
03269     // Two instruction sequences.
03270     
03271     // If this value is in the range [-32,30] and is even, use:
03272     //    tmp = VSPLTI[bhw], result = add tmp, tmp
03273     if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
03274       SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG);
03275       Res = DAG.getNode(ISD::ADD, Res.getValueType(), Res, Res);
03276       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03277     }
03278     
03279     // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is 
03280     // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
03281     // for fneg/fabs.
03282     if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
03283       // Make -1 and vspltisw -1:
03284       SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG);
03285       
03286       // Make the VSLW intrinsic, computing 0x8000_0000.
03287       SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 
03288                                        OnesV, DAG);
03289       
03290       // xor by OnesV to invert it.
03291       Res = DAG.getNode(ISD::XOR, MVT::v4i32, Res, OnesV);
03292       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03293     }
03294 
03295     // Check to see if this is a wide variety of vsplti*, binop self cases.
03296     unsigned SplatBitSize = SplatSize*8;
03297     static const signed char SplatCsts[] = {
03298       -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
03299       -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
03300     };
03301     
03302     for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
03303       // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
03304       // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
03305       int i = SplatCsts[idx];
03306       
03307       // Figure out what shift amount will be used by altivec if shifted by i in
03308       // this splat size.
03309       unsigned TypeShiftAmt = i & (SplatBitSize-1);
03310       
03311       // vsplti + shl self.
03312       if (SextVal == (i << (int)TypeShiftAmt)) {
03313         SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
03314         static const unsigned IIDs[] = { // Intrinsic to use for each size.
03315           Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
03316           Intrinsic::ppc_altivec_vslw
03317         };
03318         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
03319         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03320       }
03321       
03322       // vsplti + srl self.
03323       if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
03324         SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
03325         static const unsigned IIDs[] = { // Intrinsic to use for each size.
03326           Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
03327           Intrinsic::ppc_altivec_vsrw
03328         };
03329         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
03330         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03331       }
03332       
03333       // vsplti + sra self.
03334       if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
03335         SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
03336         static const unsigned IIDs[] = { // Intrinsic to use for each size.
03337           Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
03338           Intrinsic::ppc_altivec_vsraw
03339         };
03340         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
03341         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03342       }
03343       
03344       // vsplti + rol self.
03345       if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
03346                            ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
03347         SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG);
03348         static const unsigned IIDs[] = { // Intrinsic to use for each size.
03349           Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
03350           Intrinsic::ppc_altivec_vrlw
03351         };
03352         Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG);
03353         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Res);
03354       }
03355 
03356       // t = vsplti c, result = vsldoi t, t, 1
03357       if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
03358         SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
03359         return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG);
03360       }
03361       // t = vsplti c, result = vsldoi t, t, 2
03362       if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
03363         SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
03364         return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG);
03365       }
03366       // t = vsplti c, result = vsldoi t, t, 3
03367       if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
03368         SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG);
03369         return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG);
03370       }
03371     }
03372     
03373     // Three instruction sequences.
03374     
03375     // Odd, in range [17,31]:  (vsplti C)-(vsplti -16).
03376     if (SextVal >= 0 && SextVal <= 31) {
03377       SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG);
03378       SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
03379       LHS = DAG.getNode(ISD::SUB, LHS.getValueType(), LHS, RHS);
03380       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
03381     }
03382     // Odd, in range [-31,-17]:  (vsplti C)+(vsplti -16).
03383     if (SextVal >= -31 && SextVal <= 0) {
03384       SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG);
03385       SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG);
03386       LHS = DAG.getNode(ISD::ADD, LHS.getValueType(), LHS, RHS);
03387       return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), LHS);
03388     }
03389   }
03390     
03391   return SDValue();
03392 }
03393 
03394 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
03395 /// the specified operations to build the shuffle.
03396 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
03397                                         SDValue RHS, SelectionDAG &DAG) {
03398   unsigned OpNum = (PFEntry >> 26) & 0x0F;
03399   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
03400   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
03401   
03402   enum {
03403     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
03404     OP_VMRGHW,
03405     OP_VMRGLW,
03406     OP_VSPLTISW0,
03407     OP_VSPLTISW1,
03408     OP_VSPLTISW2,
03409     OP_VSPLTISW3,
03410     OP_VSLDOI4,
03411     OP_VSLDOI8,
03412     OP_VSLDOI12
03413   };
03414   
03415   if (OpNum == OP_COPY) {
03416     if (LHSID == (1*9+2)*9+3) return LHS;
03417     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
03418     return RHS;
03419   }
03420   
03421   SDValue OpLHS, OpRHS;
03422   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG);
03423   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG);
03424   
03425   unsigned ShufIdxs[16];
03426   switch (OpNum) {
03427   default: assert(0 && "Unknown i32 permute!");
03428   case OP_VMRGHW:
03429     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
03430     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
03431     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
03432     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
03433     break;
03434   case OP_VMRGLW:
03435     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
03436     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
03437     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
03438     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
03439     break;
03440   case OP_VSPLTISW0:
03441     for (unsigned i = 0; i != 16; ++i)
03442       ShufIdxs[i] = (i&3)+0;
03443     break;
03444   case OP_VSPLTISW1:
03445     for (unsigned i = 0; i != 16; ++i)
03446       ShufIdxs[i] = (i&3)+4;
03447     break;
03448   case OP_VSPLTISW2:
03449     for (unsigned i = 0; i != 16; ++i)
03450       ShufIdxs[i] = (i&3)+8;
03451     break;
03452   case OP_VSPLTISW3:
03453     for (unsigned i = 0; i != 16; ++i)
03454       ShufIdxs[i] = (i&3)+12;
03455     break;
03456   case OP_VSLDOI4:
03457     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG);
03458   case OP_VSLDOI8:
03459     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG);
03460   case OP_VSLDOI12:
03461     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG);
03462   }
03463   SDValue Ops[16];
03464   for (unsigned i = 0; i != 16; ++i)
03465     Ops[i] = DAG.getConstant(ShufIdxs[i], MVT::i8);
03466   
03467   return DAG.getNode(ISD::VECTOR_SHUFFLE, OpLHS.getValueType(), OpLHS, OpRHS,
03468                      DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
03469 }
03470 
03471 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
03472 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
03473 /// return the code it can be lowered into.  Worst case, it can always be
03474 /// lowered into a vperm.
03475 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 
03476                                                  SelectionDAG &DAG) {
03477   SDValue V1 = Op.getOperand(0);
03478   SDValue V2 = Op.getOperand(1);
03479   SDValue PermMask = Op.getOperand(2);
03480   
03481   // Cases that are handled by instructions that take permute immediates
03482   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
03483   // selected by the instruction selector.
03484   if (V2.getOpcode() == ISD::UNDEF) {
03485     if (PPC::isSplatShuffleMask(PermMask.getNode(), 1) ||
03486         PPC::isSplatShuffleMask(PermMask.getNode(), 2) ||
03487         PPC::isSplatShuffleMask(PermMask.getNode(), 4) ||
03488         PPC::isVPKUWUMShuffleMask(PermMask.getNode(), true) ||
03489         PPC::isVPKUHUMShuffleMask(PermMask.getNode(), true) ||
03490         PPC::isVSLDOIShuffleMask(PermMask.getNode(), true) != -1 ||
03491         PPC::isVMRGLShuffleMask(PermMask.getNode(), 1, true) ||
03492         PPC::isVMRGLShuffleMask(PermMask.getNode(), 2, true) ||
03493         PPC::isVMRGLShuffleMask(PermMask.getNode(), 4, true) ||
03494         PPC::isVMRGHShuffleMask(PermMask.getNode(), 1, true) ||
03495         PPC::isVMRGHShuffleMask(PermMask.getNode(), 2, true) ||
03496         PPC::isVMRGHShuffleMask(PermMask.getNode(), 4, true)) {
03497       return Op;
03498     }
03499   }
03500   
03501   // Altivec has a variety of "shuffle immediates" that take two vector inputs
03502   // and produce a fixed permutation.  If any of these match, do not lower to
03503   // VPERM.
03504   if (PPC::isVPKUWUMShuffleMask(PermMask.getNode(), false) ||
03505       PPC::isVPKUHUMShuffleMask(PermMask.getNode(), false) ||
03506       PPC::isVSLDOIShuffleMask(PermMask.getNode(), false) != -1 ||
03507       PPC::isVMRGLShuffleMask(PermMask.getNode(), 1, false) ||
03508       PPC::isVMRGLShuffleMask(PermMask.getNode(), 2, false) ||
03509       PPC::isVMRGLShuffleMask(PermMask.getNode(), 4, false) ||
03510       PPC::isVMRGHShuffleMask(PermMask.getNode(), 1, false) ||
03511       PPC::isVMRGHShuffleMask(PermMask.getNode(), 2, false) ||
03512       PPC::isVMRGHShuffleMask(PermMask.getNode(), 4, false))
03513     return Op;
03514   
03515   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
03516   // perfect shuffle table to emit an optimal matching sequence.
03517   unsigned PFIndexes[4];
03518   bool isFourElementShuffle = true;
03519   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
03520     unsigned EltNo = 8;   // Start out undef.
03521     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
03522       if (PermMask.getOperand(i*4+j).getOpcode() == ISD::UNDEF)
03523         continue;   // Undef, ignore it.
03524       
03525       unsigned ByteSource = 
03526         cast<ConstantSDNode>(PermMask.getOperand(i*4+j))->getZExtValue();
03527       if ((ByteSource & 3) != j) {
03528         isFourElementShuffle = false;
03529         break;
03530       }
03531       
03532       if (EltNo == 8) {
03533         EltNo = ByteSource/4;
03534       } else if (EltNo != ByteSource/4) {
03535         isFourElementShuffle = false;
03536         break;
03537       }
03538     }
03539     PFIndexes[i] = EltNo;
03540   }
03541     
03542   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 
03543   // perfect shuffle vector to determine if it is cost effective to do this as
03544   // discrete instructions, or whether we should use a vperm.
03545   if (isFourElementShuffle) {
03546     // Compute the index in the perfect shuffle table.
03547     unsigned PFTableIndex = 
03548       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
03549     
03550     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
03551     unsigned Cost  = (PFEntry >> 30);
03552     
03553     // Determining when to avoid vperm is tricky.  Many things affect the cost
03554     // of vperm, particularly how many times the perm mask needs to be computed.
03555     // For example, if the perm mask can be hoisted out of a loop or is already
03556     // used (perhaps because there are multiple permutes with the same shuffle
03557     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
03558     // the loop requires an extra register.
03559     //
03560     // As a compromise, we only emit discrete instructions if the shuffle can be
03561     // generated in 3 or fewer operations.  When we have loop information 
03562     // available, if this block is within a loop, we should avoid using vperm
03563     // for 3-operation perms and use a constant pool load instead.
03564     if (Cost < 3) 
03565       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG);
03566   }
03567   
03568   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
03569   // vector that will get spilled to the constant pool.
03570   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
03571   
03572   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
03573   // that it is in input element units, not in bytes.  Convert now.
03574   MVT EltVT = V1.getValueType().getVectorElementType();
03575   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
03576   
03577   SmallVector<SDValue, 16> ResultMask;
03578   for (unsigned i = 0, e = PermMask.getNumOperands(); i != e; ++i) {
03579     unsigned SrcElt;
03580     if (PermMask.getOperand(i).getOpcode() == ISD::UNDEF)
03581       SrcElt = 0;
03582     else 
03583       SrcElt = cast<ConstantSDNode>(PermMask.getOperand(i))->getZExtValue();
03584     
03585     for (unsigned j = 0; j != BytesPerElement; ++j)
03586       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
03587                                            MVT::i8));
03588   }
03589   
03590   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8,
03591                                     &ResultMask[0], ResultMask.size());
03592   return DAG.getNode(PPCISD::VPERM, V1.getValueType(), V1, V2, VPermMask);
03593 }
03594 
03595 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
03596 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
03597 /// information about the intrinsic.
03598 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
03599                                   bool &isDot) {
03600   unsigned IntrinsicID =
03601     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
03602   CompareOpc = -1;
03603   isDot = false;
03604   switch (IntrinsicID) {
03605   default: return false;
03606     // Comparison predicates.
03607   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
03608   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
03609   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
03610   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
03611   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
03612   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
03613   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
03614   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
03615   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
03616   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
03617   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
03618   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
03619   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
03620     
03621     // Normal Comparisons.
03622   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
03623   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
03624   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
03625   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
03626   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
03627   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
03628   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
03629   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
03630   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
03631   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
03632   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
03633   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
03634   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
03635   }
03636   return true;
03637 }
03638 
03639 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
03640 /// lower, do it, otherwise return null.
03641 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 
03642                                                      SelectionDAG &DAG) {
03643   // If this is a lowered altivec predicate compare, CompareOpc is set to the
03644   // opcode number of the comparison.
03645   int CompareOpc;
03646   bool isDot;
03647   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
03648     return SDValue();    // Don't custom lower most intrinsics.
03649   
03650   // If this is a non-dot comparison, make the VCMP node and we are done.
03651   if (!isDot) {
03652     SDValue Tmp = DAG.getNode(PPCISD::VCMP, Op.getOperand(2).getValueType(),
03653                                 Op.getOperand(1), Op.getOperand(2),
03654                                 DAG.getConstant(CompareOpc, MVT::i32));
03655     return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Tmp);
03656   }
03657   
03658   // Create the PPCISD altivec 'dot' comparison node.
03659   SDValue Ops[] = {
03660     Op.getOperand(2),  // LHS
03661     Op.getOperand(3),  // RHS
03662     DAG.getConstant(CompareOpc, MVT::i32)
03663   };
03664   std::vector<MVT> VTs;
03665   VTs.push_back(Op.getOperand(2).getValueType());
03666   VTs.push_back(MVT::Flag);
03667   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
03668   
03669   // Now that we have the comparison, emit a copy from the CR to a GPR.
03670   // This is flagged to the above dot comparison.
03671   SDValue Flags = DAG.getNode(PPCISD::MFCR, MVT::i32,
03672                                 DAG.getRegister(PPC::CR6, MVT::i32),
03673                                 CompNode.getValue(1)); 
03674   
03675   // Unpack the result based on how the target uses it.
03676   unsigned BitNo;   // Bit # of CR6.
03677   bool InvertBit;   // Invert result?
03678   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
03679   default:  // Can't happen, don't crash on invalid number though.
03680   case 0:   // Return the value of the EQ bit of CR6.
03681     BitNo = 0; InvertBit = false;
03682     break;
03683   case 1:   // Return the inverted value of the EQ bit of CR6.
03684     BitNo = 0; InvertBit = true;
03685     break;
03686   case 2:   // Return the value of the LT bit of CR6.
03687     BitNo = 2; InvertBit = false;
03688     break;
03689   case 3:   // Return the inverted value of the LT bit of CR6.
03690     BitNo = 2; InvertBit = true;
03691     break;
03692   }
03693   
03694   // Shift the bit into the low position.
03695   Flags = DAG.getNode(ISD::SRL, MVT::i32, Flags,
03696                       DAG.getConstant(8-(3-BitNo), MVT::i32));
03697   // Isolate the bit.
03698   Flags = DAG.getNode(ISD::AND, MVT::i32, Flags,
03699                       DAG.getConstant(1, MVT::i32));
03700   
03701   // If we are supposed to, toggle the bit.
03702   if (InvertBit)
03703     Flags = DAG.getNode(ISD::XOR, MVT::i32, Flags,
03704                         DAG.getConstant(1, MVT::i32));
03705   return Flags;
03706 }
03707 
03708 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 
03709                                                    SelectionDAG &DAG) {
03710   // Create a stack slot that is 16-byte aligned.
03711   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
03712   int FrameIdx = FrameInfo->CreateStackObject(16, 16);
03713   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
03714   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
03715   
03716   // Store the input value into Value#0 of the stack slot.
03717   SDValue Store = DAG.getStore(DAG.getEntryNode(),
03718                                  Op.getOperand(0), FIdx, NULL, 0);
03719   // Load it out.
03720   return DAG.getLoad(Op.getValueType(), Store, FIdx, NULL, 0);
03721 }
03722 
03723 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) {
03724   if (Op.getValueType() == MVT::v4i32) {
03725     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
03726     
03727     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG);
03728     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG); // +16 as shift amt.
03729     
03730     SDValue RHSSwap =   // = vrlw RHS, 16
03731       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG);
03732     
03733     // Shrinkify inputs to v8i16.
03734     LHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, LHS);
03735     RHS = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHS);
03736     RHSSwap = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, RHSSwap);
03737     
03738     // Low parts multiplied together, generating 32-bit results (we ignore the
03739     // top parts).
03740     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
03741                                         LHS, RHS, DAG, MVT::v4i32);
03742     
03743     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
03744                                         LHS, RHSSwap, Zero, DAG, MVT::v4i32);
03745     // Shift the high parts up 16 bits.
03746     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, Neg16, DAG);
03747     return DAG.getNode(ISD::ADD, MVT::v4i32, LoProd, HiProd);
03748   } else if (Op.getValueType() == MVT::v8i16) {
03749     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
03750     
03751     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG);
03752 
03753     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
03754                             LHS, RHS, Zero, DAG);
03755   } else if (Op.getValueType() == MVT::v16i8) {
03756     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
03757     
03758     // Multiply the even 8-bit parts, producing 16-bit sums.
03759     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
03760                                            LHS, RHS, DAG, MVT::v8i16);
03761     EvenParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, EvenParts);
03762     
03763     // Multiply the odd 8-bit parts, producing 16-bit sums.
03764     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
03765                                           LHS, RHS, DAG, MVT::v8i16);
03766     OddParts = DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, OddParts);
03767     
03768     // Merge the results together.
03769     SDValue Ops[16];
03770     for (unsigned i = 0; i != 8; ++i) {
03771       Ops[i*2  ] = DAG.getConstant(2*i+1, MVT::i8);
03772       Ops[i*2+1] = DAG.getConstant(2*i+1+16, MVT::i8);
03773     }
03774     return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v16i8, EvenParts, OddParts,
03775                        DAG.getNode(ISD::BUILD_VECTOR, MVT::v16i8, Ops, 16));
03776   } else {
03777     assert(0 && "Unknown mul to lower!");
03778     abort();
03779   }
03780 }
03781 
03782 /// LowerOperation - Provide custom lowering hooks for some operations.
03783 ///
03784 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
03785   switch (Op.getOpcode()) {
03786   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
03787   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
03788   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
03789   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
03790   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
03791   case ISD::SETCC:              return LowerSETCC(Op, DAG);
03792   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
03793   case ISD::VASTART:            
03794     return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
03795                         VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
03796   
03797   case ISD::VAARG:            
03798     return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
03799                       VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
03800 
03801   case ISD::FORMAL_ARGUMENTS:
03802     return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex, 
03803                                  VarArgsStackOffset, VarArgsNumGPR,
03804                                  VarArgsNumFPR, PPCSubTarget);
03805 
03806   case ISD::CALL:               return LowerCALL(Op, DAG, PPCSubTarget,
03807                                                  getTargetMachine());
03808   case ISD::RET:                return LowerRET(Op, DAG, getTargetMachine());
03809   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
03810   case ISD::DYNAMIC_STACKALLOC:
03811     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
03812 
03813   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
03814   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
03815   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
03816   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
03817 
03818   // Lower 64-bit shifts.
03819   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
03820   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
03821   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
03822 
03823   // Vector-related lowering.
03824   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
03825   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
03826   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
03827   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
03828   case ISD::MUL:                return LowerMUL(Op, DAG);
03829   
03830   // Frame & Return address.
03831   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
03832   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
03833   }
03834   return SDValue();
03835 }
03836 
03837 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
03838                                            SmallVectorImpl<SDValue>&Results,
03839                                            SelectionDAG &DAG) {
03840   switch (N->getOpcode()) {
03841   default:
03842     assert(false && "Do not know how to custom type legalize this operation!");
03843     return;
03844   case ISD::FP_ROUND_INREG: {
03845     assert(N->getValueType(0) == MVT::ppcf128);
03846     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
03847     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::f64, N->getOperand(0),
03848                              DAG.getIntPtrConstant(0));
03849     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::f64, N->getOperand(0),
03850                              DAG.getIntPtrConstant(1));
03851 
03852     // This sequence changes FPSCR to do round-to-zero, adds the two halves
03853     // of the long double, and puts FPSCR back the way it was.  We do not
03854     // actually model FPSCR.
03855     std::vector<MVT> NodeTys;
03856     SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
03857 
03858     NodeTys.push_back(MVT::f64);   // Return register
03859     NodeTys.push_back(MVT::Flag);    // Returns a flag for later insns
03860     Result = DAG.getNode(PPCISD::MFFS, NodeTys, &InFlag, 0);
03861     MFFSreg = Result.getValue(0);
03862     InFlag = Result.getValue(1);
03863 
03864     NodeTys.clear();
03865     NodeTys.push_back(MVT::Flag);   // Returns a flag
03866     Ops[0] = DAG.getConstant(31, MVT::i32);
03867     Ops[1] = InFlag;
03868     Result = DAG.getNode(PPCISD::MTFSB1, NodeTys, Ops, 2);
03869     InFlag = Result.getValue(0);
03870 
03871     NodeTys.clear();
03872     NodeTys.push_back(MVT::Flag);   // Returns a flag
03873     Ops[0] = DAG.getConstant(30, MVT::i32);
03874     Ops[1] = InFlag;
03875     Result = DAG.getNode(PPCISD::MTFSB0, NodeTys, Ops, 2);
03876     InFlag = Result.getValue(0);
03877 
03878     NodeTys.clear();
03879     NodeTys.push_back(MVT::f64);    // result of add
03880     NodeTys.push_back(MVT::Flag);   // Returns a flag
03881     Ops[0] = Lo;
03882     Ops[1] = Hi;
03883     Ops[2] = InFlag;
03884     Result = DAG.getNode(PPCISD::FADDRTZ, NodeTys, Ops, 3);
03885     FPreg = Result.getValue(0);
03886     InFlag = Result.getValue(1);
03887 
03888     NodeTys.clear();
03889     NodeTys.push_back(MVT::f64);
03890     Ops[0] = DAG.getConstant(1, MVT::i32);
03891     Ops[1] = MFFSreg;
03892     Ops[2] = FPreg;
03893     Ops[3] = InFlag;
03894     Result = DAG.getNode(PPCISD::MTFSF, NodeTys, Ops, 4);
03895     FPreg = Result.getValue(0);
03896 
03897     // We know the low half is about to be thrown away, so just use something
03898     // convenient.
03899     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::ppcf128, FPreg, FPreg));
03900     return;
03901   }
03902   case ISD::FP_TO_SINT:
03903     Results.push_back(LowerFP_TO_SINT(SDValue(N, 0), DAG));
03904     return;
03905   }
03906 }
03907 
03908 
03909 //===----------------------------------------------------------------------===//
03910 //  Other Lowering Code
03911 //===----------------------------------------------------------------------===//
03912 
03913 MachineBasicBlock *
03914 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
03915                                     bool is64bit, unsigned BinOpcode) {
03916   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
03917   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
03918 
03919   const BasicBlock *LLVM_BB = BB->getBasicBlock();
03920   MachineFunction *F = BB->getParent();
03921   MachineFunction::iterator It = BB;
03922   ++It;
03923 
03924   unsigned dest = MI->getOperand(0).getReg();
03925   unsigned ptrA = MI->getOperand(1).getReg();
03926   unsigned ptrB = MI->getOperand(2).getReg();
03927   unsigned incr = MI->getOperand(3).getReg();
03928 
03929   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
03930   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
03931   F->insert(It, loopMBB);
03932   F->insert(It, exitMBB);
03933   exitMBB->transferSuccessors(BB);
03934 
03935   MachineRegisterInfo &RegInfo = F->getRegInfo();
03936   unsigned TmpReg = (!BinOpcode) ? incr :
03937     RegInfo.createVirtualRegister(
03938        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
03939                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
03940 
03941   //  thisMBB:
03942   //   ...
03943   //   fallthrough --> loopMBB
03944   BB->addSuccessor(loopMBB);
03945 
03946   //  loopMBB:
03947   //   l[wd]arx dest, ptr
03948   //   add r0, dest, incr
03949   //   st[wd]cx. r0, ptr
03950   //   bne- loopMBB
03951   //   fallthrough --> exitMBB
03952   BB = loopMBB;
03953   BuildMI(BB, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
03954     .addReg(ptrA).addReg(ptrB);
03955   if (BinOpcode)
03956     BuildMI(BB, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
03957   BuildMI(BB, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
03958     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
03959   BuildMI(BB, TII->get(PPC::BCC))
03960     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);    
03961   BB->addSuccessor(loopMBB);
03962   BB->addSuccessor(exitMBB);
03963 
03964   //  exitMBB:
03965   //   ...
03966   BB = exitMBB;
03967   return BB;
03968 }
03969 
03970 MachineBasicBlock *
03971 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, 
03972                                             MachineBasicBlock *BB,
03973                                             bool is8bit,    // operation
03974                                             unsigned BinOpcode) {
03975   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
03976   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
03977   // In 64 bit mode we have to use 64 bits for addresses, even though the
03978   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
03979   // registers without caring whether they're 32 or 64, but here we're
03980   // doing actual arithmetic on the addresses.
03981   bool is64bit = PPCSubTarget.isPPC64();
03982 
03983   const BasicBlock *LLVM_BB = BB->getBasicBlock();
03984   MachineFunction *F = BB->getParent();
03985   MachineFunction::iterator It = BB;
03986   ++It;
03987 
03988   unsigned dest = MI->getOperand(0).getReg();
03989   unsigned ptrA = MI->getOperand(1).getReg();
03990   unsigned ptrB = MI->getOperand(2).getReg();
03991   unsigned incr = MI->getOperand(3).getReg();
03992 
03993   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
03994   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
03995   F->insert(It, loopMBB);
03996   F->insert(It, exitMBB);
03997   exitMBB->transferSuccessors(BB);
03998 
03999   MachineRegisterInfo &RegInfo = F->getRegInfo();
04000   const TargetRegisterClass *RC = 
04001     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
04002               (const TargetRegisterClass *) &PPC::GPRCRegClass;
04003   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
04004   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
04005   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
04006   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
04007   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
04008   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
04009   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
04010   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
04011   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
04012   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
04013   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
04014   unsigned Ptr1Reg;
04015   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
04016 
04017   //  thisMBB:
04018   //   ...
04019   //   fallthrough --> loopMBB
04020   BB->addSuccessor(loopMBB);
04021 
04022   // The 4-byte load must be aligned, while a char or short may be
04023   // anywhere in the word.  Hence all this nasty bookkeeping code.
04024   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
04025   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
04026   //   xori shift, shift1, 24 [16]
04027   //   rlwinm ptr, ptr1, 0, 0, 29
04028   //   slw incr2, incr, shift
04029   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
04030   //   slw mask, mask2, shift
04031   //  loopMBB:
04032   //   lwarx tmpDest, ptr
04033   //   add tmp, tmpDest, incr2
04034   //   andc tmp2, tmpDest, mask
04035   //   and tmp3, tmp, mask
04036   //   or tmp4, tmp3, tmp2
04037   //   stwcx. tmp4, ptr
04038   //   bne- loopMBB
04039   //   fallthrough --> exitMBB
04040   //   srw dest, tmpDest, shift
04041 
04042   if (ptrA!=PPC::R0) {
04043     Ptr1Reg = RegInfo.createVirtualRegister(RC);
04044     BuildMI(BB, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
04045       .addReg(ptrA).addReg(ptrB);
04046   } else {
04047     Ptr1Reg = ptrB;
04048   }
04049   BuildMI(BB, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
04050       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
04051   BuildMI(BB, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
04052       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
04053   if (is64bit)
04054     BuildMI(BB, TII->get(PPC::RLDICR), PtrReg)
04055       .addReg(Ptr1Reg).addImm(0).addImm(61);
04056   else
04057     BuildMI(BB, TII->get(PPC::RLWINM), PtrReg)
04058       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
04059   BuildMI(BB, TII->get(PPC::SLW), Incr2Reg)
04060       .addReg(incr).addReg(ShiftReg);
04061   if (is8bit)
04062     BuildMI(BB, TII->get(PPC::LI), Mask2Reg).addImm(255);
04063   else {
04064     BuildMI(BB, TII->get(PPC::LI), Mask3Reg).addImm(0);
04065     BuildMI(BB, TII->get(PPC::ORI), Mask2Reg).addReg(Mask3Reg).addImm(65535);
04066   }
04067   BuildMI(BB, TII->get(PPC::SLW), MaskReg)
04068       .addReg(Mask2Reg).addReg(ShiftReg);
04069 
04070   BB = loopMBB;
04071   BuildMI(BB, TII->get(PPC::LWARX), TmpDestReg)
04072     .addReg(PPC::R0).addReg(PtrReg);
04073   if (BinOpcode)
04074     BuildMI(BB, TII->get(BinOpcode), TmpReg)
04075       .addReg(Incr2Reg).addReg(TmpDestReg);
04076   BuildMI(BB, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
04077     .addReg(TmpDestReg).addReg(MaskReg);
04078   BuildMI(BB, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
04079     .addReg(TmpReg).addReg(MaskReg);
04080   BuildMI(BB, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
04081     .addReg(Tmp3Reg).addReg(Tmp2Reg);
04082   BuildMI(BB, TII->get(PPC::STWCX))
04083     .addReg(Tmp4Reg).addReg(PPC::R0).addReg(PtrReg);
04084   BuildMI(BB, TII->get(PPC::BCC))
04085     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);    
04086   BB->addSuccessor(loopMBB);
04087   BB->addSuccessor(exitMBB);
04088 
04089   //  exitMBB:
04090   //   ...
04091   BB = exitMBB;
04092   BuildMI(BB, TII->get(PPC::SRW), dest).addReg(TmpDestReg).addReg(ShiftReg);
04093   return BB;
04094 }
04095 
04096 MachineBasicBlock *
04097 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
04098                                                MachineBasicBlock *BB) {
04099   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
04100 
04101   // To "insert" these instructions we actually have to insert their
04102   // control-flow patterns.
04103   const BasicBlock *LLVM_BB = BB->getBasicBlock();
04104   MachineFunction::iterator It = BB;
04105   ++It;
04106 
04107   MachineFunction *F = BB->getParent();
04108 
04109   if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
04110       MI->getOpcode() == PPC::SELECT_CC_I8 ||
04111       MI->getOpcode() == PPC::SELECT_CC_F4 ||
04112       MI->getOpcode() == PPC::SELECT_CC_F8 ||
04113       MI->getOpcode() == PPC::SELECT_CC_VRRC) {
04114 
04115     // The incoming instruction knows the destination vreg to set, the
04116     // condition code register to branch on, the true/false values to
04117     // select between, and a branch opcode to use.
04118 
04119     //  thisMBB:
04120     //  ...
04121     //   TrueVal = ...
04122     //   cmpTY ccX, r1, r2
04123     //   bCC copy1MBB
04124     //   fallthrough --> copy0MBB
04125     MachineBasicBlock *thisMBB = BB;
04126     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
04127     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
04128     unsigned SelectPred = MI->getOperand(4).getImm();
04129     BuildMI(BB, TII->get(PPC::BCC))
04130       .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
04131     F->insert(It, copy0MBB);
04132     F->insert(It, sinkMBB);
04133     // Update machine-CFG edges by transferring all successors of the current
04134     // block to the new block which will contain the Phi node for the select.
04135     sinkMBB->transferSuccessors(BB);
04136     // Next, add the true and fallthrough blocks as its successors.
04137     BB->addSuccessor(copy0MBB);
04138     BB->addSuccessor(sinkMBB);
04139     
04140     //  copy0MBB:
04141     //   %FalseValue = ...
04142     //   # fallthrough to sinkMBB
04143     BB = copy0MBB;
04144     
04145     // Update machine-CFG edges
04146     BB->addSuccessor(sinkMBB);
04147     
04148     //  sinkMBB:
04149     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
04150     //  ...
04151     BB = sinkMBB;
04152     BuildMI(BB, TII->get(PPC::PHI), MI->getOperand(0).getReg())
04153       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
04154       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
04155   }
04156   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
04157     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
04158   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
04159     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
04160   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
04161     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
04162   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
04163     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
04164 
04165   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
04166     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
04167   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
04168     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
04169   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
04170     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
04171   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
04172     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
04173 
04174   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
04175     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
04176   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
04177     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
04178   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
04179     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
04180   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
04181     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
04182 
04183   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
04184     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
04185   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
04186     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
04187   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
04188     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
04189   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
04190     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
04191 
04192   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
04193     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
04194   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
04195     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
04196   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
04197     BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
04198   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
04199     BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
04200 
04201   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
04202     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
04203   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
04204     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
04205   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
04206     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
04207   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
04208     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
04209 
04210   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
04211     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
04212   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
04213     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
04214   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
04215     BB = EmitAtomicBinary(MI, BB, false, 0);
04216   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
04217     BB = EmitAtomicBinary(MI, BB, true, 0);
04218 
04219   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
04220            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
04221     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
04222 
04223     unsigned dest   = MI->getOperand(0).getReg();
04224     unsigned ptrA   = MI->getOperand(1).getReg();
04225     unsigned ptrB   = MI->getOperand(2).getReg();
04226     unsigned oldval = MI->getOperand(3).getReg();
04227     unsigned newval = MI->getOperand(4).getReg();
04228 
04229     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
04230     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
04231     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
04232     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
04233     F->insert(It, loop1MBB);
04234     F->insert(It, loop2MBB);
04235     F->insert(It, midMBB);
04236     F->insert(It, exitMBB);
04237     exitMBB->transferSuccessors(BB);
04238 
04239     //  thisMBB:
04240     //   ...
04241     //   fallthrough --> loopMBB
04242     BB->addSuccessor(loop1MBB);
04243 
04244     // loop1MBB:
04245     //   l[wd]arx dest, ptr
04246     //   cmp[wd] dest, oldval
04247     //   bne- midMBB
04248     // loop2MBB:
04249     //   st[wd]cx. newval, ptr
04250     //   bne- loopMBB
04251     //   b exitBB
04252     // midMBB:
04253     //   st[wd]cx. dest, ptr
04254     // exitBB:
04255     BB = loop1MBB;
04256     BuildMI(BB, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
04257       .addReg(ptrA).addReg(ptrB);
04258     BuildMI(BB, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
04259       .addReg(oldval).addReg(dest);
04260     BuildMI(BB, TII->get(PPC::BCC))
04261       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
04262     BB->addSuccessor(loop2MBB);
04263     BB->addSuccessor(midMBB);
04264 
04265     BB = loop2MBB;
04266     BuildMI(BB, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
04267       .addReg(newval).addReg(ptrA).addReg(ptrB);
04268     BuildMI(BB, TII->get(PPC::BCC))
04269       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
04270     BuildMI(BB, TII->get(PPC::B)).addMBB(exitMBB);
04271     BB->addSuccessor(loop1MBB);
04272     BB->addSuccessor(exitMBB);
04273     
04274     BB = midMBB;
04275     BuildMI(BB, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
04276       .addReg(dest).addReg(ptrA).addReg(ptrB);
04277     BB->addSuccessor(exitMBB);
04278 
04279     //  exitMBB:
04280     //   ...
04281     BB = exitMBB;
04282   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
04283              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
04284     // We must use 64-bit registers for addresses when targeting 64-bit,
04285     // since we're actually doing arithmetic on them.  Other registers
04286     // can be 32-bit.
04287     bool is64bit = PPCSubTarget.isPPC64();
04288     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
04289 
04290     unsigned dest   = MI->getOperand(0).getReg();
04291     unsigned ptrA   = MI->getOperand(1).getReg();
04292     unsigned ptrB   = MI->getOperand(2).getReg();
04293     unsigned oldval = MI->getOperand(3).getReg();
04294     unsigned newval = MI->getOperand(4).getReg();
04295 
04296     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
04297     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
04298     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
04299     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
04300     F->insert(It, loop1MBB);
04301     F->insert(It, loop2MBB);
04302     F->insert(It, midMBB);
04303     F->insert(It, exitMBB);
04304     exitMBB->transferSuccessors(BB);
04305 
04306     MachineRegisterInfo &RegInfo = F->getRegInfo();
04307     const TargetRegisterClass *RC = 
04308       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
04309                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
04310     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
04311     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
04312     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
04313     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
04314     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
04315     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
04316     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
04317     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
04318     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
04319     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
04320     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
04321     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
04322     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
04323     unsigned Ptr1Reg;
04324     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
04325     //  thisMBB:
04326     //   ...
04327     //   fallthrough --> loopMBB
04328     BB->addSuccessor(loop1MBB);
04329 
04330     // The 4-byte load must be aligned, while a char or short may be
04331     // anywhere in the word.  Hence all this nasty bookkeeping code.
04332     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
04333     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
04334     //   xori shift, shift1, 24 [16]
04335     //   rlwinm ptr, ptr1, 0, 0, 29
04336     //   slw newval2, newval, shift
04337     //   slw oldval2, oldval,shift
04338     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
04339     //   slw mask, mask2, shift
04340     //   and newval3, newval2, mask
04341     //   and oldval3, oldval2, mask
04342     // loop1MBB:
04343     //   lwarx tmpDest, ptr
04344     //   and tmp, tmpDest, mask
04345     //   cmpw tmp, oldval3
04346     //   bne- midMBB
04347     // loop2MBB:
04348     //   andc tmp2, tmpDest, mask
04349     //   or tmp4, tmp2, newval3
04350     //   stwcx. tmp4, ptr
04351     //   bne- loop1MBB
04352     //   b exitBB
04353     // midMBB:
04354     //   stwcx. tmpDest, ptr
04355     // exitBB:
04356     //   srw dest, tmpDest, shift
04357     if (ptrA!=PPC::R0) {
04358       Ptr1Reg = RegInfo.createVirtualRegister(RC);
04359       BuildMI(BB, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
04360         .addReg(ptrA).addReg(ptrB);
04361     } else {
04362       Ptr1Reg = ptrB;
04363     }
04364     BuildMI(BB, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
04365         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
04366     BuildMI(BB, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
04367         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
04368     if (is64bit)
04369       BuildMI(BB, TII->get(PPC::RLDICR), PtrReg)
04370         .addReg(Ptr1Reg).addImm(0).addImm(61);
04371     else
04372       BuildMI(BB, TII->get(PPC::RLWINM), PtrReg)
04373         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
04374     BuildMI(BB, TII->get(PPC::SLW), NewVal2Reg)
04375         .addReg(newval).addReg(ShiftReg);
04376     BuildMI(BB, TII->get(PPC::SLW), OldVal2Reg)
04377         .addReg(oldval).addReg(ShiftReg);
04378     if (is8bit)
04379       BuildMI(BB, TII->get(PPC::LI), Mask2Reg).addImm(255);
04380     else {
04381       BuildMI(BB, TII->get(PPC::LI), Mask3Reg).addImm(0);
04382       BuildMI(BB, TII->get(PPC::ORI), Mask2Reg).addReg(Mask3Reg).addImm(65535);
04383     }
04384     BuildMI(BB, TII->get(PPC::SLW), MaskReg)
04385         .addReg(Mask2Reg).addReg(ShiftReg);
04386     BuildMI(BB, TII->get(PPC::AND), NewVal3Reg)
04387         .addReg(NewVal2Reg).addReg(MaskReg);
04388     BuildMI(BB, TII->get(PPC::AND), OldVal3Reg)
04389         .addReg(OldVal2Reg).addReg(MaskReg);
04390 
04391     BB = loop1MBB;
04392     BuildMI(BB, TII->get(PPC::LWARX), TmpDestReg)
04393         .addReg(PPC::R0).addReg(PtrReg);
04394     BuildMI(BB, TII->get(PPC::AND),TmpReg).addReg(TmpDestReg).addReg(MaskReg);
04395     BuildMI(BB, TII->get(PPC::CMPW), PPC::CR0)
04396         .addReg(TmpReg).addReg(OldVal3Reg);
04397     BuildMI(BB, TII->get(PPC::BCC))
04398         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
04399     BB->addSuccessor(loop2MBB);
04400     BB->addSuccessor(midMBB);
04401 
04402     BB = loop2MBB;
04403     BuildMI(BB, TII->get(PPC::ANDC),Tmp2Reg).addReg(TmpDestReg).addReg(MaskReg);
04404     BuildMI(BB, TII->get(PPC::OR),Tmp4Reg).addReg(Tmp2Reg).addReg(NewVal3Reg);
04405     BuildMI(BB, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
04406         .addReg(PPC::R0).addReg(PtrReg);
04407     BuildMI(BB, TII->get(PPC::BCC))
04408       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
04409     BuildMI(BB, TII->get(PPC::B)).addMBB(exitMBB);
04410     BB->addSuccessor(loop1MBB);
04411     BB->addSuccessor(exitMBB);
04412     
04413     BB = midMBB;
04414     BuildMI(BB, TII->get(PPC::STWCX)).addReg(TmpDestReg)
04415       .addReg(PPC::R0).addReg(PtrReg);
04416     BB->addSuccessor(exitMBB);
04417 
04418     //  exitMBB:
04419     //   ...
04420     BB = exitMBB;
04421     BuildMI(BB, TII->get(PPC::SRW),dest).addReg(TmpReg).addReg(ShiftReg);
04422   } else {
04423     assert(0 && "Unexpected instr type to insert");
04424   }
04425 
04426   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
04427   return BB;
04428 }
04429 
04430 //===----------------------------------------------------------------------===//
04431 // Target Optimization Hooks
04432 //===----------------------------------------------------------------------===//
04433 
04434 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
04435                                              DAGCombinerInfo &DCI) const {
04436   TargetMachine &TM = getTargetMachine();
04437   SelectionDAG &DAG = DCI.DAG;
04438   switch (N->getOpcode()) {
04439   default: break;
04440   case PPCISD::SHL:
04441     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
04442       if (C->getZExtValue() == 0)   // 0 << V -> 0.
04443         return N->getOperand(0);
04444     }
04445     break;
04446   case PPCISD::SRL:
04447     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
04448       if (C->getZExtValue() == 0)   // 0 >>u V -> 0.
04449         return N->getOperand(0);
04450     }
04451     break;
04452   case PPCISD::SRA:
04453     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
04454       if (C->getZExtValue() == 0 ||   //  0 >>s V -> 0.
04455           C->isAllOnesValue())    // -1 >>s V -> -1.
04456         return N->getOperand(0);
04457     }
04458     break;
04459     
04460   case ISD::SINT_TO_FP:
04461     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
04462       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
04463         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
04464         // We allow the src/dst to be either f32/f64, but the intermediate
04465         // type must be i64.
04466         if (N->getOperand(0).getValueType() == MVT::i64 &&
04467             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
04468           SDValue Val = N->getOperand(0).getOperand(0);
04469           if (Val.getValueType() == MVT::f32) {
04470             Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
04471             DCI.AddToWorklist(Val.getNode());
04472           }
04473             
04474           Val = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Val);
04475           DCI.AddToWorklist(Val.getNode());
04476           Val = DAG.getNode(PPCISD::FCFID, MVT::f64, Val);
04477           DCI.AddToWorklist(Val.getNode());
04478           if (N->getValueType(0) == MVT::f32) {
04479             Val = DAG.getNode(ISD::FP_ROUND, MVT::f32, Val, 
04480                               DAG.getIntPtrConstant(0));
04481             DCI.AddToWorklist(Val.getNode());
04482           }
04483           return Val;
04484         } else if (N->getOperand(0).getValueType() == MVT::i32) {
04485           // If the intermediate type is i32, we can avoid the load/store here
04486           // too.
04487         }
04488       }
04489     }
04490     break;
04491   case ISD::STORE:
04492     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
04493     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
04494         !cast<StoreSDNode>(N)->isTruncatingStore() &&
04495         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
04496         N->getOperand(1).getValueType() == MVT::i32 &&
04497         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
04498       SDValue Val = N->getOperand(1).getOperand(0);
04499       if (Val.getValueType() == MVT::f32) {
04500         Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
04501         DCI.AddToWorklist(Val.getNode());
04502       }
04503       Val = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Val);
04504       DCI.AddToWorklist(Val.getNode());
04505 
04506       Val = DAG.getNode(PPCISD::STFIWX, MVT::Other, N->getOperand(0), Val,
04507                         N->getOperand(2), N->getOperand(3));
04508       DCI.AddToWorklist(Val.getNode());
04509       return Val;
04510     }
04511     
04512     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
04513     if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
04514         N->getOperand(1).getNode()->hasOneUse() &&
04515         (N->getOperand(1).getValueType() == MVT::i32 ||
04516          N->getOperand(1).getValueType() == MVT::i16)) {
04517       SDValue BSwapOp = N->getOperand(1).getOperand(0);
04518       // Do an any-extend to 32-bits if this is a half-word input.
04519       if (BSwapOp.getValueType() == MVT::i16)
04520         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BSwapOp);
04521 
04522       return DAG.getNode(PPCISD::STBRX, MVT::Other, N->getOperand(0), BSwapOp,
04523                          N->getOperand(2), N->getOperand(3),
04524                          DAG.getValueType(N->getOperand(1).getValueType()));
04525     }
04526     break;
04527   case ISD::BSWAP:
04528     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
04529     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
04530         N->getOperand(0).hasOneUse() &&
04531         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
04532       SDValue Load = N->getOperand(0);
04533       LoadSDNode *LD = cast<LoadSDNode>(Load);
04534       // Create the byte-swapping load.
04535       std::vector<MVT> VTs;
04536       VTs.push_back(MVT::i32);
04537       VTs.push_back(MVT::Other);
04538       SDValue MO = DAG.getMemOperand(LD->getMemOperand());
04539       SDValue Ops[] = {
04540         LD->getChain(),    // Chain
04541         LD->getBasePtr(),  // Ptr
04542         MO,                // MemOperand
04543         DAG.getValueType(N->getValueType(0)) // VT
04544       };
04545       SDValue BSLoad = DAG.getNode(PPCISD::LBRX, VTs, Ops, 4);
04546 
04547       // If this is an i16 load, insert the truncate.  
04548       SDValue ResVal = BSLoad;
04549       if (N->getValueType(0) == MVT::i16)
04550         ResVal = DAG.getNode(ISD::TRUNCATE, MVT::i16, BSLoad);
04551       
04552       // First, combine the bswap away.  This makes the value produced by the
04553       // load dead.
04554       DCI.CombineTo(N, ResVal);
04555 
04556       // Next, combine the load away, we give it a bogus result value but a real
04557       // chain result.  The result value is dead because the bswap is dead.
04558       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
04559       
04560       // Return N so it doesn't get rechecked!
04561       return SDValue(N, 0);
04562     }
04563     
04564     break;
04565   case PPCISD::VCMP: {
04566     // If a VCMPo node already exists with exactly the same operands as this
04567     // node, use its result instead of this node (VCMPo computes both a CR6 and
04568     // a normal output).
04569     //
04570     if (!N->getOperand(0).hasOneUse() &&
04571         !N->getOperand(1).hasOneUse() &&
04572         !N->getOperand(2).hasOneUse()) {
04573       
04574       // Scan all of the users of the LHS, looking for VCMPo's that match.
04575       SDNode *VCMPoNode = 0;
04576       
04577       SDNode *LHSN = N->getOperand(0).getNode();
04578       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
04579            UI != E; ++UI)
04580         if (UI->getOpcode() == PPCISD::VCMPo &&
04581             UI->getOperand(1) == N->getOperand(1) &&
04582             UI->getOperand(2) == N->getOperand(2) &&
04583             UI->getOperand(0) == N->getOperand(0)) {
04584           VCMPoNode = *UI;
04585           break;
04586         }
04587       
04588       // If there is no VCMPo node, or if the flag value has a single use, don't
04589       // transform this.
04590       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
04591         break;
04592         
04593       // Look at the (necessarily single) use of the flag value.  If it has a 
04594       // chain, this transformation is more complex.  Note that multiple things
04595       // could use the value result, which we should ignore.
04596       SDNode *FlagUser = 0;
04597       for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 
04598            FlagUser == 0; ++UI) {
04599         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
04600         SDNode *User = *UI;
04601         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
04602           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
04603             FlagUser = User;
04604             break;
04605           }
04606         }
04607       }
04608       
04609       // If the user is a MFCR instruction, we know this is safe.  Otherwise we
04610       // give up for right now.
04611       if (FlagUser->getOpcode() == PPCISD::MFCR)
04612         return SDValue(VCMPoNode, 0);
04613     }
04614     break;
04615   }
04616   case ISD::BR_CC: {
04617     // If this is a branch on an altivec predicate comparison, lower this so
04618     // that we don't have to do a MFCR: instead, branch directly on CR6.  This
04619     // lowering is done pre-legalize, because the legalizer lowers the predicate
04620     // compare down to code that is difficult to reassemble.
04621     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
04622     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
04623     int CompareOpc;
04624     bool isDot;
04625     
04626     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
04627         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
04628         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
04629       assert(isDot && "Can't compare against a vector result!");
04630       
04631       // If this is a comparison against something other than 0/1, then we know
04632       // that the condition is never/always true.
04633       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
04634       if (Val != 0 && Val != 1) {
04635         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
04636           return N->getOperand(0);
04637         // Always !=, turn it into an unconditional branch.
04638         return DAG.getNode(ISD::BR, MVT::Other, 
04639                            N->getOperand(0), N->getOperand(4));
04640       }
04641     
04642       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
04643       
04644       // Create the PPCISD altivec 'dot' comparison node.
04645       std::vector<MVT> VTs;
04646       SDValue Ops[] = {
04647         LHS.getOperand(2),  // LHS of compare
04648         LHS.getOperand(3),  // RHS of compare
04649         DAG.getConstant(CompareOpc, MVT::i32)
04650       };
04651       VTs.push_back(LHS.getOperand(2).getValueType());
04652       VTs.push_back(MVT::Flag);
04653       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, VTs, Ops, 3);
04654       
04655       // Unpack the result based on how the target uses it.
04656       PPC::Predicate CompOpc;
04657       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
04658       default:  // Can't happen, don't crash on invalid number though.
04659       case 0:   // Branch on the value of the EQ bit of CR6.
04660         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
04661         break;
04662       case 1:   // Branch on the inverted value of the EQ bit of CR6.
04663         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
04664         break;
04665       case 2:   // Branch on the value of the LT bit of CR6.
04666         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
04667         break;
04668       case 3:   // Branch on the inverted value of the LT bit of CR6.
04669         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
04670         break;
04671       }
04672 
04673       return DAG.getNode(PPCISD::COND_BRANCH, MVT::Other, N->getOperand(0),
04674                          DAG.getConstant(CompOpc, MVT::i32),
04675                          DAG.getRegister(PPC::CR6, MVT::i32),
04676                          N->getOperand(4), CompNode.getValue(1));
04677     }
04678     break;
04679   }
04680   }
04681   
04682   return SDValue();
04683 }
04684 
04685 //===----------------------------------------------------------------------===//
04686 // Inline Assembly Support
04687 //===----------------------------------------------------------------------===//
04688 
04689 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
04690                                                        const APInt &Mask,
04691                                                        APInt &KnownZero, 
04692                                                        APInt &KnownOne,
04693                                                        const SelectionDAG &DAG,
04694                                                        unsigned Depth) const {
04695   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
04696   switch (Op.getOpcode()) {
04697   default: break;
04698   case PPCISD::LBRX: {
04699     // lhbrx is known to have the top bits cleared out.
04700     if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
04701       KnownZero = 0xFFFF0000;
04702     break;
04703   }
04704   case ISD::INTRINSIC_WO_CHAIN: {
04705     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
04706     default: break;
04707     case Intrinsic::ppc_altivec_vcmpbfp_p:
04708     case Intrinsic::ppc_altivec_vcmpeqfp_p:
04709     case Intrinsic::ppc_altivec_vcmpequb_p:
04710     case Intrinsic::ppc_altivec_vcmpequh_p:
04711     case Intrinsic::ppc_altivec_vcmpequw_p:
04712     case Intrinsic::ppc_altivec_vcmpgefp_p:
04713     case Intrinsic::ppc_altivec_vcmpgtfp_p:
04714     case Intrinsic::ppc_altivec_vcmpgtsb_p:
04715     case Intrinsic::ppc_altivec_vcmpgtsh_p:
04716     case Intrinsic::ppc_altivec_vcmpgtsw_p:
04717     case Intrinsic::ppc_altivec_vcmpgtub_p:
04718     case Intrinsic::ppc_altivec_vcmpgtuh_p:
04719     case Intrinsic::ppc_altivec_vcmpgtuw_p:
04720       KnownZero = ~1U;  // All bits but the low one are known to be zero.
04721       break;
04722     }        
04723   }
04724   }
04725 }
04726 
04727 
04728 /// getConstraintType - Given a constraint, return the type of
04729 /// constraint it is for this target.
04730 PPCTargetLowering::ConstraintType 
04731 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
04732   if (Constraint.size() == 1) {
04733     switch (Constraint[0]) {
04734     default: break;
04735     case 'b':
04736     case 'r':
04737     case 'f':
04738     case 'v':
04739     case 'y':
04740       return C_RegisterClass;
04741     }
04742   }
04743   return TargetLowering::getConstraintType(Constraint);
04744 }
04745 
04746 std::pair<unsigned, const TargetRegisterClass*> 
04747 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
04748                                                 MVT VT) const {
04749   if (Constraint.size() == 1) {
04750     // GCC RS6000 Constraint Letters
04751     switch (Constraint[0]) {
04752     case 'b':   // R1-R31
04753     case 'r':   // R0-R31
04754       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
04755         return std::make_pair(0U, PPC::G8RCRegisterClass);
04756       return std::make_pair(0U, PPC::GPRCRegisterClass);
04757     case 'f':
04758       if (VT == MVT::f32)
04759         return std::make_pair(0U, PPC::F4RCRegisterClass);
04760       else if (VT == MVT::f64)
04761         return std::make_pair(0U, PPC::F8RCRegisterClass);
04762       break;
04763     case 'v': 
04764       return std::make_pair(0U, PPC::VRRCRegisterClass);
04765     case 'y':   // crrc
04766       return std::make_pair(0U, PPC::CRRCRegisterClass);
04767     }
04768   }
04769   
04770   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
04771 }
04772 
04773 
04774 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
04775 /// vector.  If it is invalid, don't add anything to Ops. If hasMemory is true
04776 /// it means one of the asm constraint of the inline asm instruction being
04777 /// processed is 'm'.
04778 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, char Letter,
04779                                                      bool hasMemory,
04780                                                      std::vector<SDValue>&Ops,
04781                                                      SelectionDAG &DAG) const {
04782   SDValue Result(0,0);
04783   switch (Letter) {
04784   default: break;
04785   case 'I':
04786   case 'J':
04787   case 'K':
04788   case 'L':
04789   case 'M':
04790   case 'N':
04791   case 'O':
04792   case 'P': {
04793     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
04794     if (!CST) return; // Must be an immediate to match.
04795     unsigned Value = CST->getZExtValue();
04796     switch (Letter) {
04797     default: assert(0 && "Unknown constraint letter!");
04798     case 'I':  // "I" is a signed 16-bit constant.
04799       if ((short)Value == (int)Value)
04800         Result = DAG.getTargetConstant(Value, Op.getValueType());
04801       break;
04802     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
04803     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
04804       if ((short)Value == 0)
04805         Result = DAG.getTargetConstant(Value, Op.getValueType());
04806       break;
04807     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
04808       if ((Value >> 16) == 0)
04809         Result = DAG.getTargetConstant(Value, Op.getValueType());
04810       break;
04811     case 'M':  // "M" is a constant that is greater than 31.
04812       if (Value > 31)
04813         Result = DAG.getTargetConstant(Value, Op.getValueType());
04814       break;
04815     case 'N':  // "N" is a positive constant that is an exact power of two.
04816       if ((int)Value > 0 && isPowerOf2_32(Value))
04817         Result = DAG.getTargetConstant(Value, Op.getValueType());
04818       break;
04819     case 'O':  // "O" is the constant zero. 
04820       if (Value == 0)
04821         Result = DAG.getTargetConstant(Value, Op.getValueType());
04822       break;
04823     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
04824       if ((short)-Value == (int)-Value)
04825         Result = DAG.getTargetConstant(Value, Op.getValueType());
04826       break;
04827     }
04828     break;
04829   }
04830   }
04831   
04832   if (Result.getNode()) {
04833     Ops.push_back(Result);
04834     return;
04835   }
04836   
04837   // Handle standard constraint letters.
04838   TargetLowering::LowerAsmOperandForConstraint(Op, Letter, hasMemory, Ops, DAG);
04839 }
04840 
04841 // isLegalAddressingMode - Return true if the addressing mode represented
04842 // by AM is legal for this target, for a load/store of the specified type.
04843 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
04844                                               const Type *Ty) const {
04845   // FIXME: PPC does not allow r+i addressing modes for vectors!
04846   
04847   // PPC allows a sign-extended 16-bit immediate field.
04848   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
04849     return false;
04850   
04851   // No global is ever allowed as a base.
04852   if (AM.BaseGV)
04853     return false;
04854   
04855   // PPC only support r+r, 
04856   switch (AM.Scale) {
04857   case 0:  // "r+i" or just "i", depending on HasBaseReg.
04858     break;
04859   case 1:
04860     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
04861       return false;
04862     // Otherwise we have r+r or r+i.
04863     break;
04864   case 2:
04865     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
04866       return false;
04867     // Allow 2*r as r+r.
04868     break;
04869   default:
04870     // No other scales are supported.
04871     return false;
04872   }
04873   
04874   return true;
04875 }
04876 
04877 /// isLegalAddressImmediate - Return true if the integer value can be used
04878 /// as the offset of the target addressing mode for load / store of the
04879 /// given type.
04880 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
04881   // PPC allows a sign-extended 16-bit immediate field.
04882   return (V > -(1 << 16) && V < (1 << 16)-1);
04883 }
04884 
04885 bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
04886   return false; 
04887 }
04888 
04889 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
04890   // Depths > 0 not supported yet! 
04891   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
04892     return SDValue();
04893 
04894   MachineFunction &MF = DAG.getMachineFunction();
04895   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
04896 
04897   // Just load the return address off the stack.
04898   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
04899 
04900   // Make sure the function really does not optimize away the store of the RA
04901   // to the stack.
04902   FuncInfo->setLRStoreRequired();
04903   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
04904 }
04905 
04906 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
04907   // Depths > 0 not supported yet! 
04908   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
04909     return SDValue();
04910   
04911   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
04912   bool isPPC64 = PtrVT == MVT::i64;
04913   
04914   MachineFunction &MF = DAG.getMachineFunction();
04915   MachineFrameInfo *MFI = MF.getFrameInfo();
04916   bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects()) 
04917                   && MFI->getStackSize();
04918 
04919   if (isPPC64)
04920     return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::X31 : PPC::X1,
04921       MVT::i64);
04922   else
04923     return DAG.getCopyFromReg(DAG.getEntryNode(), is31 ? PPC::R31 : PPC::R1,
04924       MVT::i32);
04925 }
04926 
04927 bool
04928 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
04929   // The PowerPC target isn't yet aware of offsets.
04930   return false;
04931 }